import qs from 'qs';

import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { enums, stringUtils, dataUtils } from '@utils';
import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import * as bpmService from '../../../services/common/bpm';
import * as contractsService from '../../../services/contract-mgmt/contracts/contracts';
import { formUtils } from '../../../utils';

const { customMsg } = enums;
export default {
  namespace: 'contracts',
  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    addBtnFlag: false,
    editBtnFlag: false,
    viewBtnFlag: false,
    approvalBtnFlag: false,
    cancelBtnFlag: false,
    sealUploadBtnFlag: false,
    deleteBtnFlag: false,
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen((location) => {
        // if (location.pathname === '/contract-mgmt/contracts') {
        // }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // 角色判断 ctm_cts_add/ ctm_cts_edit/ ctm_cts_view/ ctm_cts_approval/ ctm_cts_cancel
      let { addBtnFlag, editBtnFlag, viewBtnFlag, approvalBtnFlag, cancelBtnFlag, sealUploadBtnFlag, deleteBtnFlag } = yield select(({ contracts }) => contracts);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_add';
        })) {
          addBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_edit';
        })) {
          editBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_view';
        })) {
          viewBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_approval';
        })) {
          approvalBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_cancel';
        })) {
          cancelBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_seal_upload';
        })) {
          sealUploadBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'ctm_cts_delete';
        })) {
          deleteBtnFlag = true;
        }
      }
      const data = yield call(contractsService.query, payload);
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            addBtnFlag,
            editBtnFlag,
            viewBtnFlag,
            approvalBtnFlag,
            cancelBtnFlag,
            sealUploadBtnFlag,
            deleteBtnFlag,
          },
        });
        // console.log(payload);
        // window.location.href = '#ddd';
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
          // state: { ...payload },
        }));
      } else {
        throw data;
      }
    },

    * getSingle({ payload }: ReduxAction, { select, put, call }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });

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

      if (payload.mode === 'create') {
        yield put(routerRedux.push('/contract-mgmt/contracts/create'));
      } else if (payload.mode === 'view') {
        const urlProps = {...(payload.otherProps || {}), mode: 'view'};
        if (!!urlProps.uploadSeal) {
          const formData = yield call(contractsService.getSingle, payload.id);
          if (formData.data.checkStatus === customMsg.CONTRACT_STATUS_CANCELLED) {
            message.error(formData.data.checkStatusName + customMsg.CONTRACT_NOT_UPLOAD_SEAL);
            return;
          }
        }
        yield put(routerRedux.push(`/contract-mgmt/contracts/${payload.id}?${qs.stringify(urlProps)}`));
      } else {
        const formData = yield call(contractsService.getSingle, payload.id);
        if (formData.success) {
          if (payload.mode === 'update') {
            if (formData.data.checkStatus === customMsg.CONTRACT_STATUS_CREATE && formData.data.createUserId === currentUser.user.id) {
              yield put(routerRedux.push(`/contract-mgmt/contracts/${payload.id}?mode=update`));
            } else if (formData.data.checkStatus !== customMsg.CONTRACT_STATUS_CREATE) {
              message.error(formData.data.checkStatusName + customMsg.CONTRACT_NOT_UPDATE);
            } else {
              message.error(customMsg.CONTRACT_NOT_CREATEUSER);
            }
          }
          if (payload.mode === 'approval') {
            if (!formData.data.prcId || formData.data.checkStatus === customMsg.CONTRACT_STATUS_VALID) {
              message.error(formData.data.checkStatusName + customMsg.CONTRACT_NOT_APPROVAL);
            } else {
              const status = yield call(bpmService.doCheckActived, formData.data.prcId);
              if (status.success) {
                if (status.data) {
                  yield put(routerRedux.push(`/contract-mgmt/contracts/${payload.id}?mode=approval`));
                } else {
                  Modal.error({
                    title: customMsg.NOT_ACTIVE_HANDLER, // 您不是当前处理人
                  });
                }
              }
            }
          }
        }
      }
    },

    * delete({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(contractsService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * updateStatus({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const formData = yield call(contractsService.getSingle, payload.id);
      if (formData.success) {
        if (formData.data.checkStatus === customMsg.CONTRACT_STATUS_CREATE
          || formData.data.checkStatus === customMsg.CONTRACT_STATUS_OVERDUE) {
          const data = yield call(contractsService.updateStatus, formUtils.standardiseFormData(payload));
          if (data.success) {
            yield put({ type: 'query' });
          } else {
            throw data;
          }
        } else {
          message.error(formData.data.checkStatusName + customMsg.CONTRACT_NOT_INVALID);
        }
      } else {
        throw formData;
      }
    },

    * deleteContract({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const formData = yield call(contractsService.getSingle, payload.id);
      if (formData.success) {
        // 只能删除`生效`的合同
        if (formData.data.checkStatus === customMsg.CONTRACT_STATUS_VALID) {
          const result = yield call(contractsService.deleteContract, payload.id);
          if (result.success){
            yield put({
              type: 'query',
              payload: dataUtils.queryStringToJSON(location.search) || { from: '' }
            });
          } else {
            throw result;
          }
        } else {
          message.error(formData.data.checkStatusName + customMsg.CONTRACT_NOT_DELETE);
        }
      } else {
        throw formData;
      }
    },
  },

  reducers: {

    querySuccess(state: object, action: ReduxAction) {
      const {
        list, total, addBtnFlag, editBtnFlag,
        viewBtnFlag, approvalBtnFlag, cancelBtnFlag, sealUploadBtnFlag,
        deleteBtnFlag,
      } = action.payload;
      return {
        ...state,
        list,
        total,
        addBtnFlag,
        editBtnFlag,
        viewBtnFlag,
        approvalBtnFlag,
        cancelBtnFlag,
        sealUploadBtnFlag,
        deleteBtnFlag,
      };
    },

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

  },
};
