import * as claimOrderService from '../../../services/quality/co/claimOrders';
import * as itemDetailService from '../../../services/item/itemDetail';
import * as supplierDetailService from '../../../services/supplier/suppliers';
import * as edDetailService from '../../../services/quality/ed/ed';
import * as bpmService from '../../../services/common/bpm';
import { routerRedux } from 'dva/router';
import { stringUtils, dataUtils, enums } from '@utils';
import pathToRegexp from 'path-to-regexp';
import { Modal,message } from 'antd';
const { customMsg, viewMode, entType, compsMode, dutyMode, taskResult } = enums;

export default {
  namespace: 'claimOrderDetail',
  state: {
    formData: {},
    mode: 'view',
    total: 0,
    advice: '',
    supplier: {},
    doc8D: {},
    recpModalVisible: false,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/cooperate/quality/co/:id').exec(location.pathname);
        if (match) {
          if (match[1] === 'create') {
            const doc8DId = stringUtils.queryURL('8d');
            dispatch({ type: 'clean' });
            dispatch({ type: 'create', payload: { doc8DId } });
          } else {
            dispatch({ type: 'clean' });
            dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
            dispatch({ type: 'querySingle', payload: { id: match[1] } });
          }
        }
      })
    },
  },

  effects: {
    * querySingle({ payload }, { call, put, select }) {
      const { mode } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const { supplier } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const data = yield call(claimOrderService.getSingle, payload.id);
      let modeCfg = mode;
      if (data.success) {
        // 过滤viewMode
        if (data.data.prcId) {
          modeCfg = mode === viewMode.APPROVE ? viewMode.EDIT : viewMode.VIEW;
        } else {
          modeCfg = supplier.supplier ? viewMode.VIEW :
            ((mode === viewMode.CREATE || mode === viewMode.UPDATE) ? viewMode.CREATE : viewMode.VIEW);
        }
        // 判断登录用户是否为当前处理人
        if (data.data.prcId && mode !== viewMode.VIEW) {
          const status = yield call(bpmService.doCheckActived, data.data.prcId);
          if (!(status.success && status.data)) {
            Modal.error({ title: customMsg.NOT_ACTIVE_HANDLER });
            modeCfg = viewMode.VIEW;
          }
        }

        // 初始配置文件参数
        const defId = data.data.defId ? data.data.defId : 'StatementOfClaim:';
        const nodeId = modeCfg === viewMode.VIEW ? mode : (data.data.prcId ? data.data.taskKey : 'initiator');
        const params = {
          defId,
          nodeId: nodeId ? nodeId : modeCfg,
          mode: modeCfg,
        };
        // 拉去远程文件配置
        const cfgData = yield call(bpmService.getFormCfg, params);
        if (cfgData.success) {
          yield put({
            type: 'updateState',
            payload: {
              remoteCfg: cfgData.data,
            },
          });
        } else {
          throw cfgData;
        }

        // 初始化 放大镜组件
        const formData = data.data;
        formData.ouName = { id: formData.ouId, name: formData.ouName, code: formData.ouCode }; // 公司
        formData.suppName = { id: formData.suppId, name: formData.suppName, code: formData.suppCode }; // 供应商

        yield put({
          type: 'updateState',
          payload: {
            mode,
            formData,
          },
        });
      } else {
        throw data;
      }
    },

    * create({ payload }, { call, put, select, all }) {
      let { doc8D } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const { supplier, formData } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      let mode = supplier.supplier ? viewMode.VIEW : viewMode.CREATE;
      const newFormData = { attachRepo: dataUtils.getRandomInt(1, 9999999) };
      const { doc8DId } = payload;
      if (doc8DId) {
        // 拉取 8D报告信息
        const doc8Data = yield call(edDetailService.getSingle, doc8DId);
        if (doc8Data.success && doc8Data.data) {
          doc8D = Object.assign({}, doc8Data.data);
          const { id, reportCode, dutyType, suppId } = doc8D;
          // 供应商责任
          if (dutyType === dutyMode.DUTY_MODE_SUPP) {
            // 拉取 供应商信息
            const data = yield call(supplierDetailService.getSingle, suppId);
            if (data.success) {
              const { edpPbSupp } = data.data;
              newFormData['docId8D'] = id;
              newFormData['docNo8D'] = reportCode;
              newFormData['suppId'] = edpPbSupp.id;
              newFormData['suppName'] = { id: edpPbSupp.id, code: edpPbSupp.suppCode, name: edpPbSupp.suppName };
              newFormData['suppCode'] = edpPbSupp.suppCode;
              newFormData['currId'] = edpPbSupp.currId;
              newFormData['currName'] = edpPbSupp.currName;
              newFormData['contPerson'] = edpPbSupp.bussPic;
              newFormData['contTel'] = edpPbSupp.bussPicTel;
            } else {
              throw data;
            }
          } else {
            Modal.error({ title: customMsg.CLAIM_DUTY_ENT }); // 内部责任不能创建索赔单
            mode = viewMode.VIEW;
          }
        }
      }

      // 拉去远程配置文件
      const params = {
        defId: 'StatementOfClaim:',
        nodeId: 'initiator',
        mode,
      };
      const cfgData = yield call(bpmService.getFormCfg, params);
      if (cfgData.success) {
        yield put({
          type: 'updateState',
          payload: {
            doc8D,
            mode,
            formData: newFormData,
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw cfgData;
      }
    },


    * save({ payload }, { call, put, select, all }) {
      const { formData, advice } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const { submitted, type } = payload;
      const { items } = formData;

      const newFormData = Object.assign({}, formData);
      newFormData.items = Object.assign([], items);
      newFormData.submitted = submitted; // 是否提交到工作流
      if (newFormData.compsMode === compsMode.COMPS_MODE_MONEY) {
        newFormData.items = [];
      } else if (newFormData.compsMode === compsMode.COMPS_MODE_ITEM) {
        newFormData.mcu = null;
        newFormData.amt = '';
      }
      if(type && type !== taskResult.APPROVED && !advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(claimOrderService.update, newFormData);
      if (data.success) {
        if (type) {
          const flowUri = type === taskResult.APPROVED ? bpmService.doApprove :
            (type === taskResult.REJECTED ? bpmService.doReject : bpmService.doDisabled);
          const result = yield call(flowUri, { taskId: newFormData.taskId, advice });
          if (result.success) {
            yield put({ type: 'cancel' });
          } else {
            throw result;
          }
        } else {
          yield put({ type: 'cancel' });
        }
      } else {
        throw data;
      }
    },

    * updateMaterial({ payload }, { call, put, select, all }) {
      const { formData } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const { items } = formData;
      const { index, value } = payload;
      const newList = items.slice().filter(item => item.itemId);
      if (value) {
        for (let i of value) {
          const data = yield call(itemDetailService.getSingle, i.id);
          if (data.success) {
            let newItem = {
              id : data.data.id,
              itemId : data.data.id,
              itemCode : data.data.outerCode,
              itemName : data.data.itemName,
              spec : data.data.spec,
              uomName : data.data.uomName
            };
            let hasItem = newList.find((item, index) => {
              if (item.itemId === newItem.itemId) {
                newList[index] = newItem;
              }
              return item.itemId === newItem.itemId
            });
            if (!hasItem) {
              newList.push({ ...newItem });
            }
          } else {
            throw data;
          }
        }
      } else {
        newList[index] = { id: dataUtils.getRandomInt(-99999999, -1), price: 0 };
      }
      formData.items = newList;
      yield put({
        type: 'updateState',
        payload: {
          formData,
        }
      });
    },

    * updateFormData({ payload }, { call, put, select }) {
      const { formData } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      const { key, value } = payload;

      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      if (key === 'suppName') {
        if (value.id) {
          const data = yield call(supplierDetailService.getSingle, value.id);
          if (data.success) {
            const { edpPbSupp } = data.data;
            newFormData['suppId'] = value.id;
            newFormData['suppCode'] = edpPbSupp.suppCode;
            newFormData['currId'] = edpPbSupp.currId;
            newFormData['currName'] = edpPbSupp.currName;
            newFormData['contPerson'] = edpPbSupp.bussPic;
            newFormData['contTel'] = edpPbSupp.bussPicTel;
          } else {
            throw data;
          }
        } else {
          newFormData['suppName'] = '';
          newFormData['suppId'] = '';
          newFormData['suppCode'] = '';
          newFormData['currId'] = '';
          newFormData['currName'] = '';
          newFormData['contPerson'] = '';
          newFormData['contTel'] = '';
        }
        // 如果更新供应商，则清空物料列表
        if (newFormData.items) {
          newFormData.items = [];
        }
      } else if (key === 'ouName') {
        if (value.id) {
          newFormData['ouId'] = value.id;
        } else {
          newFormData['ouName'] = '';
          newFormData['ouId'] = '';
        }
        newFormData['mcu'] = '';
      }

      yield put({
        type: 'updateState',
        payload: {
          formData: newFormData,
        },
      });
    },

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

    * clean({ payload }, { call, put, select }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'view',
          total: 0,
          advice: '',
          doc8D: {},
          attachRepo: '',
          supplier: {
            supplier: user.entType === entType.SUPP,
            suppName: user.name,
          },
          recpModalVisible: false,
        },
      });
    },

    * confirm({ payload }, { call, put, select }) {
      const { advice, formData } = yield select(({ claimOrderDetail }) => claimOrderDetail);
      // if(!advice.trim()){
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(claimOrderService.qualityCheck, formData.id);
      if (data.success) {
        if (data.data) {
          const result = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
          if (result.success) {
            yield put({ type: 'cancel' });
          } else {
            throw result;
          }
        } else {
          Modal.error({ title: '索赔物料并未完全入库，不能确认通过' });
        }
      } else {
        throw data;
      }
    },

  },

  reducers: {
    addRow(state, { payload }) {
      const { formData, total } = state;
      const items = formData.items || [];
      const newList = items.slice();
      payload.price = 0; // 初始单价为0
      payload.lineNo = (items.length ? items.length : 0) + 1;
      newList.push(payload);
      formData.items = newList;
      return {
        ...state,
        formData,
        total: total + 1,
      };
    },

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

    updateCell(state, { payload }) {
      const { formData } = state;
      const { items } = formData;
      const newList = items.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;

      // 计算单行总价
      if (key === 'qty' || key === 'price') {
        const qty = newList[index]['qty'] || 0;
        const price = newList[index]['price'] || 0;
        const total = qty * price;
        newList[index]['amt'] = total.toFixed(2);
      }
      return {
        ...state,
        items: newList,
      };
    },

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

    updateAdvice(state, { payload }) {
      const { value } = payload;
      let advice = state.advice;
      advice = value;
      return {
        ...state,
        advice,
      };
    },

    showRecpModal(state, { payload }) {
      return { ...state, ...payload, recpModalVisible: true };
    },

    hideRecpModal(state, { payload }) {
      return { ...state, ...payload, recpModalVisible: false };
    },

  },
}
