import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { dataUtils, stringUtils } from '@utils';
import { routerRedux } from 'dva/router';
import { message, Modal } from 'antd';
import { enums } from '../../../utils';
import pathToRegexp from 'path-to-regexp';
import * as compareService from '../../../services/source/compare';
import * as bpmService from '../../../services/common/bpm';

const { viewMode } = enums;

export default {

  namespace: 'compareAudit',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'view',
    filterParams: {},
    detailBtnFlag: false,
    confirmBtnFlag: false,
    exportBtnFlag: false,
    deleteBtnFlag: false,
    batchApproveBtnFlag: false,
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen((location) => {
        // console.log("location==>", location)
        if (location.pathname === '/source-mgmt/qo/qo/item') {
          dispatch({ type: 'query' });
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // if(payload.monthDate){
      // 角色判断
      let { detailBtnFlag, confirmBtnFlag, exportBtnFlag, deleteBtnFlag, batchApproveBtnFlag } = yield select(({ compareAudit }) => compareAudit);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_item_detail';
        })) {
          detailBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_item_confirm';
        })) {
          confirmBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_item_export';
        })) {
          exportBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_comp_delete';
        })) {
          deleteBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_comp_approve';
        })) {
          batchApproveBtnFlag = true;
        }
      }
      yield put({
        type: 'updateState',
        payload: {
          detailBtnFlag, confirmBtnFlag, exportBtnFlag, deleteBtnFlag, batchApproveBtnFlag
        },
      });
      const data = yield call(compareService.query, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
          // state: { ...payload },
        }));
      } else {
        throw data;
      }
      // }else{
      //   message.warn('请填写询价月份');
      // }
    },
    * getSingle({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      if (payload.mode === viewMode.VIEW) {
        yield put(
          routerRedux.push(`/source-mgmt/qo/compare/detail?mode=${payload.mode}&docId=${payload.docId}`)
        );
      } else if (payload.mode === viewMode.EDIT) {
        const currentUser = yield select(({ app }) => app.user);
        let row = payload.row;
        if (row.docStatus === '00' && row.createUserId ===  currentUser.user.id) {
          yield put(
            routerRedux.push(`/source-mgmt/qo/compare/detail?mode=${payload.mode}&docId=${row.pcDocId}`)
          );
        } else {
          message.error('只能修改自己创建的且状态为待提交的比价单');
        }
      } else {
        if (payload.docStatus === '01') {
          const status = yield call(bpmService.doCheckActived, payload.prcId);
          if (status.success) {
            if (status.data) {
              yield put(
                routerRedux.push(`/source-mgmt/qo/compare/detail?mode=${payload.mode}&docId=${payload.docId}`)
              );
            } else {
              message.error('您不是当前处理人，不能进行审批');
            }
          }
        } else {
          message.error('当前状态不能进行审批操作');
        }
      }
    },
    * showPop({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put({
        type: 'showModal',
        payload: {
          mode: payload.mode,
        }
      });
    },
    * hideModal({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
    },
    * clean({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          filterParams: {},
        },
      });
    },
    * delete({ payload }, { put, call }) {
      const data = yield call(compareService.deleteProcess, payload);
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'query' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },
    * batchApprove({ payload }, { put, call }) {
      const data = yield call(compareService.batchApprove, payload.pcIds);
      console.log(data);
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'query' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },
  },

  reducers: {

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

    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,
      };
    },

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

    showModal(state: object, action: ReduxAction) {
      return { ...state, ...action.payload, modalVisible: true };
    },

  },
};
