import {
  getAddressDataAPI,
  getLogisticsDataAPI,
  getSettlementDataAPI,
  getPayforMainDataAPI,
  getInvoiceInfoDataAPI,
  getOrderCartDataAPI,
  sumbtOrderAPI,
  saveTempOrderAPI,
  promotionInfoAPI,
  occupyMnyTopLimitAPI,
  orderCreditCheckerAPI,
  setDefaultAddressAPI,
  getSupplierDataAPI,
  orderEditAPI,
  orderEditForCopyAPI,
  getProjectDataAPI,
  fillItemBomInfoAPI,
  getAccountPeriodInfoAPI
} from "../services/api";

import { getCustomer } from "@/utils/request.js";

export default {
  namespace: "orderEdit",

  state: {
    addressData: [],
    invoiceInfoData: [],
    orderCartData: [],
    supplierData: [],
    orderEditData: {},
    projectData: [],
    resultOrder:[]
  },

  effects: {
    // 获取供应商
    *getSupplierData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      payload.customer = getCustomer().id;
      const response = yield call(getSupplierDataAPI, payload);
      yield put({
        type: "supplierData",
        supplierData: response
      });
    },
    // 请求收货人地址
    *getAddressData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      payload.customer = getCustomer().id;
      const response = yield call(getAddressDataAPI, payload);
      if (response && Array.isArray(response)) {
        response.forEach(item => (item.isSelected = item.isDefault));
      }
      yield put({
        type: "addressData",
        addressData: response
      });
    },
    // 请求物流方式
    *getLogisticsData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      payload.customer = getCustomer().id;
      const response = yield call(getLogisticsDataAPI, payload);
      yield put({
        type: "logisticsData",
        logisticsData: response
      });
    },
    // 请求结算方式
    *getSettlementData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      const response = yield call(getSettlementDataAPI, payload);
      yield put({
        type: "settlementData",
        settlementData: response
      });
    },
    // 请求主表支付方式
    *getPayforMainData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      const response = yield call(getPayforMainDataAPI, payload);
      yield put({
        type: "payforMainData",
        payforMainData: response
      });
    },
    // 请求结发票信息
    *getInvoiceInfoData({ payload }, { call, put }) {
      payload = payload ? payload : {};
      payload.customer = getCustomer().id;
      const response = yield call(getInvoiceInfoDataAPI, payload);
      yield put({
        type: "invoiceInfoData",
        invoiceInfoData: response
      });
    },
    // 请求订单商品
    *getOrderCartData({ payload }, { call, put }) {
      const response = yield call(getOrderCartDataAPI, payload);
      yield put({
        type: "orderCartData",
        orderCartData: response.data || []
      });
    },
    // 暂存订单
    *saveTempOrder({ payload }, { call, put }) {
      const response = yield call(saveTempOrderAPI, payload);
      yield put({
        type: "resultOrder",
        resultOrder: response
      });
    },
    // 提交订单
    *submitOrder({ payload }, { call, put }) {
      const response = yield call(sumbtOrderAPI, payload);
      yield put({
        type: "resultOrder",
        resultOrder: response
      });
    },
    // 获取促销
    *getPromotionInfo({ payload }, { call, put }) {
      payload.customerId = getCustomer().id;
      const { saleOrgId, customerId, promotionStyle } = payload;
      if (promotionStyle) {
        payload.promotionStyle = promotionStyle.split(",");
      }
      const response = yield call(promotionInfoAPI, payload);
      yield put({
        type: "promotionInfoData",
        promotionInfoData: response
      });
      // 匹配促销后，再信用检测
      /*
      if (response && response.reqOrderItems) {
        const newReqOrderItems = response.reqOrderItems.concat([]);
        newReqOrderItems.forEach(item => {
          item.dealAmount =
            parseFloat(item.promPrice || "0") *
            parseFloat(item.mainNum || "0") - parseFloat(item.promAmount || "0");
        });
        yield put({
          type: "orderCreditChecker",
          payload: {
            saleOrgId: saleOrgId, // 销售组织
            customerId: customerId, // 客户
            reqOrderItems: newReqOrderItems
          }
        });
      }
      */
    },
    // 设置默认收获地址
    *setDefaultAddress({ payload }, { call, put }) {
      let response = yield call(setDefaultAddressAPI, payload);
      response = response || [];
      yield put({
        type: "addressData",
        addressData: response
      });
    },
    // 获取客户可用余额及冲抵比例
    *getOccupyMnyTopLimit({ payload }, { call, put }) {
      payload.customerId = getCustomer().id;
      let response = yield call(occupyMnyTopLimitAPI, payload);
      response = response || [];
      yield put({
        type: "occupyMnyTopLimits",
        occupyMnyTopLimits: response
      });
    },
    *orderCreditChecker({ payload }, { call, put }) {
      const response = yield call(orderCreditCheckerAPI, payload);
      yield put({
        type: "orderCredit",
        orderCredit: response || {}
      });
    },
    // 订单编辑
    *getOrderEditData({ payload }, { call, put }) {
      const response = yield call(orderEditAPI, payload);
      yield put({
        type: "orderEditData",
        orderEditData: response
      });
    },
    // 订单复制
    *getOrderEditDataForCopy({ payload }, { call, put }) {
      const response = yield call(orderEditForCopyAPI, payload);
      yield put({
        type: "orderEditData",
        orderEditData: response
      });
    },
    // 获取项目
    *getProjectData({ payload }, { call, put }) {
      const response = yield call(getProjectDataAPI, payload);
      const datas = (response || {}).content || [];
      yield put({
        type: "projectData",
        projectData: datas
      });
    },
    // 补充BOM信息
    *getItemBomInfo({ payload }, { call, put }) {
      const { reqOrderItems } = payload;
      const newReqOrderItems = [].concat(reqOrderItems);
      if (newReqOrderItems && newReqOrderItems.length > 0) {
        for (let i = 0; i < newReqOrderItems.length; i++) {
          const params = {
            parentGoodId: newReqOrderItems[i].goodsId
          };
          const response = yield call(fillItemBomInfoAPI, params);
          if (response && response.length > 0) {
            newReqOrderItems[i].reqOrderItemBoms = response[0].goodsBomChildren || [];
            if (response[0].goodsBomChildren) {
              const optionalBom = response[0].goodsBomChildren.find(item => item.isOptional == 1);
              if (optionalBom) {
                newReqOrderItems[i].isOptional = 1;
              }
            }
          }
        }
      }
      yield put({
        type: "orderCartData",
        orderCartData: newReqOrderItems
      });
    },
    // 匹配账期
    *getAccountPeriodInfo({ payload }, { call, put }) {
      if (payload && payload.saleModel) {
        switch (payload.saleModel) {
          case "01":
            payload.orderType = "GeneralSale";
            break;
          case "02":
            payload.orderType = "SaleReturn";
            break;
          case "03":
            payload.orderType = "FeeGoodsSubsidy";
            break;
          default:
            break;
        }
      }
      const response = yield call(getAccountPeriodInfoAPI, payload);
      yield put({
        type: "accountPeriodInfo",
        accountPeriodInfo: response
      });
    },
  },

  reducers: {
    supplierData(state, payload) {
      return {
        ...state,
        supplierData: payload.supplierData
      };
    },
    addressData(state, payload) {
      return {
        ...state,
        addressData: payload.addressData
      };
    },
    logisticsData(state, payload) {
      return {
        ...state,
        logisticsData: payload.logisticsData
      };
    },
    settlementData(state, payload) {
      return {
        ...state,
        settlementData: payload.settlementData
      };
    },
    payforMainData(state, payload) {
      return {
        ...state,
        payforMainData: payload.payforMainData
      };
    },
    invoiceInfoData(state, payload) {
      return {
        ...state,
        invoiceInfoData: payload.invoiceInfoData
      };
    },
    orderCartData(state, payload) {
      return {
        ...state,
        orderCartData: payload.orderCartData
      };
    },
    resultOrder(state, payload) {
      return {
        ...state,
        resultOrder: payload.resultOrder
      };
    },
    orderEditData(state, payload) {
      return {
        ...state,
        orderEditData: payload.orderEditData
      };
    },
    /*orderCustfeeData(state, payload) {
      return {
        ...state,
        orderCustfeeData: payload.orderCustfeeData
      };
    },*/
    occupyMnyTopLimits(state, payload) {
      return {
        ...state,
        occupyMnyTopLimits: payload.occupyMnyTopLimits
      };
    },
    orderCredit(state, payload) {
      return {
        ...state,
        orderCredit: payload.orderCredit
      };
    },
    promotionInfoData(state, payload) {
      return {
        ...state,
        promotionInfoData: payload.promotionInfoData
      };
    },
    projectData(state, payload) {
      return {
        ...state,
        projectData: payload.projectData
      };
    },
    accountPeriodInfo(state, payload) {
      return {
        ...state,
        accountPeriodInfo: payload.accountPeriodInfo
      };
    },
  }
};
