import axios from "@/utils/request";
import { deepClone } from "../../utils";

/* 状态 */
const state = {
  copilot: {
    /* 产量驾驶舱 */
    yield: {
      ftoInvest: null,
      chipInvest: null,
      chipOutput: null,
      stdOutput: null,
      bipvOutput: null,
    },
    /* 能源驾驶舱 */
    energy: {},
    /* 效率驾驶舱 */
    efficiency: {
      chipOee: {
        current: [],
        previous: [],
      },
      transformRate: {
        current: [],
        previous: [],
      },
      chipRate: {
        target: [],
        current: [],
        previous: [],
        outputNumber:[],
      },
      stdRate: {
        target: [],
        current: [],
        outputNumber:[]
      },
    },
  },
  home: {
    /** 主页状态 */
    ftoInvest: null,
    chipInvest: null,
    chipOutput: null,
    stdOutput: null,
    bipvOutput: null,
  },
};

const mutations = {
  SET_HOME_INFO: (state, payload) => {
    state.home.ftoInvest = payload.ftoInvest;
    state.home.chipInvest = payload.chipInvest;
    state.home.chipOutput = payload.chipOutput;
    state.home.stdOutput = payload.stdOutput;
    state.home.bipvOutput = payload.bipvOutput;
  },
  SET_COPILOT_INFO: (state, { type, payload }) => {
    switch (type) {
      case "yield":
        state.copilot.yield.ftoInvest = payload.ftoInvest;
        state.copilot.yield.chipInvest = payload.chipInvest;
        state.copilot.yield.chipOutput = payload.chipOutput;
        state.copilot.yield.stdOutput = payload.stdOutput;
        state.copilot.yield.bipvOutput = payload.bipvOutput;
        break;
      case "energy":
        state.copilot.energy = payload.data;
        break;
      case "efficiency":
        console.log('222222', payload)
        state.copilot.efficiency.chipOee = payload.chipOee;
        state.copilot.efficiency.transformRate = payload.transformRate;
        state.copilot.efficiency.chipRate = payload.chipRate;
        state.copilot.efficiency.stdRate = payload.stdRate;
        break;
    }
  },
};

