import * as edDetailService from '../../../services/quality/ed/ed';
import * as bpmService from '../../../services/common/bpm';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message, Modal } from 'antd';
import { dataUtils, formUtils, enums } from '../../../utils';

const { customMsg, viewMode } = enums;

export default {

  namespace: 'edDetail',

  state: {
    formData: {},
    mode: '',
    from: '',
    taskKey: '',
    taskId: '',
    advice: '',
    remoteCfg: null,
    list: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/quality/edo/:id').exec(location.pathname);
        if (match) {
          if (match[1] === 'create') {
            dispatch({ type: 'clean' });
            dispatch({ type: 'newCreate' });
            return 0;
          }
          dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          dispatch({ type: 'query', payload: match[1] });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      let { mode } = yield select(({ edDetail }) => edDetail);
      const formData = yield call(edDetailService.getSingle, payload);
      if (formData.success) {

        formData.data.org = {
          id: formData.data.orgId,
          code: formData.data.orgCode,
          name: formData.data.orgName,
          ouId: formData.data.ouId,
          ouName: formData.data.ouName,
        };

        const currentUser = yield select(({ app }) => app.user);
        formData.data.roleName = currentUser.roleName;

        if (formData.data.dutyType === '01') {
          formData.data.dutySuppRole = formData.data.dutyRole;
        };
        if (formData.data.dutyType === '02') {
          formData.data.dutyOuRole = formData.data.dutyRole;
        }

        formData.data.hasClaimOrder ? formData.data.docNo = '是' : formData.data.docNo = '否';

        if (formData.data.prcId && mode === 'approval') {
          //判断登录用户是否为当前处理人
          const status = yield call(bpmService.doCheckActived, formData.data.prcId);
          if (!(status.success && status.data)) {
            Modal.error({
              title: customMsg.NOT_ACTIVE_HANDLER,//您不是当前处理人
            });
            mode = viewMode.VIEW;

          }
        }

        //初始配置文件参数
        const defId = formData.data.defId ? formData.data.defId : 'Report8dAddition:1';
        const taskKey = formData.data.prcId && formData.data.taskKey ? formData.data.taskKey : 'initiator';
        const nodeId = (mode === viewMode.VIEW ? "initiator" : taskKey);
        const params = {
          defId,
          nodeId: nodeId,
          mode: mode === viewMode.UPDATE ? 'edit' : mode,
        };
        //拉去远程文件配置
        const cfgData = yield call(edDetailService.remoteCfg, params);
        if (cfgData.success) {
          yield put({
            type: 'queryConfigSuccess',
            payload: {
              remoteCfg: cfgData.data,
            },
          });
        } else {
          throw cfgData;
        }

        yield put({
          type: 'updateState',
          payload: {
            formData: formData.data,
            list: formData.data.empGroupList || [],
            mode,
            advice:'',
          },
        });

        yield put({ type: 'remoteConfig' });
      } else {
        throw formData;
      }
    },

    * newCreate({ payload }, { call, put, select }) {
      const params = {
        defId: 'Report8dAddition:1',
        nodeId: 'initiator',
        mode: 'create',
      };
      //拉远程文件配置
      const cfgData = yield call(edDetailService.remoteCfg, params);

      if (cfgData.success) {
        yield put({
          type: 'queryConfigSuccess',
          payload: {
            remoteCfg: cfgData.data,
          },
        });

        yield put({
          type: 'updateState',
          payload: {
            formData: {
              org: { id: null, code: null, name: null, ouId: null, ouName: null },
              dutyType: '01',
            },
          },
        });

        yield put({ type: 'remoteConfig' });
      } else {
        throw cfgData;
      }
    },

    * updateEmp({ payload }, { call, put, select }) {
      const emp = yield call(edDetailService.getEmp, payload.id);
      const index = payload.index
      if (emp.success) {
        emp.data.empId = emp.data.id;
        const data = emp.data;
        const { list } = yield select(({ edDetail }) => edDetail);
        for (let i in list) {
          if (data.empId === list[i].empId) {
            message.error('请不要重复选择员工');
            return;
          }
        }
        for (let key in data) {
          yield put({
            type: 'updateCell',
            payload: {
              key, index, value: data[key],
            },
          });
        }
      } else {
        throw emp.message;
      }
    },

    * docHref({ payload }, { call, put, select }) {
      const formData = yield select(({ edDetail }) => edDetail.formData);
      yield put(routerRedux.push(`/cooperate/quality/co?docNo8D=${formData.id}`));
    },


    * save({ payload }, { select, call, put }) {
      const formData = yield select(({ edDetail }) => edDetail.formData);
      const list = yield select(({ edDetail }) => edDetail.list);
      let mode = yield select(({ edDetail }) => edDetail.mode);

      const { submitted } = payload;
      formData.submitted = submitted; //是否提交到工作流
      formData.empGroupList = list

      formData.problemDescClsPath = 'PROBLEM_DESC';
      formData.tempPolicyClsPath = 'TEMP_POLICY';
      formData.rootCauseClsPath = 'ROOT_CAUSE';

      const newData = {
        ...formUtils.standardiseFormData(formData),
        ...formUtils.standardiseFormData(payload),
      };

      if (formData.dutyType === '01' && !formData.suppId) {
        message.error('责任单位 必填');
        return;
      }
      if (formData.dutyType === '01' && !formData.dutySuppRole) {
        message.error('责任角色 必填');
        return;
      }

      if (formData.dutyType === '02' && !formData.org.id) {
        message.error('责任部门 必填');
        return;
      }
      if (formData.dutyType === '02' && !formData.dutyOuRole) {
        message.error('责任角色 必填');
        return;
      }

      if (submitted) {
        const validate = yield call(edDetailService.validate, newData);
        if (validate.success) {
        } else {
          throw validate.message;
        }
      }

      if (mode === 'create') {
        const data = yield call(edDetailService.create, newData);
        if (data.success) {
          message.success('操作成功');
          yield put({ type: 'cancel' });
        } else {
          throw data;;
        }
      } else {
        const advice = yield select(({ edDetail }) => edDetail.advice);
        if(mode==='approval' &&!advice.trim()){
          message.error('请填写审批意见');
          return;
        }
        const data = yield call(edDetailService.update, newData);
        if (data.success) {
          if (submitted && formData.prcId) {
            const bpm = yield call(bpmService.doApprove, { taskId: formData.taskId, advice: advice });
            if (bpm.success) {
            } else {
              throw bpm;
            }
          }
          message.success('操作成功');
          yield put({ type: 'cancel' });
        } else {
          throw data;;
        }
      }

    },

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

    * continued({ payload }, { put, call, select }) {
      const formData = yield select(({ edDetail }) => edDetail.formData);
      const advice = yield select(({ edDetail }) => edDetail.advice);
      // if(!advice.trim()){
      //   message.error('请填写审批意见');
      //   return;
      // }
      if (!formData.tempPolicy || !formData.rootPolicyResult || !formData.preventionMeasure || !formData.rootCause || !formData.rootPolicy) {
        const data = yield call(bpmService.doContinued, { taskId: formData.taskId, advice: advice });
        if (data.success) {
          yield put({ type: 'cancel' });
        } else {
          throw data;
        }
      } else {
        const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice: advice });
        if (data.success) {
          yield put({ type: 'cancel' });
        } else {
          throw data;
        }

      }

    },

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

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

    * updated({ payload }, { put, select }) {
      yield put({
        type: 'updateForm',
        payload
      })
      yield put({ type: 'remoteConfig' });

    },

    * remoteConfig({ payload }, { put, select }) {
      const formData = yield select(({ edDetail }) => edDetail.formData);
      if (formData.dutyType === '01') {
        yield put({
          type: 'changeConfig', payload: {
            configs: [{
              'fieldId': 'ouName',
              'hidden': 1,
              'required': 0,
            }, {
              'fieldId': 'org',
              'hidden': 1,
              'required': 0,
            }, {
              'fieldId': 'dutyOuRole',
              'hidden': 1,
              'required': 0,
            }, {
              'fieldId': 'suppId',
              'hidden': 0,
              'required': 1,
            }, {
              'fieldId': 'dutySuppRole',
              'hidden': 0,
              'required': 1,
            }]
          },
        });
      }
      if (formData.dutyType === '02') {
        yield put({
          type: 'changeConfig', payload: {
            configs: [{
              'fieldId': 'ouName',
              'hidden': 0,
              'required': 0,
            }, {
              'fieldId': 'org',
              'hidden': 0,
              'required': 1,
            }, {
              'fieldId': 'dutyOuRole',
              'hidden': 0,
              'required': 1,
            }, {
              'fieldId': 'suppId',
              'hidden': 1,
              'required': 0,
            }, {
              'fieldId': 'dutySuppRole',
              'hidden': 1,
              'required': 0,
            }]
          },
        });
      }
    },

    * clean({ payload }, { put, select }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          valid: false,
          mode: 'create',
          taskKey: '',
          taskId: '',
          remoteCfg: null,
          list: [],
        },
      });
    },
  },

  reducers: {

    queryConfigSuccess(state, action) {
      const { remoteCfg } = action.payload;
      return {
        ...state,
        remoteCfg,
      };
    },

    changeConfig(state, action) {
      const { configs } = action.payload;
      let { remoteCfg } = state;
      let panels = remoteCfg.panels;
      for (let config of configs) {
        for (let panel of panels) {
          if (panel.panelId === 'base') {
            let fields = panel.blocks[0].fields;
            for (let field of fields) {
              if (field.fieldId === config.fieldId) {
                field.hidden = config.hidden;
                field.required = config.required;
              }
            }
          }
        }
      }
      return {
        ...state,
        remoteCfg,
      };
    },

    updateCell(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        list: newList,
      };
    },

    updateNullCell(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { index } = payload;
      newList[index] = {}
      return {
        ...state,
        list: newList,
      };
    },

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

    deleteRow(state, { payload }) {
      let { list, } = 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);
      if (key === 'org') {
        newFormData['orgCode'] = value.code;
        newFormData['orgId'] = value.id;
        newFormData['orgName'] = value.name;
        newFormData['ouId'] = value.ouId;
        newFormData['ouName'] = value.ouName;
      }
      if (key === 'dutyOuRole') {
        newFormData['dutyOuRole'] = value;
        newFormData['dutyRole'] = value;
      }
      if (key === 'dutySuppRole') {
        newFormData['dutySuppRole'] = value;
        newFormData['dutyRole'] = value;
      }
      if (key === 'dutySuppRole') {
        newFormData['dutySuppRole'] = value;
        newFormData['dutyRole'] = value;
      }
      if (key === 'dutyType' && value === '01') {
        newFormData['dutyRole'] = '';
        newFormData['dutyOuRole'] = '';
        newFormData['org'] = { id: null, code: null, name: null, ou: null };
        newFormData['orgId'] = '';
        newFormData['orgCode'] = '';
        newFormData['orgName'] = '';
        newFormData['ouId'] = '';
        newFormData['ouName'] = '';
      }
      if (key === 'dutyType' && value === '02') {
        newFormData['dutyRole'] = '';
        newFormData['dutySuppRole'] = '';
        newFormData['suppId'] = '';
      }
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },

  },

};
