import * as claimOrderService from '../../../services/quality/co/claimOrders';
import * as bpmService from '../../../services/common/bpm';
import { routerRedux } from 'dva/router';
import { stringUtils, enums } from '@utils';
import { Modal } from 'antd';
const { customMsg, viewMode, entType, approveStatus } = enums;

export default {
  namespace: 'claimOrder',
  state: {
    list: [],
    total: 0,
    currentItem: {},
    supplier: {},
    menuBtns: ['cp_order_co_add', 'cp_order_co_update', 'cp_order_co_approve', 'cp_order_co_remove'],
    showMenu: [false, false, false, false],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/cooperate/quality/co') {
          dispatch({ type: 'pageDataClean' });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      const { showMenu, menuBtns } = yield select(({ claimOrder }) => claimOrder);
      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(claimOrderService.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 }, { put, call }) {
      if (payload.mode === viewMode.CREATE) {
        yield put(routerRedux.push('/cooperate/quality/co/create')); // 新增
      } else {
        const data = yield call(claimOrderService.getSingle, payload.id);
        if (data.success) {
          const redirect = `/cooperate/quality/co/${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;
            // 修改
            if (payload.mode === viewMode.UPDATE) {
              if (!prcId) {
                yield put(routerRedux.push(redirect));
              } else {
                Modal.error({ title: data.data.approveStatusName + customMsg.PE_NOT_UPDATE });
              }
            }

            // 审批
            if (payload.mode === viewMode.APPROVE) {
              if (!prcId) {
                Modal.error({ title: data.data.approveStatusName + customMsg.PE_NOT_APPROVAL });
              } 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;
        }
      }
    },

    * remove({ payload }, { put, call, select }) {
      const { supplier } = yield select(({ claimOrder }) => claimOrder);

      const data = yield call(claimOrderService.getSingle, payload.id);
      if (data.success && data.data) {
        if (data.data.approveStatus !== approveStatus.WAITING) {
          Modal.error({ title: `${data.data.approveStatusName} ${customMsg.CLAIM_NOT_DELETE}` });
        } else {
          const rmData = yield call(claimOrderService.remove, payload.id);
          if (rmData.success) {
            yield put({
              type: 'query',
              payload: {
                limit: stringUtils.queryURL('limit'),
                offset: stringUtils.queryURL('offset') || 0,
                sortBy: stringUtils.queryURL('sortBy') || 'docNo',
                sortDirection: stringUtils.queryURL('sortDirection') || 'DESC',
                ...supplier,
              },
            });
          } else {
            throw rmData;
          }
        }
      } else {
        throw data;
      }
    },

    * pageDataClean({ payload }, { put, select }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          supplier: {
            supplier: user.entType === entType.SUPP,
            suppName: user.name,
            docNo: stringUtils.queryURL('docNo'),
            suppCode: stringUtils.queryURL('suppCode'),
            compsMode: stringUtils.queryURL('compsMode'),
            compsType: stringUtils.queryURL('compsType'),
            docDateFrom: stringUtils.queryURL('docDateFrom'),
            docDateTo: stringUtils.queryURL('docDateTo'),
            docStatus: stringUtils.queryURL('docStatus'),
            docNo8D: stringUtils.queryURL('docNo8D'),
            activeTaskKey: stringUtils.queryURL('activeTaskKey'),
            bpmStatus: stringUtils.queryURL('bpmStatus'),
          },
        },
      });
    },

  },

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

    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

  },
};
