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

const { customMsg, peStatus, entType } = enums;
export default {

  namespace: 'inquiryForm',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    filterParams: {},
    suppFlag: false,
    addBtnFlag: false,
    editBtnFlag: false,
    viewBtnFlag: false,
    deleteBtnFlag: false,
    copyBtnFlag: false,
    approvalBtnFlag: false,
    previewBtnFlag: false,
    yijiaBtnFlag: false,
    yjconfirmBtnFlag: false,
    yjAdjustBtnFlag: false,
    exportBtnFlag: false,
  },

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

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // 角色判断
      /*soum_qo_iqo_add/soum_qo_iqo_edit/soum_qo_iqo_view/soum_qo_iqo_delete
      soum_qo_iqo_copy/soum_qo_iqo_approval/ soum_qo_iqo_preview*/
      let { addBtnFlag, editBtnFlag, viewBtnFlag, deleteBtnFlag, exportBtnFlag,
        copyBtnFlag, approvalBtnFlag, previewBtnFlag, yijiaBtnFlag, yjconfirmBtnFlag, yjAdjustBtnFlag
      } = yield select(({ inquiryForm }) => inquiryForm);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_add';
        })) {
          addBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_edit';
        })) {
          editBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_view';
        })) {
          viewBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_delete';
        })) {
          deleteBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_copy';
        })) {
          copyBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_approval';
        })) {
          approvalBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_preview';
        })) {
          previewBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_quote';
        })) {
          yijiaBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_yjcfm';
        })) {
          yjconfirmBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_yjAdj';
        })) {
          yjAdjustBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_comp_export';
        })) {
          exportBtnFlag = true;
        }
      }
      const currentUser = yield select(({ app }) => app.user);
      const data = yield call(inquiryService.query, payload);
      if (data.success) {
        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, copyBtnFlag, approvalBtnFlag, previewBtnFlag,
            yijiaBtnFlag, yjconfirmBtnFlag, exportBtnFlag, yjAdjustBtnFlag,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
          // state: { ...payload },
        }));
      } else {
        throw data;
      }
    },
    * querySingle({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(inquiryService.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/qo/iqo/create'));
      } else {
        const formData = yield call(inquiryService.getSingle, payload.id);
        if (formData.success) {
          // console.log('formdata==>',formData)
          if (payload.mode === 'view') {
            const currentUser = yield select(({ app }) => app.user);
            if (entType.SUPP === currentUser.user.entType) {
              if (formData.data.itemList.length > 0) {
                // 供应商点击"查看"按钮，如果询价单为"报价中"，则实际进行报价操作，如果不是，则实际为查看操作
                if(formData.data.docStatus === '03' /* 报价中 */) {
                  // 供应商进入报价页面，实际判断在详情页面当中进行
                  yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=view`));
                } else { /* 议价中及后续状态，供应商看到的画面 */
                  // 供应商进入查看页面
                  yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=quoteview`));
                }
              } else {
                message.warn('询价单中的物料都做过报价了');
              }
            } else {
              yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=view`));
            }
          } else if (payload.mode === 'quote') {
            const data = yield call(inquiryService.queryPqItem, payload.id);
            if (data.success) {
              var pqdsCount = null != (data.data && data.data.length) ? data.data.length : 0;
              if (pqdsCount > 0) {
                yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=quote`));
              } else {
                message.warn('供应商尚未报价，不能执行该操作');
              }
            } else {
              throw data;
            }
          } else if (payload.mode === 'yjAdjust') {
            // 议价调整
            const data = yield call(inquiryService.queryPqItem, payload.id);
            if (data.success) {
              var pqdsCount = null != (data.data && data.data.length) ? data.data.length : 0;
              if (pqdsCount > 0) {
                yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=yjAdjust`));
              } else {
                message.warn('供应商尚未报价，不能执行该操作');
              }
            } else {
              throw data;
            }
          } else if (payload.mode === 'yjconfirm') {
            const data = yield call(inquiryService.queryPqItem, payload.id);
            if (data.success) {
              var pqdsCount = null != (data.data && data.data.length) ? data.data.length : 0;
              if (pqdsCount > 0) {
                yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=yjconfirm`));
              } else {
                message.warn('尚未报价，不能执行该操作');
              }
            } else {
              throw data;
            }
          } else if (payload.mode === 'update') {
            // console.log('update==>',formData)
            const currentUser = yield select(({ app }) => app.user);
            if (formData.data.docStatus === peStatus.WAITING && formData.data.createUserId === currentUser.user.id) {
              yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=update`));
            } else if (formData.data.docStatus !== peStatus.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 === peStatus.FINISH
              || formData.data.docStatus === peStatus.PRICING) {
              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/qo/iqo/${payload.id}?mode=approval`));
                } else {
                  Modal.error({
                    title: customMsg.NOT_ACTIVE_HANDLER, // 您不是当前处理人
                  });
                }
              }
            }
          }
        } else {
          message.error(formData.message);
        }
      }
    },
    * copy({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      yield put(routerRedux.push(`/source-mgmt/qo/iqo/${payload.id}?mode=${payload.mode}&operate=copy`));
    },

    * viewQuote({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put(routerRedux.push(`/source-mgmt/qo/qo?docNo=${payload.docNo}`));
    },
    * delete({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(inquiryService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },
    * create({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const data = yield call(inquiryService.create, payload);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * update({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const id = yield select(({ inquiryForm }) => inquiryForm.currentItem.id);
      const newData = { ...payload, id };
      const data = yield call(inquiryService.update, newData);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * showPop({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      yield put({
        type: 'showModal',
        payload: {
          mode: payload.mode,
        }
      });
    },
    * hideModal({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
    },
    * clean({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          filterParams: {},
        },
      });
    },
  },

  reducers: {

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

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