const actions = {
  /** 初始化首页数据 */
  async initHome({ commit }) {
    const dataArr = await getHomeInfo();
    const targetArr = await getHomeInfo();
    const payload = splitCurrentAndPrevious(dataArr.prodOutputResultDO, targetArr.prodTargetDO);
    commit("SET_HOME_INFO", payload);
  },
  /** 初始化驾驶舱数据 */
  async initCopilot({ commit }, { period, source }) {
    if (source == "comprehensive") return;

    const fetcher = {
      yield: getCopilotYield,
      comprehensive: getCopilotEnergy,
      efficiency: getCopilotEfficiency,
    }[source];
    const handler = {
      yield: splitCurrentAndPrevious,
      comprehensive: () => null,
      efficiency: splitCurrentAndPreviousA,
    }[source]
    console.log(handler)
    // 获取产量数据
    // console.log('qqqqqq',handler)
    let { data: factoryList, type } = await fetcher(period)
    console.log(factoryList,type);
    let targetList = null;
    if (source === "yield" || source === "efficiency") {
      // 获取目标数据
      let { data } = await fetcher(period, true)
      // console.log('11111',data)
      targetList = data
    }
    let factoryData = factoryList.prodOutputResultDO ? factoryList.prodOutputResultDO : factoryList.prodOutputRateDO
    let targetData = targetList.prodTargetDO ? targetList.prodTargetDO : targetList.prodTargetDO
    const payload = handler(factoryData, targetData)
    commit("SET_COPILOT_INFO", { type, payload });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};

function splitCurrentAndPreviousA(factoryListResponse, targetListResponse) {
  console.log('工厂',targetListResponse);
  // console.log('工厂',factoryListResponse);

  // 初始数据
  const { chipOee, transformRate, chipRate, stdRate } = initA();
  // factoryListResponse = [
  //   {
  //     factory: 0,
  //     oee: 0.8,
  //     previousYearOee: 0.7,
  //     componentConversionEfficiency: 0.8,
  //     previousYearComponentConversionEfficiency: 0.7,
  //     glassType: 0,
  //     yieldRate: 0.8,
  //     previousYearYieldRate: 0.7,
  //     chipYieldRate: 0.38,
  //     componentYieldRate: 0.73,
  //   },
  //   {
  //     factory: 1,
  //     oee: 0.8,
  //     previousYearOee: 0.7,
  //     componentConversionEfficiency: 0.8,
  //     previousYearComponentConversionEfficiency: 0.7,
  //     glassType: 1,
  //     yieldRate: 0.8,
  //     previousYearYieldRate: 0.7,
  //     chipYieldRate: 0.38,
  //     componentYieldRate: 0.73,
  //   },
  //   {
  //     factory: 2,
  //     oee: 0.8,
  //     previousYearOee: 0.7,
  //     componentConversionEfficiency: 0.8,
  //     previousYearComponentConversionEfficiency: 0.7,
  //     glassType: 1,
  //     yieldRate: 0.8,
  //     previousYearYieldRate: 0.7,
  //     chipYieldRate: 0.38,
  //     componentYieldRate: 0.73,
  //   },
  //   {
  //     factory: 3,
  //     oee: 0.8,
  //     previousYearOee: 0.7,
  //     componentConversionEfficiency: 0.8,
  //     previousYearComponentConversionEfficiency: 0.7,
  //     glassType: 0,
  //     yieldRate: 0.8,
  //     previousYearYieldRate: 0.7,
  //     chipYieldRate: 0.38,
  //     componentYieldRate: 0.73,
  //   },
  // ];
  if (factoryListResponse) {
    for (const factory of factoryListResponse) {
      const fId = getFactoryId(factory);
      // 获取目标值
      if (targetListResponse) {
        const {
          chipYieldRate,
          componentYieldRate,
          chipOee,
          componentConversionEfficiency,
          componentYield
        } = getFactoryTargetValueA(targetListResponse, fId);
        stdRate.target[fId] =  componentYieldRate
        chipRate.target[fId] = chipYieldRate
      }
      // 芯片OEE
      chipOee.current[fId] = factory.oee * 100 ;
      chipOee.previous[fId] = factory.previousYearOee * 100 ;
      // 转化效率
      transformRate.current[fId] =
        factory.componentConversionEfficiency * 100 ;
      transformRate.previous[fId] =
        factory.previousYearComponentConversionEfficiency * 100 ;
      // 芯片良率 与 标准组件良率
      if (![0, 1].includes(factory.glassType)) continue;
      const _t = [chipRate, stdRate][factory.glassType]
      console.log('_t',_t);
      _t.current[fId] = factory.yieldRate ;
      _t.previous[fId] = factory.previousYearYieldRate ;
    }

    return {
      chipOee,
      transformRate,
      chipRate,
      stdRate,
    };
  }
}

function splitCurrentAndPrevious(factoryListResponse, targetListResponse) {
  console.log('工厂',factoryListResponse);

  // 初始数据
  const { chipInvest, ftoInvest, chipOutput, stdOutput, bipvOutput } = init();
  if (factoryListResponse) {
    for (const factory of factoryListResponse) {

      const fId = getFactoryId(factory);
      // 获取目标值
      if (targetListResponse) {
        const { chipYield, componentYield, bipvProductOutput } =
          getFactoryTargetValue(targetListResponse, fId);
        chipOutput.target[fId] = chipYield;
        stdOutput.target[fId] = componentYield;
        bipvOutput.target[fId] = bipvProductOutput;
      }
      // 芯片投入
      chipInvest.current[fId] = factory.inputNumber;
      chipInvest.previous[fId] = factory.previousYearInputNumber;
      // FTO投入
      ftoInvest.current[fId] = factory.chipInput;
      ftoInvest.previous[fId] = factory.previousYearChipInput;
      // 产出数据, 0 - (玻璃)芯片产出, 1 - 标准组件产出, 2 - BIPV产出
      // 因为后端写的垃圾数据,所以这里要做一下判断
      if (![0, 1, 2].includes(factory.glassType)) continue;
      const _t = [chipOutput, stdOutput, bipvOutput][factory.glassType];
      _t.current[fId] = factory.outputNumber;
      _t.previous[fId] = factory.previousYearOutputNumber;
      // debugger;
    }

    return {
      chipInvest,
      ftoInvest,
      chipOutput,
      stdOutput,
      bipvOutput,
    };
  }
}

function getFactoryId(factory) {
  return factory.factory;
}

function getFactoryTargetValue(targetList, factoryId) {
  const target = targetList.find((item) => item.factory === factoryId);
  if (target) {
    return {
      // 自带模拟数据了.... random_default
      chipYield: target.chipYield ?? random_default(),
      componentYield: target.componentYield ?? random_default(),
      bipvProductOutput: target.bipvProductOutput ?? random_default(),
    };
  }
  return {
    chipYield: random_default(),
    componentYield: random_default(),
    bipvProductOutput: random_default(),
  };
}

/**
 * 获取 芯片良率目标值 和 标准组件良率目标值
 * @param {*} targetList 目标值列表
 * @param {*} factoryId 工厂ID
 * @returns
 */
function getFactoryTargetValueA(targetList, factoryId) {
  const target = targetList.find((item) => item.factory === factoryId)
  if (target) {
    return {
      chipYieldRate: target.chipYieldRate ?? random_default(),
      componentYieldRate: target.componentYieldRate ?? random_default(),
      componentYield: target.componentYield ?? random_default(),
    };
  }
  return {
    chipYieldRate:0,
    componentYieldRate:0,
    componentYield:0 ,
  };
}

/**
 *
 * @returns 初始化 效率模块里 初始状态值
 */
function initA() {
  const t_ = {
    current: Array(7).fill(0),
    previous: Array(7).fill(0),
  };
  // 芯片OEE
  const chipOee = deepClone(t_);
  // 转化效率
  const transformRate = deepClone(t_);
  // 标准组件良率
  const stdRate = {
    ...deepClone(t_),
    target: Array(7).fill(0),
  };
  // 芯片良率
  const chipRate = deepClone(stdRate);
  return {
    chipOee,
    transformRate,
    chipRate,
    stdRate,
  };
}

/**
 *
 * @returns 初始化 产量模块里 初始状态值
 */
function init() {
  const t_ = {
    current: Array(7).fill(0),
    previous: Array(7).fill(0),
  };
  // 芯片投入
  const chipInvest = deepClone(t_);
  // FTO投入
  const ftoInvest = deepClone(t_);
  // 芯片产出
  const chipOutput = {
    ...deepClone(t_),
    target: Array(7).fill(0),
  };
  // 标准组件产出
  const stdOutput = deepClone(chipOutput);
  // BIPV产出
  const bipvOutput = deepClone(chipOutput);

  return {
    chipInvest, // 芯片投入
    ftoInvest, // FTO投入
    chipOutput, // 芯片产出
    stdOutput, // 标准组件产出
    bipvOutput, // BIPV产出
  };
}

function random_default(min = 0, max = 1) {
  // return 0;
  let a = Math.floor(Math.random() * max);
  while (a < min) {
    a = Math.floor(Math.random() * max);
  }
  return a;
}

/* 接口 */
async function getHomeInfo() {
  const { code, data } = await axios.post("ip/prod-output/cockpitData", {
    factorys: [],
    date: 4,
  });
  if (code == 0) {
    return data;
  }
  console.warn("getHomeInfo failed, code: ", code);
  return null;
}

async function getHomeTarget() {
  const { code, data } = await axios.post("/ip/prod-target/query-by-date", {
    factorys: [],
    date: 4,
  });
  if (code == 0) {
    return data;
  }
  console.warn("getHomeTarget failed, code: ", code);
  return null;
}

function getUrl(copilot_module) {
  let url = {
    // 对比数据的 URL
    comparison: "",
    // 目标数据的 URL
    target: "",
  };
  switch (copilot_module) {
    case "yield":
      url.comparison = "ip/prod-output/cockpitData";
      // url.target = "/ip/prod-target/query-by-date";
      break;
    case "energy":
      break;
    case "efficiency":
      url.comparison = "ip/prod-output/cockpitDataRate";
      // url.target = "/ip/prod-target/query-rate-target";
      break;
  }

  return url;
}

async function doFetch(copilot_module = "yield", fetch_target, params) {
  const url = getUrl(copilot_module);
  const { code, data } = await axios.post(
    url.comparison,
    {
      ...params,
    }
  );
  if (code == 0) {
    return data;
  }
  console.warn("[doFetch] failed, code: ", code);
  return null;
}

/**
 *
 * @param {*} period 日周月年1,2,3,4
 * @param {*} target 是否获取目标数据
 * @returns
 */
function getCopilotYield(period, target = false) {
  return getCopilotData("yield", period, target);
}

function getCopilotEnergy(period, target = false) {
  return getCopilotData("energy", period, target);
}

function getCopilotEfficiency(period, target = false) {
  return getCopilotData("efficiency", period, target);
}

/**
 *
 * @param {*} period 周期: 日周月年
 * @param {*} target 是否获取目标数据:默认 否
 * @returns
 */
async function getCopilotData(copilot_module, period, target = false) {
  if (!copilot_module) copilot_module = "yield";
  // 请求参数,直接一次性获取所有工厂
  let queryParams = {
    factorys: [],
    date: 4,
  };

  switch (period) {
    case "日":
      queryParams.date = 1;
      break;
    case "周":
      queryParams.date = 2;
      break;
    case "月":
      queryParams.date = 3;
      break;
    case "年":
      queryParams.date = 4;
      break;
    default:
      queryParams.date = 1;
      break;
  }

  return {
    data: await doFetch(copilot_module, target ? true : false, queryParams),
    type: copilot_module,
  };
}