import * as performancesService from '../../services/supplier/performances';
import * as bpmService from '../../services/common/bpm';
import { routerRedux } from 'dva/router';
import { stringUtils, enums, dataUtils } from '@utils';
import { Modal } from 'antd';

const { customMsg, viewMode, entType, docStatus } = enums;

export default {
  namespace: 'performances',
  state: {
    list: [],
    total: 0,
    mode: 'create',
    supplier: {},
    showUploadModal: false,
    menuBtns: ["lf_sp_update", "lf_sp_approve", "lf_sp_cancel"],
    showMenu: [false, false, false],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/lifecycle/supp-performance') {
          dispatch({ type: 'pageDataClean' });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      const { showMenu, menuBtns } = yield select(({ performances }) => performances);
      const perms = yield select(({ app }) => app.perms);
      menuBtns.forEach((i) => {
        const menuId = perms.map((m) => m.menuId).find((n) => n === i);
        showMenu[menuBtns.indexOf(i)] = menuId ? true : false;
      });

      if (!payload.bpmStatus) {
        payload.bpmStatus = 'NONE';
      }
      const data = yield call(performancesService.query, { ...payload });
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            showMenu,
            list: data.data.rows,
            total: data.data.total,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));
      } else {
        throw data;
      }
    },

    * getSingle({ payload }, { call, put }) {

      const data = yield call(performancesService.getSingle, payload.id);
      if (data.success) {
        const redirect = `/lifecycle/supp-performance/${payload.id}?mode=${payload.mode}&breadCode=${data.data.suppCode}&breadOuName=${data.data.suppName.trim()}`;
        if (payload.mode === viewMode.VIEW) {
          yield put(routerRedux.push(redirect));
        } else {
          const prcId = data.data.prcId;
          const status = data.data.status;
          if (payload.mode === viewMode.CREATE) {
            if (status === docStatus.DOC_STATUS_WAITING) {
              const lastMonth = yield call(performancesService.lastMonth, data.data);
              if (lastMonth.success) {
                if (lastMonth.data && (lastMonth.data.status !== docStatus.DOC_STATUS_FINISH)) {
                  Modal.error({
                    title: customMsg.PERFORMANCE_NOT_FINISHED, // 上月绩效评分未完成，不能进行当月评分
                  });
                } else {
                  yield put(routerRedux.push(redirect));
                }
              } else {
                throw lastMonth;
              }
            } else {
              Modal.error({
                title: customMsg.PERFORMANCE_ALREADY_SCORE, // 已评分的绩效，不能再进行修改
              });
            }
          }
          if (payload.mode === viewMode.APPROVE) {
            if (status === docStatus.DOC_STATUS_WAITING) {
              Modal.error({
                title: customMsg.PERFORMANCE_NOT_SCORE, // 未评分的绩效，不能再进行审批
              });
            } else {
              const status = yield call(bpmService.doCheckActived, prcId);
              if (status.success && status.data) {
                yield put(routerRedux.push(redirect));
              } else {
                Modal.error({
                  title: customMsg.NOT_ACTIVE_HANDLER, // 您不是当前处理人
                });
              }
            }
          }
        }
      } else {
        throw data;
      }
    },

    * pageDataClean({ payload }, { put, call, select, take }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          supplier: {
            supplier: user.entType === entType.SUPP,
            suppName: user.name,
            suppCode: stringUtils.queryURL('suppCode'),
            status: stringUtils.queryURL('status'),
            scoreGrade: stringUtils.queryURL('scoreGrade'),
            performanceFromDate: stringUtils.queryURL('performanceFromDate'),
            performanceToDate: stringUtils.queryURL('performanceToDate'),
            lowQualityStatus: stringUtils.queryURL('lowQualityStatus'),
            perforType: stringUtils.queryURL('perforType'),
            assessPeriod: stringUtils.queryURL('assessPeriod'),
            observePeriod: stringUtils.queryURL('observePeriod'),
            activeTaskKey: stringUtils.queryURL('activeTaskKey'),
            bpmStatus: stringUtils.queryURL('bpmStatus'),
          },
          showUploadModal: false,
        },
      });
    },

    * clean({ payload }, { call, put, take, }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          mode: 'create',
          supplier: {},
        },
      });
    },

    * cancel({ payload }, { call, put, take, }) {
      const data = yield call(performancesService.cancel, payload.id);
      if (data.success) {
        yield put({
          type: 'query',
          payload: dataUtils.queryStringToJSON(location.search)
        });
      } else {
        throw data;
      }
    },
  },

  reducers: {

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

    updateState(state, { payload }) {
      console.log("updateState")
      console.dir(state);
      return {
        ...state,
        ...payload,
      };
    },

    showUploadModal(state, action) {
      return { ...state, showUploadModal: action.payload };
    },

  },
};
