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 itemTrialService from '../../services/item/itemTrial';
import {dataUtils, enums, formUtils} from '../../utils';

const { item } = enums;

export default {

  namespace: 'itemTrial',

  state: {
    businessList: [], // 商务评估
    qualityList: [], // 品质评估
    supplierList: [], // 供应商
    mode: 'create',
    formData: {},
    advice: '',
    from: '',
    remoteCfg: null,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/item-mgmt/itemTrial/:id').exec(location.pathname);
        // console.log(match);
        if (match) {
          dispatch({ type: 'clean' });
          if (match[1] === 'newTrial') {
            const itemId = dataUtils.queryStringToJSON(location.search).itemId;
            dispatch({ type: 'querySingle', payload: { itemId, trial: 'newTrial' } });
          } else if (match[1] === 'trial') {
            const id = dataUtils.queryStringToJSON(location.search).id;
            dispatch({ type: 'querySingle', payload: { id, trial: 'trial' } });
          } else if (match[1] === 'viewTrial') {
            const id = dataUtils.queryStringToJSON(location.search).id;
            dispatch({ type: 'querySingle', payload: { id, trial: 'viewTrial' } });
          } else if (match[1] === 'view') {
            const id = dataUtils.queryStringToJSON(location.search).id;
            dispatch({ type: 'querySingle', payload: { id, trial: 'view' } });
          } else {
            dispatch({ type: 'querySingle', payload: { id: match[1], trial: 'approve' } });
          }
        }
      });
    },
  },

  effects: {
    * querySingle({ payload }, { call, put, select }) {
      // 拉去远程配置
      let params;
      let data;
      let from = '';
      if (payload && payload.trial === 'approve') {
        data = yield call(itemTrialService.getSingle, payload.id);
        const status = yield call(bpmService.doCheckActived, data.data.prcId);
        if (status.success) {
          if (status.data) {
            params = {
              defId: 'SuppliperItem:6:141513',
              nodeId: data.data.taskKey,
              mode: 'edit',
            };
          } else {
            Modal.error({
              title: '您不是当前处理人',
              okText: '确认'
            });
            const { menu } = yield select(({ app }) => app);
            const isTrial = menu.map((m) => m.menuUrl).find((n) => n === '/item-mgmt/itemAccess');
            isTrial ?
              params = {
                defId: 'SuppliperItem:6:141513',
                nodeId: 'initiator',
                mode: 'view',
              } : params = {
                defId: 'SuppliperItem:6:141513',
                nodeId: 'sampleByTrialDepartment',
                mode: 'view',
              };
          }
        }
      } else if (payload && payload.trial === 'trial') {
        data = yield call(itemTrialService.getSingle, payload.id);
        from = 'trial';
        params = {
          defId: 'SuppliperItem:6:141513',
          nodeId: data.data.taskKey,
          mode: 'edit',
        };
      } else if (payload && payload.trial === 'newTrial') {
        data = yield call(itemTrialService.newTrial, payload.itemId);
        from = 'newTrial';
        params = {
          defId: 'SuppliperItem:6:141513',
          nodeId: 'initiator',
          mode: 'create',
        };
      } else if (payload && payload.trial === 'viewTrial') {
        data = yield call(itemTrialService.getSingle, payload.id);
        from = 'trial';
        params = {
          defId: 'SuppliperItem:6:141513',
          nodeId: 'sampleByTrialDepartment',
          mode: 'view',
        };
      } else if (payload && payload.trial === 'view') {
        data = yield call(itemTrialService.getSingle, payload.id);
        params = {
          defId: 'SuppliperItem:6:141513',
          nodeId: 'initiator',
          mode: 'view',
        };
      }
      const cfgData = yield call(itemTrialService.remoteCfg, params);
      if (data.success) {
        const { businessList, qualityList, supplierList, ...formData } = data.data;
        formData.btOrg = formData.btOrg || formData.orgId
        formData.repItemName = { id: formData.repItemId, code: formData.repItemCode, name: formData.repItemId ? `${formData.repItemName}(${formData.repItemCode})` : formData.repItemName };
        formData.cccCode = formData.c1Code ? [formData.c1Code, formData.c2Code, formData.c3Code] : [];
        formData.cccCodeName = formData.c1Code ? [formData.c1Name, formData.c2Name, formData.c3Name].join(' / ') : '';
        const business = [{
          testItem: '经营规范和信用度评估(14分)',
        }, {
          testItem: '生产可靠性及产能评估(10分)',
        }, {
          testItem: '仓储、运输能力评估(8分)',
        }, {
          testItem: '业务服务能力评估(5分)',
        }, {
          testItem: '相对成本及成本表现评估(3分)',
        }];
        const quality = [{
          testItem: '原料控制(19分)',
        }, {
          testItem: '过程控制(18分)',
        }, {
          testItem: '仓储管理(10分)',
        }, {
          testItem: '产品检测(8分)',
        }, {
          testItem: '检查与改进(5分)',
        }];
        businessList.forEach((element, index) => {
          business[index] = { ...element, ...business[index] };
        });
        qualityList.forEach((element, index) => {
          quality[index] = { ...element, ...quality[index] };
        });
        formData.attacRepo = true;
        yield put({
          type: 'updateState',
          payload: {
            formData,
            businessList: business,
            qualityList: quality,
            supplierList,
            from,
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw data;
      }
    },

    * delete({ payload }, { call, put }) {
      const data = yield call(itemTrialService.remove, payload.id);
      if (data.success) {
        yield put(routerRedux.goBack());
      } else {
        throw data;
      }
    },

    * save({ payload }, { call, put, select }) {
      if (!payload.useOrg) {
        message.error('请选择试制部门再提交');
        return;
      }
      if (!payload.suppCenter) {
        message.error('请选择供货区域再提交');
        return;
      }
      if (payload.semiProduct !== '1') {
        if (payload.supplierList.length <= 0) {
          message.error('请选择供应商再提交');
          return;
        } else {
          let count = 0;
          payload.supplierList.forEach((supplier) => {
            if (!supplier.suppName) {
              message.error('请选择供应商再提交');
              count++;
              return;
            }
          });
          if (count > 0) {
            return;
          }
        }
        // 判断物料在品项中是否存在对应的数据
        const newSupplierList = yield call(itemTrialService.isExsit, { id: payload.id, itemId: payload.itemId });
        let count = 0;
        for (let i = 0; i < payload.supplierList.length; i++) {
          if (newSupplierList.data.includes(payload.supplierList[i].id)) {
            message.error('【' + payload.supplierList[i].suppName + '】与该物料关系已存在，请重新选择');
            count++;
            return;
          }
        }
        if (count > 0) {
          return;
        }
      }
      payload.submitted = true; // 是否提交到工作流
      payload.repItemId = payload.repItemName && payload.repItemName.id;
      payload.repItemName = null;
      const data = yield call(itemTrialService.create, { ...formUtils.standardiseFormData(payload) });
      if (data.success) {
        yield put(routerRedux.goBack());
      } else {
        throw data;
      }
    },

    * update({ payload }, { select, call, put }) {
      const id = yield select(({ itemTrial }) => itemTrial.currentItem.id);
      const newData = { ...formUtils.standardiseFormData(payload), id };
      const data = yield call(itemTrialService.update, newData);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * updateSupp({ payload }, { select, call, put }) {
      let data, count = 0;
      const { supplierList } = yield select(({ itemTrial }) => itemTrial);
      supplierList.forEach((supplier) => {
        if (supplier.suppName === payload.value.name) {
          message.error('供应商选择重复');
          count++;
          return;
        }
      });
      if (count > 0) {
        return;
      }
      if (payload.value.id) {
        data = yield call(itemTrialService.supplier, payload.value.id);
        supplierList[payload.index] = data.data;
      } else {
        supplierList[payload.index] = {};
      }
      yield put({
        type: 'updateState',
        payload: supplierList,
      });
    },

    * approve({ payload }, { put, call, select }) {
      const { formData, advice, businessList, qualityList, from } = yield select(({ itemTrial }) => itemTrial);
      payload.repItemId = payload.repItemName && payload.repItemName.id;
      payload.repItemName = null;
      if (formData.taskKey === 'sampleByTrialDepartment') {
        if (!formData.stDate) {
          message.error('测试日期必填');
          return;
        }
        if (!formData.stCount) {
          message.error('测试数量必填');
          return;
        }
        if (!formData.stEvaluateDate) {
          message.error('评估日期必填');
          return;
        }
        if (!formData.stResult) {
          message.error('测试结果必填');
          return;
        }
        if (formData.semiProduct === '1' && !formData.btOrg) {
          message.error('批测部门必填');
          return;
        }
        if (!formData.stOpinion) {
          message.error('综合意见必填');
          return;
        }
      }
      if (formData.taskKey === 'qualityAssuranceInfo' || formData.taskKey === 'qualityAssuranceConfirm') {
        if (!formData.itemName) {
          message.error('物料名称必填');
          return;
        }
        if (!formData.spec) {
          message.error('规格型号必填');
          return;
        }
        if (!formData.semiStore) {
          message.error('半成品库位必填');
          return;
        }
        if (!formData.uom) {
          message.error('主计量单位必填');
          return;
        }
        if (!formData.orderPeriod) {
          message.error('订货周期必填');
          return;
        }
        if (!formData.moq) {
          message.error('最小订货数量必填');
          return;
        }
        if (!formData.storeValueDays) {
          message.error('保质期必填');
          return;
        }
        if (!formData.stdLabCost) {
          message.error('标准人工必填');
          return;
        }
        if (!formData.stdProdCost) {
          message.error('标准制费必填');
          return;
        }
      }
      if (formData.taskKey === 'purchasingStaff') {
        let count = 0;
        for (let i = 0; i < businessList.length; i++) {
          if (businessList[i].itemScore != 0 && !businessList[i].itemScore) {
            message.error('得分数必填');
            count++;
            break;
          }
        }
        if (count > 0) {
          return;
        }
        if (!formData.cgOpinion) {
          message.error('采购部意见必填');
          return;
        }
        if (!formData.btOrg) {
          message.error('批测部门必填');
          return;
        }
      }
      if (formData.taskKey === 'qualityAssurance') {
        let count = 0;
        for (let i = 0; i < qualityList.length; i++) {
          if (qualityList[i].itemScore != 0 && !qualityList[i].itemScore) {
            message.error('得分数必填');
            count++;
            break;
          }
        }
        if (count > 0) {
          return;
        }
        if (!formData.jstlOpinion) {
          message.error('技术质量部意见必填');
          return;
        }
        // if (!formData.zycfOpinion) {
        //   message.error('中央厨房意见必填');
        //   return;
        // }
      }
      if (formData.taskKey === 'batchByTrialDepartment') {
        if (!formData.btCount) {
          message.error('批测数量必填');
          return;
        }
        if (!formData.btResult) {
          message.error('批测结果必填');
          return;
        }
        if (!formData.btOpinion) {
          message.error('批测意见必填');
          return;
        }
      }
      if (formData.taskKey === 'materialDepartmentConfirm') {
        if (!formData.whType) {
          message.error('仓库类型必填');
          return;
        }
        if (!formData.uom9) {
          message.error('报货单位必填');
          return;
        }
        if (!formData.whProp) {
          message.error('采购价格仓库必填');
          return;
        }
        if (!formData.distProp) {
          message.error('配送类型必填');
          return;
        }
      }
      if (formData.taskKey === 'financialDepartmentConfirm') {
        if (!formData.itemStakeType) {
          message.error('盘点类型必填');
          return;
        }
        if (formData.cccCode.length !== 3) {
          message.error(item.ERR_NO_C3CODE, 2);
          return;
        } else {
          formData.cccCode.map((code, index) => {
            payload['c' + (index + 1) + 'Code'] = code;
          });
        }
        if (!formData.glpt) {
          message.error('总账类必填');
          return;
        }
        if (!formData.taxCode) {
          message.error('税种必填');
          return;
        }
        if (!formData.taxRate) {
          message.error('税率(%)必填');
          return;
        }
        if (!formData.taxCodeInp) {
          message.error('采购应计税码必填');
          return;
        }
        if (!formData.taxRateOutp) {
          message.error('销项税率(%)必填');
          return;
        }
        if (!formData.taxCodeOutp) {
          message.error('应纳销售税码必填');
          return;
        }
      }
      if (formData.taskKey === 'informationDepartmentConfirm') {
        if (!formData.itemStakeType) {
          message.error('盘点类型必填');
          return;
        }
        if (!formData.whType) {
          message.error('仓库类型必填');
          return;
        }
        if (!formData.glpt) {
          message.error('总账类必填');
          return;
        }
        if (!formData.origin) {
          message.error('产地必填');
          return;
        }
        if (!formData.itemPrice) {
          message.error('含税单价必填');
          return;
        }
        if (!formData.uom) {
          message.error('主计量单位必填');
          return;
        }
        if (!formData.uom10) {
          message.error('消耗单位必填');
          return;
        }
        if (!formData.uom9) {
          message.error('报货单位必填');
          return;
        }
        if (!formData.storageMode) {
          message.error('存储方式必填');
          return;
        }
        if (!formData.taxCode) {
          message.error('税种必填');
          return;
        }
        if (!formData.orderPeriod) {
          message.error('订货周期必填');
          return;
        }
        if (!formData.storageCondition) {
          message.error('存储条件必填');
          return;
        }
        if (!formData.taxRate) {
          message.error('税率(%)必填');
          return;
        }
        if (!formData.taxCodeInp) {
          message.error('采购应计税码必填');
          return;
        }
        if (!formData.taxRateOutp) {
          message.error('销项税率(%)必填');
          return;
        }
        if (!formData.taxCodeOutp) {
          message.error('应纳销售税码必填');
          return;
        }
        if (!formData.whProp) {
          message.error('采购价格仓库必填');
          return;
        }
        if (!formData.distProp) {
          message.error('配送类型必填');
          return;
        }
        if (formData.innerBrand.length === 0) {
          message.error('内部品牌必填');
          return;
        }
        if (!formData.usage) {
          message.error('用途必填');
          return;
        }
      }
      if (formData.taskKey === 'semiMaterialDepartmentConfirm') {
        if (!formData.itemStakeType) {
          message.error('盘点类型必填');
          return;
        }
        if (!formData.whType) {
          message.error('仓库类型必填');
          return;
        }
        if (!formData.semiStore) {
          message.error('半成品库位必填');
          return;
        }
        if (!formData.origin) {
          message.error('产地必填');
          return;
        }
        if (!formData.uom10) {
          message.error('消耗单位必填');
          return;
        }
        if (!formData.uom9) {
          message.error('报货单位必填');
          return;
        }
        if (!formData.whProp) {
          message.error('采购价格仓库必填');
          return;
        }
        if (!formData.distProp) {
          message.error('配送类型必填');
          return;
        }
        if (formData.innerBrand.length === 0) {
          message.error('内部品牌必填');
          return;
        }
        if (!formData.usage) {
          message.error('用途必填');
          return;
        }
      }
      if (formData.taskKey === 'semiFinancialDepartmentConfirm') {
        if (formData.cccCode.length !== 3) {
          message.error(item.ERR_NO_C3CODE, 2);
          return;
        } else {
          formData.cccCode.map((code, index) => {
            payload['c' + (index + 1) + 'Code'] = code;
          });
        }
        if (!formData.glpt) {
          message.error('总账类必填');
          return;
        }
        if (!formData.taxCode) {
          message.error('税种必填');
          return;
        }
        if (!formData.taxRate) {
          message.error('税率(%)必填');
          return;
        }
        if (!formData.taxCodeInp) {
          message.error('采购应计税码必填');
          return;
        }
        if (!formData.taxRateOutp) {
          message.error('销项税率(%)必填');
          return;
        }
        if (!formData.taxCodeOutp) {
          message.error('应纳销售税码必填');
          return;
        }
      }
      // if ((payload.taskKey === 'purchasingManager' || payload.taskKey === 'qualityAssuranceInfo'
      //   || payload.taskKey === 'purchasingManagerConfirm' || payload.taskKey === 'purchasingDirectorConfirm'
      //   || payload.taskKey === 'materialDepartmentConfirm' || payload.taskKey === 'financialDepartmentConfirm'
      //   || payload.taskKey === 'informationDepartmentConfirm' || payload.taskKey === 'qualityAssuranceConfirm'
      //   || payload.taskKey === 'semiMaterialDepartmentConfirm' || payload.taskKey === 'semiFinancialDepartmentConfirm'
      //   || payload.taskKey === 'semiInformationDepartmentConfirm') && !advice.trim()) {
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(itemTrialService.create, { ...formUtils.standardiseFormData(payload) });
      if (data.success) {
        const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
        if (data.success) {
          yield put(routerRedux.goBack());
        } else {
          throw data;
        }
      } else {
        throw data;
      }
    },

    * reject({ payload }, { put, call, select }) {
      const { formData, advice, from } = yield select(({ itemTrial }) => itemTrial);
      payload.repItemId = payload.repItemName && payload.repItemName.id;
      payload.repItemName = null;
      if (payload.taskKey === 'financialDepartmentConfirm') {
        if (payload.cccCode.length !== 3) {
          message.error(item.ERR_NO_C3CODE, 2);
        } else {
          payload.cccCode.map((code, index) => {
            payload['c' + (index + 1) + 'Code'] = code;
          });
        }
      }
      if ((payload.taskKey === 'purchasingManager' || payload.taskKey === 'qualityAssuranceInfo'
        || payload.taskKey === 'purchasingManagerConfirm' || payload.taskKey === 'purchasingDirectorConfirm'
        || payload.taskKey === 'materialDepartmentConfirm' || payload.taskKey === 'financialDepartmentConfirm'
        || payload.taskKey === 'informationDepartmentConfirm' || payload.taskKey === 'qualityAssuranceConfirm'
        || payload.taskKey === 'semiMaterialDepartmentConfirm' || payload.taskKey === 'semiFinancialDepartmentConfirm'
        || payload.taskKey === 'semiInformationDepartmentConfirm') && !advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(itemTrialService.create, { ...formUtils.standardiseFormData(payload) });
      if (data.success) {
        yield call(bpmService.doReject, { taskId: formData.taskId, advice });
        yield put(routerRedux.goBack());
      } else {
        throw data;
      }
    },

    * transCHToEn({ payload }, { call, put }) {
      const data = yield call(itemTrialService.transCHToEn, { source: payload.value });
      if (data.success) {
        yield put({
          type: 'updateForm',
          payload: {
            key: payload.targetKey,
            value: data.data,
          },
        });
      }
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          businessList: [], // 商务评估
          qualityList: [], // 品质评估
          supplierList: [], // 供应商
          mode: 'create',
          formData: {},
          advice: '',
        },
      });
    },

    * cancel({ payload }, { put, select }) {
      yield put({ type: 'clean' });
      yield put(routerRedux.goBack());
    },
  },

  reducers: {
    addRow(state, { payload }) {
      const { supplierList } = state;
      const newList = supplierList.slice();
      newList.push(payload);
      return {
        ...state,
        supplierList: newList,
      };
    },

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

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

    updateCell(state, { payload }) {
      const { type, key, index, value } = payload;
      let newList = [];
      if (type === 'supplier') {
        const { supplierList } = state;
        newList = supplierList.slice();
        newList[index][key] = value;
        return {
          ...state,
          supplierList: newList,
        };
      } else if (type === 'business') {
        const { businessList } = state;
        newList = businessList.slice();
        newList[index][key] = value;
        return {
          ...state,
          businessList: newList,
        };
      } else if (type === 'quality') {
        const { qualityList } = state;
        newList = qualityList.slice();
        newList[index][key] = value;
        return {
          ...state,
          qualityList: newList,
        };
      }
    },

    updateForm(state, { payload }) {
      const { key, value } = payload;
      const formData = state.formData;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      if (key === 'repItemName' && value.id != null) {
        newFormData[key].name = `${value.name}(${value.code})`;
      }
      return {
        ...state,
        formData: newFormData,
        supplierList: key === 'suppCenter' ? [] : state.supplierList,
      };
    },

  },

};
