import * as suppliersService from '../../services/supplier/suppliers';
import * as bpmService from '../../services/common/bpm';
import { routerRedux } from 'dva/router';
import { message, } from 'antd';
import { enums, stringUtils } from '@utils';

const { entType } = enums;

export default {

  namespace: 'suppliers',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    mode: 'create',
    editBtn: true,// 是否隐藏按钮 true隐藏 false不隐藏
    approvalBtn: true,
    adjustBtn: false,
    filterParams: {},
    supplier: {}
  },

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

  //
  effects: {
    * query({ payload }, { call, select, put }) {

      let { approvalBtn,editBtn,adjustBtn } = yield select(({ suppliers }) => suppliers);
      const perms = yield select(({ app }) => app.perms);
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'lf_sm_update') {
            editBtn = false;
          } else if (p.menuId === 'lf_sm_approval') {
            approvalBtn = false;
          } else if (p.menuId === 'lf_sm_adjust') {
            adjustBtn = true;
          }
        }
      }
      const currentItem = yield select(({ suppliers }) => suppliers.currentItem);
      const data = yield call(suppliersService.query, { ...currentItem, ...payload });
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            editBtn,
            approvalBtn,
            adjustBtn,
            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, select }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      if (payload.mode === 'view') {
        yield put(routerRedux.push(`/lifecycle/supp-mgmt/${payload.id}?mode=view`));
      } else if (payload.mode === 'qualify') {
        yield put(routerRedux.push(`/lifecycle/qualify/${payload.id}`));
      } else if (payload.mode === 'adjust') {
        yield put(routerRedux.push(`/lifecycle/supp-mgmt/adjust/${payload.id}?mode=${payload.mode}`));
      } else {
        const suppData = yield call(suppliersService.getSingle, payload.id);
        if (suppData.success) {
          const edpPbSupp = suppData.data.edpPbSupp;
          if (payload.mode === 'update') {
            const currentUser = yield select(({ app }) => app.user.user);
            if (currentUser.empCode === edpPbSupp.suppCode) {
              if (edpPbSupp.suppStatus === '01' || edpPbSupp.suppStatus === '02' || edpPbSupp.suppStatus === '04') {
                if (edpPbSupp.approveStatus !== '01') {
                  yield put(routerRedux.push(`/lifecycle/supp-mgmt/${payload.id}?mode=${payload.mode}`));
                } else {
                  message.error('该供应商当前状态不能修改');
                }
              } else {
                message.error('该供应商当前状态不能修改');
              }
            } else {
              message.error('只有当前供应商的用户可以修改资料');
            }
          }

          if (payload.mode === 'updateQualify') {
            const currentUser = yield select(({ app }) => app.user.user);
            if (currentUser.empCode === edpPbSupp.suppCode) {
              if (edpPbSupp.suppStatus === '02' || edpPbSupp.suppStatus === '04') {
                if (edpPbSupp.approveStatus !== '01') {
                  yield put(routerRedux.push(`/lifecycle/supp-mgmt/${payload.id}?mode=${payload.mode}`));
                } else {
                  message.error('该供应商当前状态不能更新资质');
                }
              } else {
                message.error('该供应商当前状态不能更新资质');
              }
            } else {
              message.error('只有当前供应商的用户可以更新资质');
            }
          }

          if (payload.mode === 'approval') {
            if (!suppData.data.prcId || edpPbSupp.approveStatus !== '01') {
              message.error('该供应商当前状态不能进行审批');
            } else {
              const status = yield call(bpmService.doCheckActived, suppData.data.prcId);
              if (status.success) {
                if (status.data) {
                  yield put(routerRedux.push(`/lifecycle/supp-mgmt/${payload.id}?mode=approval`));
                } else {
                  message.error('您不是当前处理人，不能进行审批');
                }
              }
            }
          }
        }
      }
    },

    * delete({ payload }, { call, put }) {
      const suppData = yield call(suppliersService.getSingle, payload.id);
      if (suppData.success) {
        if (suppData.data.edpPbSupp.suppStatus === '01' || suppData.data.edpPbSupp.suppStatus === '02') {
          payload.function();
        } else {
          return message.error('该供应商当前状态不能作废');
        }
      }
    },

    * disable({ payload }, { call, put }) {
      const data = yield call(suppliersService.disable, payload.id);
      if (data.success) {
        yield put({ type: 'query' });
      } 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
          },
          currentItem: {
            suppCodeName: stringUtils.queryURL('suppCodeName'),
            region: stringUtils.queryURL('region') ? stringUtils.queryURL('region').split('%2C') : [],
            suppStatus: stringUtils.queryURL('suppStatus'),
            approveStatus: stringUtils.queryURL('approveStatus'),
            invTypeList: stringUtils.queryURL('invTypeList'),
            gysylsx: stringUtils.queryURL('gysylsx') ? stringUtils.queryURL('gysylsx').split('%2C') : [],
            activeTaskKey: stringUtils.queryURL('activeTaskKey'),
            bpmStatus: stringUtils.queryURL('bpmStatus'),
          },
        },
      });
    },

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

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

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

  },

};
