import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { dataUtils, enums, formUtils, networkUtils, printUtils } from '@utils';
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 contactsService from '../../../services/contract-mgmt/contracts/contracts';
import * as contractTmplDetailService from '@services/contract-mgmt/contract-tmpls/contractTmpls';
import headerTmpl from './header.hbs';

const { viewMode, resultCode, customMsg ,entType} = enums;
export default {
  namespace: 'contractDetail',
  state: {
    formData: {
      checkStatus: '0',
      ouName: { id: null, code: null, name: null },
      suppName: { id: null, code: null, name: null }
    },
    mode: 'create',
    from: '',
    taskKey: '',
    taskId: '',
    list: [],
    inputList: [],
    modalVisible: false,
    readOnly: false,
    total: 0,
    advice: '',
    remoteCfg: null,
    attachRepo: null,
    saveBtnFlag: false,
    previewBtnFlag: false,
    AFlag:false,
    suppFlag: false,
    sealUploadFlag: false,
    attachRepoTmpl: '',
    dataKeyTmpl: ''
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen(() => {
        const match = pathToRegexp('/contract-mgmt/contracts/:id').exec(location.pathname);
        const search = dataUtils.queryStringToJSON(location.search)
        if (match) {
          if (match[1] === 'create') {
            dispatch({ type: 'create' });
            return 0;
          }
          dispatch({ type: 'readonly', payload: search || { from: '' } });
          dispatch({ type: 'query', payload: {...search, id: match[1]} });

        }
      });
    },
  },

  effects: {

    * create({ payload }: ReduxAction, { call, put, select, all }: ReduxSagaEffects) {
      yield put({ type: 'clean' });
      const roleId = yield call(contactsService.roleId, payload);
      //开发采购专员/订单采购专员不能创建A类合同
      const AFlag = (roleId.success && (2===roleId.data || 4===roleId.data))? false: true;
      // console.log('roleId=>',roleId);
      // console.log('AFlag=>',AFlag);
      const params = {
        defId: 'ATypeContract:',
        nodeId: 'initiator',
        mode: 'create',
      };
      const cfgData = yield call(bpmService.getFormCfg, params);

      if (cfgData.success) {
        // 角色判断 ctm_cts_save/ ctm_cts_preview
        let { saveBtnFlag, previewBtnFlag, sealUploadFlag } = yield select(({ contractDetail }) => contractDetail);
        const perms = yield select(({ app }) => app.perms);
        // console.log('perms==>',perms)
        if (perms) {
          if (perms.find((x) => {
              return x.menuId === 'ctm_cts_save';
            })) {
            saveBtnFlag = true;
          }
          if (perms.find((x) => {
              return x.menuId === 'ctm_cts_preview';
            })) {
            previewBtnFlag = true;
          }
          // if (perms.find((x) => {
          //   return x.menuId === 'ctm_cts_seal_upload';
          // })) {
          //   sealUploadFlag = true;
          // }
        }
        yield put({
          type: 'updateState',
          payload: {
            remoteCfg: cfgData.data,
            attachRepo: dataUtils.getRandomInt(1, 9999999),
            saveBtnFlag,
            previewBtnFlag,
            AFlag,
            sealUploadFlag,
          },
        });
      } else {
        throw cfgData;
      }
    },

    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // 角色判断 ctm_cts_save/ ctm_cts_preview
      let { saveBtnFlag, previewBtnFlag, sealUploadFlag } = yield select(({ contractDetail }) => contractDetail);
      const perms = yield select(({ app }) => app.perms);
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'ctm_cts_save';
          })) {
          saveBtnFlag = true;
        }
        if (perms.find((x) => {
            return x.menuId === 'ctm_cts_preview';
          })) {
          previewBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_seal_upload' && !!payload.uploadSeal ;
        })) {
          sealUploadFlag = true;
        }
      }
      const formData = yield call(contactsService.getSingle, payload.id);
      let { mode } = yield select(({ contractDetail }) => contractDetail);
      const roleId = yield call(contactsService.roleId, payload.id);
      //开发采购专员/订单采购专员不能创建A类合同
      const AFlag = ((mode === viewMode.UPDATE) && roleId.success && (2===roleId.data || 4===roleId.data))? false: true;
      if (formData.success) {
        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;
          }
        }

        formData.data.suppName = {
          id: formData.data.suppId,
          code: formData.data.suppCode,
          name: formData.data.suppName,
        };
        formData.data.ouName = { id: formData.data.ouId, code: formData.data.ouCode, name: formData.data.ouName };

        // 使用模板附件
        const { contractModelId } = formData.data;
        if (contractModelId) {
          yield put({
            type: 'getContractTmplAttach',
            payload : { contractModelId }
          });
        }

        // 初始配置文件参数
        const params = {
          defId: 'ATypeContract:',
          nodeId: formData.data.prcId ? (mode === viewMode.VIEW ? 'initiator' : formData.data.taskKey) : 'initiator',
          mode: mode === viewMode.UPDATE ? 'edit' : mode,
        };
        // 拉去远程文件配置
        const cfgData = yield call(bpmService.getFormCfg, params);
        if (cfgData.success) {
          const currentUser = yield select(({ app }) => app.user);
          yield put({
            type: 'updateState',
            payload: {
              remoteCfg: cfgData.data,
              formData: formData.data,
              list: formData.data.contractsAmListViews,
              inputList: formData.data.contactsTmplVarList,
              attachRepo: formData.data.attachRepo,
              saveBtnFlag,
              previewBtnFlag,
              AFlag,
              suppFlag: (entType.SUPP === currentUser.user.entType) ? true : false,
              sealUploadFlag,
              mode
            },
          });
        } else {
          throw cfgData;
        }
      } else {
        throw formData;
      }
    },

    * getContractTmplAttach({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const { contractModelId } = payload;
      const contractTmpl = yield call(contractTmplDetailService.getTemplage, contractModelId);
      if (contractTmpl.success) {
        yield put({
          type: 'updateState',
          payload: {
            attachRepoTmpl: contractTmpl.data.attachRepo,
            dataKeyTmpl: contractTmpl.data.id
          },
        });
      } else {
        throw contractTmpl;
      }
    },

    * readonly({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      let readonly = false;
      if (payload.mode === 'view' || payload.mode === 'approval') {
      readonly
        = true;
      } else {
      readonly
        = false;
      }
      yield put({
        type: 'updateState', payload: {
          mode: payload.mode,
          readOnly: readonly,
          advice:'',
        },
      });
    },

    * save({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const attachRepo = yield select(({ contractDetail }) => contractDetail.attachRepo);
      const formData = yield select(({ contractDetail }) => contractDetail.formData);
      const list = yield select(({ contractDetail }) => contractDetail.list);
      const inputList = yield select(({ contractDetail }) => contractDetail.inputList);
      const { submitted } = payload;
      formData.submitted = submitted;
      formData.attachRepo = attachRepo;

      const newData = {
        ...formUtils.standardiseFormData(payload),
        ...formUtils.standardiseFormData(formData),
        contactsAmPayloads: list,
        contactsTmplVarList: inputList,
      };

      if (newData.timeInForceDate >= newData.deadDate) {
        message.error(customMsg.CONTRACT_CHECK_DATE);
        return;
      }
      // console.log('newdata=>',newData)
      const checkData = yield call(contactsService.checkDate, newData);
      if(checkData.success){
        const data = yield call(contactsService.update, newData);
        if (data.success) {
          message.success(resultCode.OK);
          if (submitted) {
            yield put(routerRedux.replace(`/contract-mgmt/contracts/${data.data}?mode=view`));
          } else {
            // yield put(routerRedux.push('/contract-mgmt/contracts'));
            yield put(routerRedux.replace(`/contract-mgmt/contracts/${data.data}?mode=update`));
          }
        } else {
          throw data;
        }
      }else{
        message.error(checkData.message);
      }
    },

    * approve({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ contractDetail }) => contractDetail.formData);
      const advice = yield select(({ contractDetail }) => contractDetail.advice);
      // if(!advice.trim()){
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      if (data.success) {
        message.success(resultCode.OK);
        yield put(routerRedux.push('/contract-mgmt/contracts'));
      } else {
        throw data;
      }
    },

    * reject({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ contractDetail }) => contractDetail.formData);
      const advice = yield select(({ contractDetail }) => contractDetail.advice);
      if(!advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      if (data.success) {
        // const data = yield call(contractsService.updateStatus, {id:formData.id,checkStatus:'5'});
        message.success(resultCode.OK);
        yield put(routerRedux.push('/contract-mgmt/contracts'));
      } else {
        throw data;
      }
    },

    * submitAgain({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ contractDetail }) => contractDetail.formData);
      const advice = yield select(({ contractDetail }) => contractDetail.advice);

      const list = yield select(({ contractDetail }) => contractDetail.list);
      const inputList = yield select(({ contractDetail }) => contractDetail.inputList);
      formData.submitted = false;

      const newData = {
        ...formUtils.standardiseFormData(payload),
        ...formUtils.standardiseFormData(formData),
        contactsAmPayloads: list,
        contactsTmplVarList: inputList,
      };

      if (newData.timeInForceDate >= newData.deadDate) {
        message.error(customMsg.CONTRACT_CHECK_DATE);
        return;
      }
      if(!advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(contactsService.update, newData);
      if (data.success) {
        const dataApprove = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
        if (dataApprove.success) {
          message.success(resultCode.OK);
          yield put(routerRedux.push('/contract-mgmt/contracts'));
        } else {
          throw dataApprove;
        }
      } else {
        throw data;

      }
    },

    * cancel({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {

      yield put(routerRedux.goBack());
      yield put({ type: 'clean' });

    },

    * clean({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {
            checkStatus: '0',
            ouName: { id: null, code: null, name: null },
            suppName: { id: null, code: null, name: null },
          },
          valid: false,
          mode: 'create',
          taskKey: '',
          taskId: '',
          list: [],
          modalVisible: false,
          readOnly: false,
          from: '',
          inputList: [],
          total: 0,
          advice: '',
          remoteCfg: null,
          attachRepo: null,
          saveBtnFlag: false,
          previewBtnFlag: false,
          suppFlag: false,
          sealUploadFlag: false,
          attachRepoTmpl: '',
          dataKeyTmpl: ''
        },
      });
    },

    * print({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const printData = yield call(contactsService.queryPrint, payload.formData.id);
      // console.log("print===",printData);
      if (printData.success) {
        const list = yield select(({ contractDetail }) => contractDetail.list);
        // console.log("list==>",list)
        /* todo 看页面的处理逻辑来决定打印时补充条款是否需要重新排序，需要排序就打开这段注释
        const sortBy = (attr,rev) => {
          //第二个参数没有传递 默认升序排列
          if(rev ==  undefined){
            rev = 1;
          }else{
            rev = (rev) ? 1 : -1;
          }
          return function(a,b){
            a = a[attr];
            b = b[attr];
            if(a < b){
              return rev * -1;
            }
            if(a > b){
              return rev * 1;
            }
            return 0;
          }
        }
        console.log("list-sort==>",list.sort(sortBy('lineNo',true)));*/
        const tasks = [{
          content: { formData: printData.data, itemData: list },
          tmpl: headerTmpl,
        }];
        printUtils.print(tasks, false);
      } else {
        throw printData;
      }

    },

    * updateTmpl({ payload }: ReduxAction, { select, put, call }: ReduxSagaEffects) {
      const { value } = payload;
      const { id } = yield select(({ contractDetail }) => contractDetail.formData);
      let inputListData;
      if (value != null) {
        const inputList = yield call(contactsService.queryTpmlVars, { contractId: id, contractModelId: value });
        if (inputList.success) {
          inputListData = inputList.data;
        }
        // 更新模板附件
        yield put({
          type: 'getContractTmplAttach',
          payload : { contractModelId: value }
        });
      } else {
        inputListData = [];
      }
      yield put({
        type: 'updateState',
        payload: {
          inputList: inputListData,
        },
      });
      yield put({
        type: 'updateForm',
        payload,
      });
    },
  },

  reducers: {

    addRow(state: object, { payload }: ReduxAction) {
      const { list, total } = state;
      const newList = list.slice();
      payload.lineNo = (list.length ? list.length : 0) + 1;
      newList.push(payload);
      return {
        ...state,
        list: newList,
        total: total + 1,
      };
    },

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

    updateInputCell(state: object, { payload }: ReduxAction) {
      const { inputList } = state;
      const newList = inputList.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        inputList: newList,
      };
    },

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

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

    updateState(state: object, { payload }: ReduxAction) {
      return {
        ...state,
        ...payload,
      };
    },

    updateForm(state: object, { payload }: ReduxAction) {
      const { key, value } = payload;
      const formData = state.formData;
      const newFormData = Object.assign({}, formData);
      if (key === 'suppName') {
        newFormData.suppCode = value.code;
        newFormData.suppId = value.id;
      }
      if (key === 'ouName') {
        newFormData.ouCode = value.code;
        newFormData.ouId = value.id;
      }
      newFormData[key] = value;
      // console.log('==',newFormData)
      return {
        ...state,
        formData: newFormData,
      };
    },

  },

};
