import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as contractTmplDetailService from '../../../services/contract-mgmt/contract-tmpls/contractTmpls';
import { stringUtils, dataUtils, formUtils } from '../../../utils';

export default {

  namespace: 'contractTmplDetail',

  state: {
    formData: {
      modelTitle: '',
    },
    mode: 'create',
    from: '',
    taskKey: '',
    taskId: '',
    modelContent: '',
    list: [],
    saveBtnFlag: false,
    readOnly: false
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen(() => {
        const match = pathToRegexp('/contract-mgmt/contract-tmpls/:id').exec(location.pathname);
        if (match) {
          if (match[1] === 'create') {
            const tmpl = stringUtils.queryURL('tmpl');
            dispatch({ type: 'clean' });
            dispatch({ type: 'newCreate', payload: tmpl });
          } else {
            dispatch({ type: 'updateState', payload: { formData: {} } });
            dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
            dispatch({ type: 'query', payload: match[1] });
          }
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      let { mode, saveBtnFlag } = yield select(({ contractTmplDetail }) => contractTmplDetail);
      const perms = yield select(({ app }) => app.perms);
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'ctm_ctt_details_save';
          })) {
          saveBtnFlag = true;
        }
      }
      const formData = yield call(contractTmplDetailService.getSingle, payload);
      if (formData.success) {
        const modelContent = formData.data.modelContent;
        if (!formData.data.attachRepo) {
          formData.data.newAttach = true;
          formData.data.attachRepo = dataUtils.getRandomInt(1, 9999999);
        }
        yield put({
          type: 'updateState',
          payload: {
            formData: formData.data,
            list: formData.data.contactVarsList,
            modelContent,
            saveBtnFlag,
            readOnly: mode === 'view',
          },
        });
      } else {
        throw formData;
      }
    },

    * newCreate({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      let { saveBtnFlag } = yield select(({ contractTmplDetail }) => contractTmplDetail);
      const perms = yield select(({ app }) => app.perms);
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'ctm_ctt_details_save';
          })) {
          saveBtnFlag = true;
        }
      }

      if (payload) { // 复制合同
        const formData = yield call(contractTmplDetailService.getSingle, payload);
        if (formData.success) {
          const modelContent = formData.data.modelContent;
          formData.data.id = null; // 移除合同id
          formData.data.newAttach = true;
          formData.data.attachRepo = dataUtils.getRandomInt(1, 9999999);
          yield put({
            type: 'updateState',
            payload: {
              formData: formData.data,
              list: formData.data.contactVarsList,
              modelContent,
              saveBtnFlag
            },
          });
        } else {
          throw formData;
        }
      } else { // 新增合同
        const currentUser = yield select(({ app }) => app.user);
        yield put({
          type: 'updateState',
          payload: {
            formData: {
              newAttach: true,
              attachRepo: dataUtils.getRandomInt(1, 9999999),
              checkUser: currentUser.userName,
            },
            saveBtnFlag
          },
        });
      }
    },

    * save({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const formData = yield select(({ contractTmplDetail }) => contractTmplDetail.formData);
      const list = yield select(({ contractTmplDetail }) => contractTmplDetail.list);
      const newData = {
        ...formUtils.standardiseFormData(formData),
        modelContent: payload.modelContent,
        contactVarsList: list,
      };
      const data = yield call(contractTmplDetailService.create, newData);
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'cancel' });
      } else {
        throw data;

      }
    },
    * redirect({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put(routerRedux.push('/contract-mgmt/contract-tmpls'));
    },

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

    * clean({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {
            modelTitle: '',
          },
          mode: 'create',
          from: '',
          taskKey: '',
          taskId: '',
          modelContent: '',
          list: [],
          saveBtnFlag: false,
          readOnly: false
        },
      });
    },
  },

  reducers: {

    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);
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },

    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,
      };
    },
    addRow(state: object, { payload }: ReduxAction) {
      const { list, total } = state;
      const newList = list.slice();
      newList.push(payload);
      return {
        ...state,
        list: newList,
      };
    },
    deleteRow(state: object, { payload }: ReduxAction) {
      const { list, total } = state;
      let newList = list;
      payload.selectedKeys.map((sId) => {
        newList = newList.slice().filter((item) => item.id !== sId);
      });
      return {
        ...state,
        list: newList,
      };
    },
  },
};
