import * as examService from '../../../services/source/exams';
import * as tenderService from '../../../services/source/tenders';
import * as bpmService from '../../../services/common/bpm';
import { routerRedux } from 'dva/router';
import { enums, stringUtils } from '@utils';
import { message, Modal } from 'antd';
const { bidStatus, resultCode, customMsg } = enums;
export default {
  namespace: 'examForm',

  state: {
    list: [],
    total: 1,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    filterParams: {},
    bidOpenBtnFlag: false,
    approvalBtnFlag: false,
    suppScoreBtnFlag: false
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/source-mgmt/bid-mgmt/exam') {
          // dispatch({ type: 'clean' });
          // dispatch({ type: 'query' });
        }
      });
    }
  },

  effects: {
    *query({ payload }, { call, put, select }) {
      // 角色判断
      /*soum_bm_em_bidOpen/soum_bm_em_approval/soum_bm_em_suppScore*/
      let { bidOpenBtnFlag, approvalBtnFlag, suppScoreBtnFlag } = yield select(
        ({ examForm }) => examForm
      );
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_em_bidOpen';
          })
        ) {
          bidOpenBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_em_approval';
          })
        ) {
          approvalBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_em_suppScore';
          })
        ) {
          suppScoreBtnFlag = true;
        }
      }
      if (!payload.bpmStatus) {
        payload.bpmStatus = 'NONE';
      }
      const { filterParams } = yield select(({ examForm }) => examForm);
      const data = yield call(examService.query, {
        ...filterParams,
        ...payload
      });
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: { ...filterParams, ...payload },
            bidOpenBtnFlag,
            approvalBtnFlag,
            suppScoreBtnFlag
          }
        });
        yield put(
          routerRedux.replace({
            pathname: location.pathname,
            search: '?' + stringUtils.JSON2QueryString(payload)
          })
        );
      } else {
        throw data;
      }
    },
    *querySingle({ payload }, { call, put }) {
      const data = yield call(examService.getSingle, payload.id);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode
          }
        });
      } else {
        throw data;
      }
    },
    *getSingle({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode
        }
      });
      if (payload.mode === 'create') {
        yield put(routerRedux.push('/source-mgmt/bid-mgmt/exam/create'));
      } else {
        if (payload.mode === 'approval') {
          const formData = yield call(tenderService.review, payload.id);
          if (formData.success) {
            if (formData.data.prcId) {
              const status = yield call(
                bpmService.doCheckActived,
                formData.data.prcId
              );
              if (status.success) {
                if (status.data) {
                  yield put(
                    routerRedux.push(
                      `/source-mgmt/bid-mgmt/tender-review/${payload.id}`
                    )
                  );
                } else {
                  Modal.error({
                    title: customMsg.NOT_ACTIVE_HANDLER // 您不是当前处理人
                  });
                }
              }
            } else {
              if (payload.item.docStatus === bidStatus.PENDING_ADJUST) {
                yield put(
                  routerRedux.push(
                    `/source-mgmt/bid-mgmt/tender-review/${payload.id}`
                  )
                );
              } else {
                message.warn(
                  '不能对' + payload.item.docStatusName + '的招标单发起审批'
                );
              }
            }
          } else {
            message.error(formData.message);
          }
        } else if (payload.mode === 'update') {
          const data = yield call(examService.canBid, payload.id);
          if (data.success) {
            yield put(
              routerRedux.push(
                `/source-mgmt/bid-mgmt/exam/${payload.id}?mode=update`
              )
            );
          } else {
            message.warn(data.message);
          }
        } else if (payload.mode === 'view') {
          const formData = yield call(tenderService.review, payload.id);
          if (formData.success) {
            const { docStatus } = formData.data;
            if (docStatus !== bidStatus.TO_OPEN_BID) {
              yield put(
                routerRedux.push(
                  `/source-mgmt/bid-mgmt/exam/${payload.id}?mode=view`
                )
              );
            } else {
              message.warn(resultCode.NG_NOT_OPEN_BID);
            }
          } else {
            throw formData;
          }
        } else if (payload.mode === 'apprview') {
          yield put(
            routerRedux.push(
              `/source-mgmt/bid-mgmt/tender-result/${payload.id}`
            )
          );
        }
      }
    },
    *delete({ payload }, { call, put }) {
      const data = yield call(examService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    *create({ payload }, { put, call }) {
      const data = yield call(examService.create, payload);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    *update({ payload }, { put, call, select }) {
      const id = yield select(({ tenderForm }) => tenderForm.currentItem.id);
      const newData = { ...payload, id };
      const data = yield call(examService.update, newData);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    *showPop({ payload }, { put, call }) {
      yield put({
        type: 'showModal',
        payload: {
          mode: payload.mode
        }
      });
    },
    *hideModal({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {}
        }
      });
    },
    *clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          filterParams: {}
        }
      });
    }
  },

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

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