import * as soaService from '../../../services/cooperate/finance/statementOfAccount';
import * as statementOfAccountService from '../../../services/cooperate/finance/statementOfAccount';
import { message } from 'antd';

export default {

  namespace: 'accountDetails',

  state: {
    detailList: [], // 对账明细
    detailTotal: 0,
    showDiff: false,
    showAccount: false,
    accountIds: [],
    queryDetails: null, // 该参数没用到
    saveDetails: null, // 查询条件 accountDetails.saveDetails = accountBillList.queryDetails
    limit: 10,
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      const { formData, mode } = yield select(({ accountBillList }) => accountBillList);
      if (mode === 'view' || (mode === 'approval' && formData.status !== '01')) {
        payload['id'] = formData.id;
      } else {
        const currentUser = yield select(({ app }) => app.user);
        const { formData } = yield select(({ accountBillList }) => accountBillList);
        payload['supplierId'] = currentUser.user.entId;
        payload['ouId'] = formData.ouId;
        payload['accountType'] = formData.accountType;
        payload['payFromDate'] = formData.payFromDate;
        payload['payToDate'] = formData.payToDate;
      }
      const data = yield call(soaService.queryDetails, payload);
      if (data.success) {

        // 初始化一些字段
        soaService.initialDetailInfo(data);

        yield put({
          type: 'updateState',
          payload: {
            accountIds: [],
            saveDetails: payload,
            detailList: data.data.rows,
            detailTotal: data.data.total,
          },
        });

      } else {
        throw data;
      }
    },

    //查看差异订单
    * showDiff({ payload }, { call, put, select }) {
      //const currentUser = yield select(({ app }) => app.user);
      //const { formData } = yield select(({ accountBillList }) => accountBillList);
      const { showDiff, saveDetails } = yield select(({ accountDetails }) => accountDetails);
      // if (!payload['id']) {
      //   payload['supplierId'] = currentUser.user.entId;
      //   payload['ouId'] = formData.ouId;
      // }
      !showDiff ? saveDetails['diffTypes'] = ['1', '2', '3'] : saveDetails['diffTypes'] = [];
      const data = yield call(soaService.queryDetails, saveDetails);
      if (data.success) {

        // 初始化一些字段
        soaService.initialDetailInfo(data);

        yield put({
          type: 'updateState',
          payload: {
            saveDetails,
            showDiff: !showDiff,
            detailList: data.data.rows,
            detailTotal: data.data.total,
          },
        });
      } else {
        throw data;
      }
    },

    //查看未对帐订单
    * showAccount({ payload }, { call, put, select }) {
      const { showAccount, saveDetails } = yield select(({ accountDetails }) => accountDetails);
      !showAccount ? saveDetails['isAccount'] = 1 : saveDetails['isAccount'] = 0;
      const data = yield call(soaService.queryDetails, saveDetails);
      if (data.success) {

        // 初始化一些字段
        soaService.initialDetailInfo(data);

        yield put({
          type: 'updateState',
          payload: {
            saveDetails,
            showAccount: !showAccount,
            detailList: data.data.rows,
            detailTotal: data.data.total,
          },
        });
      } else {
        throw data;
      }
    },

    //查看汇总明细
    * showSummaryDetails({ payload }, { call, put, select }) {
      const { saveDetails } = yield select(({ accountDetails }) => accountDetails);
      const data = yield call(soaService.queryDetails, { ...saveDetails, itemCode: payload.itemCode });
      if (data.success) {

        // 初始化一些字段
        soaService.initialDetailInfo(data);

        yield put({
          type: 'updateState',
          payload: {
            detailList: data.data.rows,
            detailTotal: data.data.total,
          },
        });
      } else {
        throw data;
      }
    },

    //查看明细
    * queryDetail({ payload }, { call, put, select }) {
      const { limit } = yield select(({ accountDetails }) => accountDetails);
      yield put({
        type: 'updateState',
        payload: {
          accountIds: payload.accountIds,
        },
      });
      // const currentUser = yield select(({ app }) => app.user);
      const { queryDetails } = yield select(({ accountBillList }) => accountBillList);

      // payload['supplierId'] = currentUser.user.entId;
      // payload['ouId'] = formData.ouId;
      payload['limit'] = limit;
      payload['offset'] = 0;
      const detail = Object.assign(queryDetails, payload);
      const data = yield call(soaService.queryDetails, detail);
      if (data.success) {

        // 初始化一些字段
        soaService.initialDetailInfo(data);

        yield put({
          type: 'updateState',
          payload: {
            saveDetails: detail,
            detailList: data.data.rows,
            detailTotal: data.data.total,
          },
        });
      } else {
        throw data;
      }

    },

    //单据列表 查看明细执行方法
    * changeSave({ payload }, { call, put, select }) {
      //先保存查询前的明细
      if (payload.limit) {
        yield put({
          type: 'updateState',
          payload: {
            limit: payload.limit,
          },
        });
      }
      // yield put({
      //   type: 'updateDetails',
      // });
      const detailList = yield select(({ accountDetails }) => accountDetails.detailList);
      const updateData = yield call(soaService.updateDetails, detailList);

      if (updateData.success) {
        //保存后查询新的数据
        const currentUser = yield select(({ app }) => app.user);
        const { formData } = yield select(({ accountBillList }) => accountBillList);
        const { accountIds, limit } = yield select(({ accountDetails }) => accountDetails);
        payload['supplierId'] = currentUser.user.entId;
        payload['ouId'] = formData.ouId;
        payload['accountType'] = formData.accountType;
        payload['payFromDate'] = formData.payFromDate;
        payload['payToDate'] = formData.payToDate;
        payload['limit'] = limit;
        if (accountIds.length) {
          payload['accountIds'] = accountIds;
        }
        const data = yield call(soaService.queryDetails, payload);
        if (data.success) {

          // 初始化一些字段
          soaService.initialDetailInfo(data);

          yield put({
            type: 'updateState',
            payload: {
              detailList: data.data.rows,
              detailTotal: data.data.total,
            },
          });
        } else {
          throw data;
        }
        //编辑时保存整单数据
        const { mode } = yield select(({ accountBillList }) => accountBillList);
        if (mode === 'update') {
          yield put({
            type: 'accountBillList/save',
          });

          // const diffData = yield call(soaService.isDiff, currentUser.user.entId, formData.ouId);
          // const relevantAmt = yield call(soaService.initial, currentUser.user.entId, formData.ouId);
          // if (diffData.success && relevantAmt.success) {
          //   const amt = relevantAmt.data.amt;
          //   const netAmt = relevantAmt.data.netAmt;
          //   const taxAmt = relevantAmt.data.taxAmt;
          //   yield put({
          //     type: 'accountBillList/updateState',
          //     payload: {
          //       formData: { ...formData, amt, amtStr: formatAmt(amt), netAmt, netAmtStr: formatAmt(netAmt), taxAmt, taxAmtStr: formatAmt(taxAmt), diffFlag: diffData.data > 0 ? '1' : '0' },
          //     }
          //   });
          //   yield put({
          //     type: 'accountBillList/save',
          //   });
          // } else {
          //   throw updateData;
          // }
        }
      }
    },

    * save({ }, { select, call, put }) {
      //const { index, row } = payload;
      // yield put({
      //   type: 'updateDetails',
      // });
      const { saveDetails } = yield select(({ accountDetails }) => accountDetails);

      //如果是新建，保存前进行一次校验，防止出现多次保存同期对账单
      const { mode } = yield select(({ accountBillList }) => accountBillList);
      if (mode === 'create') {
        const checkData = yield call(statementOfAccountService.isExistAccount, {
          suppId: saveDetails.supplierId,
          ouId: saveDetails.ouId,
          accountType: saveDetails.accountType
        });
        if (checkData.data > 0) {
          message.error("账期内已存在对账单，无法继续新建");
          return;
        }
      }

      const detailList = yield select(({ accountDetails }) => accountDetails.detailList);
      //const currentUser = yield select(({ app }) => app.user);
      // for (let i in detailList) {
      //   if (detailList[i].diffQty || detailList[i].diffPrice || detailList[i].differenceAmt) {
      //     detailList[i].accOver = 1;
      //   } else if (detailList[i].diffType == '0') {
      //     detailList[i].accOver = 1;
      //   } else {
      //     detailList[i].accOver = 0;
      //   }
      //   if (detailList[i].diffQty && detailList[i].diffQty != 0) {
      //     detailList[i].diffType = '1';
      //     if (detailList[i].diffPrice && detailList[i].diffPrice != 0) detailList[i].diffType = '3';
      //   } else if (detailList[i].diffPrice && detailList[i].diffPrice != 0) {
      //     detailList[i].diffType = '2';
      //   } else if (detailList[i].accOver == 0) {
      //     detailList[i].diffType = null;
      //   } else {
      //     detailList[i].diffType = '0';
      //   }
      // }
      //  const newData = { ...formUtils.standardiseFormData(row) };
      const data = yield call(soaService.updateDetails, detailList);
      if (data.success) {
        yield put({
          type: 'accountBillList/save',
          payload: saveDetails,
        });
      } else {
        throw data;
      }
    },

    * isAllAccount({ payload }, { call, put, select }) {
      const { saveDetails, accountIds } = yield select(({ accountDetails }) => accountDetails);
      const { formData } = yield select(({ accountBillList }) => accountBillList);
      const accStatus = payload.isAllAccount;

      const query = Object.assign(formData, saveDetails, { accOver: accStatus ? 1 : 0, accountIds: accountIds } );
      const data = yield call(soaService.updateAccOver, query);
      if (data.success) {
        yield put({
          type: 'queryDetail',
          payload: {
            accountIds: accountIds
          },
        });
      } else {
        throw data;
      }
    },
  },

  reducers: {
    updateCell(state, { payload }) {
      const { key, index, value } = payload;
      const { detailList } = state;
      const newList = detailList.slice();
      if (key === 'deliQty' || key === 'deliPrice') {
        newList[index][key] = value ? value : 0;
      } else {
        newList[index][key] = value;
      }

      if (key === 'deliQty') {
        //前端计算会出现误差
        newList[index].diffQty = parseFloat((newList[index].deliQty - newList[index].qty).toFixed(2));
        newList[index].deliAmt = parseFloat((newList[index].deliQty * newList[index].deliPrice).toFixed(2));
        newList[index].differenceAmt = parseFloat((newList[index].deliAmt - newList[index].amt).toFixed(2));

        // 更新差异类型
        soaService.updateDiffType(newList[index]);
      }
      if (key === 'deliPrice') {
        newList[index].diffPrice = parseFloat((newList[index].deliPrice - newList[index].price).toFixed(4));
        newList[index].deliAmt = parseFloat((newList[index].deliQty * newList[index].deliPrice).toFixed(2));
        newList[index].differenceAmt = parseFloat((newList[index].deliAmt - newList[index].amt).toFixed(2));

        // 更新差异类型
        soaService.updateDiffType(newList[index]);
      }
      return {
        ...state,
        detailList: newList,
      };
    },

    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    //更新对账明细
    updateDetails(state, { payload }) {
      const { detailList } = state;
      const newList = detailList.slice();
      if (!newList) {
        message.error('对账明细不存在');
        return;
      }
      for (let i in newList) {
        if (newList[i].diffQty || newList[i].diffPrice || newList[i].differenceAmt) {
          newList[i].accOver = 1;
        } else if (newList[i].diffType == '0') {
          newList[i].accOver = 1;
        } else {
          newList[i].accOver = 0;
        }
        if (newList[i].diffQty && newList[i].diffQty != 0) {
          newList[i].diffType = '1';
          if (newList[i].diffPrice && newList[i].diffPrice != 0) newList[i].diffType = '3';
        } else if (newList[i].diffPrice && newList[i].diffPrice != 0) {
          newList[i].diffType = '2';
        } else if (newList[i].accOver == 0) {
          newList[i].diffType = null;
        } else {
          newList[i].diffType = '0';
        }
      }
      return {
        ...state,
        detailList: newList,
      };
    },

    editable(state, { payload }) {
      const { index, value, row } = payload;
      const { detailList } = state;
      const newList = detailList.slice();
      if (value === '0') {
        newList[index] = Object.assign({}, row, { qeditable: false, peditable: false, teditable: true });
        newList[index].diffQty = null;
        newList[index].diffPrice = null;
        newList[index].diffType = '0';
      } else if (value === '1') {
        newList[index] = Object.assign({}, row, { qeditable: true, peditable: false, teditable: true, });
        newList[index].diffPrice = null;
        newList[index].diffRemark = null;
        newList[index].diffType = '1';
      } else if (value === '2') {
        newList[index] = Object.assign({}, row, { qeditable: false, peditable: true, teditable: false, });
        newList[index].diffQty = null;
        newList[index].diffRemark = null;
        newList[index].diffType = '2';
      }
      return {
        ...state,
        detailList: newList,
      };
    },

    isAccount(state, { payload }) {
      const { index, value, row } = payload;
      const { detailList } = state;
      const newList = detailList.slice();
      if (value) {
        newList[index].accOver = 1;
        newList[index].diffType = '0';
        newList[index].diffQty = 0;
        newList[index].deliQty = newList[index].qty;
        newList[index].diffPrice = 0;
        newList[index].deliPrice = newList[index].price;
        newList[index].differenceAmt = 0;
        newList[index].deliAmt = newList[index].amt;
        newList[index] = Object.assign({}, row, { editable: false });
      } else {
        newList[index].accOver = 0;
        newList[index].diffType = null;
        newList[index] = Object.assign({}, row, { editable: true });
      }
      return {
        ...state,
        detailList: newList,
      };
    },

  },

};
