import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as bpmService from '../../../services/common/bpm';
import * as soaService from '../../../services/cooperate/finance/statementOfAccount';
import * as statementOfAccountService from '../../../services/cooperate/finance/statementOfAccount';
import { dataUtils, formUtils } from '../../../utils';
import { numberUtils } from '@utils';

export default {

  namespace: 'accountBillList',

  state: {
    formData: {},
    mode: 'create',
    list: [],
    total: 0,
    listSummary: {},
    advice: '',
    summaryList: [], // 汇总明细
    viewSummary: false,
    modalVisible: false,
    modalItem: [],
    remoteCfg: null,
    queryDetails: null, // 查询参数
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/cooperate/finance/soa/:id').exec(location.pathname);
        if (match) {
          if (match[1] === 'create') {
            dispatch({ type: 'clean' });
            const ouId = dataUtils.queryStringToJSON(location.search).ouId;
            const accountType = dataUtils.queryStringToJSON(location.search).accountType;
            dispatch({ type: 'newCreate', payload: { ouId, accountType } });
            return 0;
          }
          if (match[1] === 'view' || match[1] === 'update' || match[1] === 'approval') {
            dispatch({ type: 'clean' });
            const id = dataUtils.queryStringToJSON(location.search).id;
            dispatch({ type: 'initWithForm', payload: { id, mode: match[1] } });
            return 0;
          }
          // dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          // debugger;
          // dispatch({ type: 'query', payload: match[1] });

        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      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.queryBillList, payload);
      if (data.success) {
        const summaryData = yield call(soaService.queryBillListSummary, payload);
        if (data.success) {
          const listSummary = summaryData.data;
          listSummary.amtStr = numberUtils.round_half_up_format(listSummary.amt, 2);
          listSummary.netAmtStr = numberUtils.round_half_up_format(listSummary.netAmt, 2);
          listSummary.taxAmtStr = numberUtils.round_half_up_format(listSummary.taxAmt, 2);
          listSummary.totalQtyStr = numberUtils.round_half_up_format(listSummary.totalQty, 2);
          yield put({
            type: 'updateState',
            payload: {
              queryDetails: payload,
              list: data.data.rows,
              total: data.data.total,
              listSummary: listSummary,
            },
          });
        } else {
          throw data;
        }
      } else {
        throw data;
      }
    },

    * newCreate({ payload }, { call, put, select }) {
      const currentUser = yield select(({ app }) => app.user);
      const { ouId,accountType } = payload;
      const data = yield call(soaService.initial, {suppId:currentUser.user.entId, ouId,accountType});
      const formData = data.data;
      const params = {
        defId: 'AccountCheck:2:416975',
        nodeId: 'initiator',
        mode: 'create',
      };
      const cfgData = yield call(soaService.remoteCfg, params);
      if (data.success) {
        formData.amtStr = numberUtils.round_half_up_format(formData.amt, 2);
        formData.netAmtStr = numberUtils.round_half_up_format(formData.netAmt, 2);
        formData.taxAmtStr = numberUtils.round_half_up_format(formData.taxAmt, 2);
        formData.supp = formData.suppCode + formData.suppName;
        formData.contact = (formData.contPerson || '') + (formData.bcontactTel || '');
        formData.fcontact = (formData.fcontactPerson || '') + (formData.fcontactTel || '');
        formData.payDate = formData.payFromDate + '—' + formData.payToDate;
        yield put({
          type: 'updateState',
          payload: {
            formData: formData,
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw data;
      }
    },

    * initWithForm({ payload }, { call, put, select }) {
      let { id, mode } = payload;
      const data = yield call(soaService.getSingle, id);
      const formData = data.data;
      if (mode === 'approval') {
        const status = yield call(bpmService.doCheckActived, data.data.prcId);
        if (status.success) {
          if (!status.data) {
            Modal.error({
              title: '您不是当前处理人',
              okText: '确认'
            });
            mode = 'view';
          }
        }
      }
      const params = {
        defId: 'AccountCheck:2:416975',
        nodeId: 'initiator',
        mode: mode === 'update' ? 'edit' : mode,
      };
      const cfgData = yield call(soaService.remoteCfg, params);
      if (data.success) {
        formData.amtStr = numberUtils.round_half_up_format(formData.amt, 2);
        formData.netAmtStr = numberUtils.round_half_up_format(formData.netAmt, 2);
        formData.taxAmtStr = numberUtils.round_half_up_format(formData.taxAmt, 2);
        formData.supp = formData.suppCode + formData.suppName;
        formData.contact = (formData.contPerson || '') + (data.data.bcontactTel || '');
        formData.fcontact = (formData.fcontactPerson || '') + (data.data.fcontactTel || '');
        formData.payDate = formData.payFromDate + '—' + formData.payToDate;
        yield put({
          type: 'updateState',
          payload: {
            formData: formData,
            mode,
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw data;
      }
    },

    * save({ payload }, { select, call, put }) {
      //检查明细行是否有值
      const detailTotal = yield select(({ accountDetails }) => accountDetails.detailTotal);
      if (detailTotal <= 0) {
        message.error('对账明细不存在，不能新建');
        return;
      }
      //保存整单
      const formData = yield select(({ accountBillList }) => accountBillList.formData);
      const newData = {
        ...formUtils.standardiseFormData(formData),
      };
      const data = yield call(soaService.save, Object.assign(newData, payload));
      if (data.success) {
        //新增时跳转界面
        const { mode } = yield select(({ accountBillList }) => accountBillList);
        if (mode === 'create') {
          yield put(routerRedux.replace(`/cooperate/finance/soa/update?id=${data.data.id}`));
        } else {
          data.data.amtStr = numberUtils.round_half_up_format(data.data.amt, 2);
          data.data.netAmtStr = numberUtils.round_half_up_format(data.data.netAmt, 2);
          data.data.taxAmtStr = numberUtils.round_half_up_format(data.data.taxAmt, 2);
          data.data.supp = data.data.suppCode + data.data.suppName;
          data.data.contact = (data.data.contPerson || '') + (data.data.bcontactTel || '');
          data.data.fcontact = (data.data.fcontactPerson || '') + (data.data.fcontactTel || '');
          data.data.payDate = data.data.payFromDate + '—' + data.data.payToDate;
          yield put({
            type: 'updateState',
            payload: {
              formData: data.data
            },
          });
        }
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },

    * submit({ payload }, { select, call, put }) {
      const detailTotal = yield select(({ accountDetails }) => accountDetails.detailTotal);
      if (detailTotal <= 0) {
        message.error('对账明细不存在，不能新建');
        return;
      }

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

      if (saveDetailResult.success) {
        const formData = yield select(({ accountBillList }) => accountBillList.formData);
        const newData = {
          ...formUtils.standardiseFormData(formData),
        };
        const data = yield call(soaService.submit, newData);
        if (data.success) {
          yield put(routerRedux.goBack());
        } else {
          throw data;
        }
      } else {
        throw saveDetailResult;
      }
    },

    * approve({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ accountBillList }) => accountBillList);
      // if(!advice.trim()){
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      if (data.success) {
        yield put(routerRedux.push('/cooperate/finance/soa'));
      } else {
        throw data;
      }
    },

    * reject({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ accountBillList }) => accountBillList);
      if(!advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      if (data.success) {
        yield put(routerRedux.push('/cooperate/finance/soa'));
      } else {
        throw data;
      }
    },

    * redirect({ payload }, { put }) {
      yield put(routerRedux.goBack());
    },

    * cancel({ payload }, { put }) {
      yield put({ type: 'clean' });
      yield put({ type: 'redirect' });
    },

    * viewSummary({ payload }, { select, call, put }) {
      //  const currentUser = yield select(({ app }) => app.user);
      const viewSummary = yield select(({ accountBillList }) => accountBillList.viewSummary);
      //  const supplierId = currentUser.user.entId;
      const { saveDetails } = yield select(({ accountDetails }) => accountDetails);
      const data = yield call(soaService.querySummary, saveDetails);
      if (data.success) {
        for (let i in data.data) {
          data.data[i].item = (data.data[i].itemCode || '') + (data.data[i].itemName || '') + '(' + (data.data[i].spec || '') + ')' + (data.data[i].uomDesc || '');
        }
        yield put({
          type: 'updateState',
          payload: {
            summaryList: data.data,
            viewSummary: !viewSummary,
          },
        });
      } else {
        throw data;
      }
    },

    * modal({ }, { call, put, select }) {
      const { formData } = yield select(({ accountBillList }) => accountBillList);
      const data = yield call(soaService.getAccountRecps, { docNo: formData.docNo });
      if (data.success) {
        yield put({
          type: 'showModal',
          payload: {
            modalItem: data.data,
          },
        });
      } else {
        throw data;
      }
    },

    * clean({ payload }, { put, select }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'create',
          list: [],
          total: 0,
          summaryList: [],
          modalVisible: false,
          viewSummary: false,
          remoteCfg: null,
          advice: '',
        },
      });
    },
  },

  reducers: {
    addRow(state, { payload }) {
      const { list, total } = state;
      const newList = list.slice();
      // newList.unshift(payload)
      newList.push(payload);
      return {
        ...state,
        list: newList,
      };
    },

    showModal(state: object, { payload }) {
      return { ...state, ...payload, modalVisible: true };
    },

    hideModal(state: object, { payload }) {
      return {
        ...state, ...payload, modalVisible: false, modalItem: [],
      };
    },

    updateCell(state, { payload }) {
      console.log(payload);
      const { key, index, value } = payload;
      const { detailList } = state;
      const newList = detailList.slice();
      newList[index][key] = value;

      return {
        ...state,
        detailList: newList,
      };
    },

    deleteRow(state, { payload }) {
      const { list, total } = state;
      const newList = list.slice().filter((item) => item.id !== payload);
      return {
        ...state,
        list: newList,
      };
    },

    querySuccess(state, action) {
      const { list, total } = action.payload;
      return {
        ...state,
        list,
        total,
      };
    },

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

    updateForm(state, { payload }) {
      const { key, value } = payload;
      const formData = state.formData;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },
  },

};
