import * as tenderService from '../../../services/source/tenders';
import * as bidGroupDetailService from '../../../services/source/bidGroupDetail';
import * as bpmService from '../../../services/common/bpm';
import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import { enums, stringUtils } from '@utils';

const { customMsg, bidStatus, entType } = enums;
export default {
  namespace: 'tenderForm',

  state: {
    list: [],
    total: 0,
    formData: {},
    currentItem: {},
    modalVisible: false,
    groupModalVisible: false,
    mode: 'create',
    suppFlag: false,
    addBtnFlag: false,
    editBtnFlag: false,
    viewBtnFlag: false,
    deleteBtnFlag: false,
    approvalBtnFlag: false,
    bidViewBtnFlag: false,
    bidTeamBtnFlag: false,
    bidResultBtnFlag: false,
    groupData: {},
    groupList: []
  },

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

  effects: {
    *query({ payload }, { call, put, select }) {
      // 角色判断
      /*soum_bm_ts_add/soum_bm_ts_edit/soum_bm_ts_view/soum_bm_ts_delete/
      soum_bm_ts_approval/soum_bm_ts_bidView/soum_bm_ts_bidTeam/soum_bm_ts_bidResult*/
      let {
        addBtnFlag,
        editBtnFlag,
        viewBtnFlag,
        deleteBtnFlag,
        approvalBtnFlag,
        bidViewBtnFlag,
        bidTeamBtnFlag,
        bidResultBtnFlag
      } = yield select(({ tenderForm }) => tenderForm);
      const perms = yield select(({ app }) => app.perms);
      if (perms) {
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_add';
          })
        ) {
          addBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_edit';
          })
        ) {
          editBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_view';
          })
        ) {
          viewBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_delete';
          })
        ) {
          deleteBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_approval';
          })
        ) {
          approvalBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_bidView';
          })
        ) {
          bidViewBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_bidTeam';
          })
        ) {
          bidTeamBtnFlag = true;
        }
        if (
          perms.find(x => {
            return x.menuId === 'soum_bm_ts_bidResult';
          })
        ) {
          bidResultBtnFlag = true;
        }
      }

      if (!payload.bpmStatus) {
        payload.bpmStatus = 'NONE';
      }
      const currentUser = yield select(({ app }) => app.user);
      const data = yield call(tenderService.query, payload);
      if (data.success) {

        if (data.data.rows) {
          data.data.rows.map(row => {
            row.intervalDate = `${row.bidFromDate}--${row.bidToDate}`;
          })
        }

        yield put({
          type: 'updateState',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            suppFlag: entType.SUPP === currentUser.user.entType ? true : false,
            addBtnFlag,
            editBtnFlag,
            viewBtnFlag,
            deleteBtnFlag,
            approvalBtnFlag,
            bidViewBtnFlag,
            bidTeamBtnFlag,
            bidResultBtnFlag
          }
        });
        yield put(
          routerRedux.replace({
            pathname: location.pathname,
            search: '?' + stringUtils.JSON2QueryString(payload)
          })
        );
      } else {
        throw data;
      }
    },

    *querySingle({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(tenderService.getSingle, payload.id);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode
          }
        });
      } else {
        throw data;
      }
    },

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

      if (payload.mode === 'create') {
        yield put(
          routerRedux.push('/source-mgmt/bid-mgmt/tenders/tenders/create')
        );
      } else {
        const formData = yield call(tenderService.getSingle, payload.id);
        if (formData.success) {
          if (payload.mode === 'view') {
            const currentUser = yield select(({ app }) => app.user);
            if (entType.SUPP === currentUser.user.entType) {
              const flagData = yield call(tenderService.suppHas, payload.id);
              if (flagData.success) {
                yield put(
                  routerRedux.push(
                    `/source-mgmt/bid-mgmt/tenders/tenders/${
                      payload.id
                    }?mode=view`
                  )
                );
              } else {
                message.warn('您的资质不够，不能查看或进行投标');
              }
            } else {
              yield put(
                routerRedux.push(
                  `/source-mgmt/bid-mgmt/tenders/tenders/${
                    payload.id
                  }?mode=view`
                )
              );
            }
          } else if (payload.mode === 'update') {
            const currentUser = yield select(({ app }) => app.user);
            if (
              formData.data.docStatus === bidStatus.WAITING &&
              formData.data.createUserId === currentUser.user.id
            ) {
              yield put(
                routerRedux.push(
                  `/source-mgmt/bid-mgmt/tenders/tenders/${
                    payload.id
                  }?mode=update`
                )
              );
            } else if (formData.data.docStatus !== bidStatus.WAITING) {
              message.warn(
                formData.data.docStatusName + customMsg.PE_NOT_UPDATE
              );
            } else {
              message.warn(customMsg.PE_NOT_CREATEUSER);
            }
          } else if (payload.mode === 'approval') {
            if (
              !formData.data.prcId ||
              formData.data.docStatus !== bidStatus.APPROVING
            ) {
              message.error(
                formData.data.docStatusName + customMsg.PE_NOT_APPROVAL
              );
            } else {
              const status = yield call(
                bpmService.doCheckActived,
                formData.data.prcId
              );
              if (status.success) {
                if (status.data) {
                  yield put(
                    routerRedux.push(
                      `/source-mgmt/bid-mgmt/tenders/tenders/${
                        payload.id
                      }?mode=approval`
                    )
                  );
                } else {
                  Modal.error({
                    title: customMsg.NOT_ACTIVE_HANDLER // 您不是当前处理人
                  });
                }
              }
            }
          }
        } else {
          message.error(formData.message);
        }
      }
    },

    *bidView(
      { payload }: ReduxAction,
      { select, call, put }: ReduxSagaEffects
    ) {
      if (
        payload.docStatus !== bidStatus.WAITING &&
        payload.docStatus !== bidStatus.APPROVING
      ) {
        yield put(
          routerRedux.push(
            `/source-mgmt/bid-mgmt/bids/bids?docNoName=${payload.docNo}`
          )
        );
      } else {
        message.warn('该招标单还未开始投标');
      }
    },

    *bidGroupView(
      { payload }: ReduxAction,
      { select, call, put }: ReduxSagaEffects
    ) {
      if (
        payload.docStatus == bidStatus.PENDING_ADJUST ||
        payload.docStatus == bidStatus.TO_FINAL_CONFIRMATION ||
        payload.docStatus == bidStatus.FINISH
      ) {
        const formData = yield call(tenderService.groupView, payload.id);
        if (formData.success) {
          yield put({
            type: 'updateState',
            payload: {
              groupData: formData.data,
              groupList: formData.data.members
            }
          });
        } else {
          throw formData;
        }
      } else {
        const formData = yield call(
          bidGroupDetailService.getSingle,
          payload.groupId
        );
        if (formData.success) {
          yield put({
            type: 'updateState',
            payload: {
              groupData: formData.data,
              groupList: formData.data.members
            }
          });
        } else {
          throw formData;
        }
      }
      yield put({
        type: 'showGroupModal'
      });
    },

    *bidResult(
      { payload }: ReduxAction,
      { select, call, put }: ReduxSagaEffects
    ) {
      if (
        payload.docStatus === bidStatus.FINISH ||
        payload.docStatus === bidStatus.DROP
      ) {
        yield put(
          routerRedux.push(`/source-mgmt/bid-mgmt/tender-result/${payload.id}`)
        );
      } else {
        message.warn('该招标单评标尚未结束');
      }
    },

    *delete({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const formData = yield call(tenderService.getSingle, payload.ids[0]);
      if (formData.success) {
        const currentUser = yield select(({ app }) => app.user);
        if (formData.data.docStatus === bidStatus.WAITING) {
          if (formData.data.createUserId === currentUser.user.id) {
            const data = yield call(tenderService.remove, [...payload.ids]);
            if (data.success) {
              yield put({ type: 'query', payload: {} });
            } else {
              throw data;
            }
          } else {
            message.warn('不能作废别人的招标单');
          }
        } else {
          message.warn(formData.data.docStatusName + customMsg.PE_NOT_DELETE);
        }
      } else {
        message.warn(customMsg.PE_QUERY_FAIL);
      }
    },

    *clean({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {}
      });
    }
  },

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

    showGroupModal(state: object, action: ReduxAction) {
      return { ...state, ...action.payload, groupModalVisible: true };
    },

    groupHideModal(state: object, action: ReduxAction) {
      return {
        ...state,
        ...action.payload,
        groupModalVisible: false,
        groupList: []
      };
    }
  }
};
