import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import * as tenderService from '../../../services/source/tenders';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { enums } from '@utils';
import { message } from 'antd';
import * as bpmService from '../../../services/common/bpm';
const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const { bidStatus, resultCode, viewMode } = enums;
export default {

  namespace: 'tenderReview',

  state: {
    formData: {},
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    submitBtnFlag: false,
    acceptBtnFlag: false,
    mode: 'view',
    sData: {
      businessName: '商务部分（50分）',
      registeredCapitalName: '注册资本（5）',
      enterpriseQualificationName: '企业资质及等级（5）',
      enterpriseReputationName: '企业荣誉及知名度（5）',
      enterpriseSalesName: '企业销售业绩（5）',
      quotationName: '报价得分（30）',
      technicalName: '技术部分（50分）',
      qualityContentName: '质量内容（40）',
      saleServiceName: '售后服务（10）'
    },
    sList: [],
    remoteCfg: null,
    advice: '',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        const match = pathToRegexp('/source-mgmt/bid-mgmt/tender-review/:id').exec(location.pathname);
        // console.log('match==>',match);
        if (match) {
          dispatch({ type: 'query', payload: match[1] });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      // console.warn('you are in review', payload)
      // 角色判断soum_bm_em_submit/  soum_bm_em_accept
      let { submitBtnFlag, acceptBtnFlag } = yield select(({ tenderReview }) => tenderReview);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_bm_em_submit';
        })) {
          submitBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_bm_em_accept';
        })) {
          acceptBtnFlag = true;
        }
      }
      // 初始配置文件参数
      const params = {
        defId: 'BidResultEvaluation:',
        nodeId: bidStatus.PENDING_ADJUST ? 'initiator' : 'purchasingDirector',
        mode: viewMode.VIEW,
      };
      // console.log('param==>',params)
      // 远程文件配置
      const cfgData = yield call(bpmService.getFormCfg, params);
      console.log('cfgdata==>', cfgData)
      if (cfgData.success) {
        yield put({
          type: 'updateState',
          payload: {
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw cfgData;
      }
      const data = yield call(tenderService.review, payload);
      // console.log('data==>',data)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            formData: data.data,
            list: data.data.items,
            submitBtnFlag,
            acceptBtnFlag,
            advice:'',
          },
        });
      } else {
        throw data;
      }
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          submitBtnFlag: false,
          acceptBtnFlag: false,
          mode: 'view',
          sList: [],
          remoteCfg: null,
          advice: '',
        },
      });
    },

    * cancel({ payload }, { put }) {
      yield put(routerRedux.goBack());
    },

    * status({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ tenderReview }) => tenderReview.formData);
      const advice = yield select(({ tenderReview }) => tenderReview.advice);
      if (!advice.trim()) {
        message.error('请填写审批意见');
        return;
      }

      const { list } = yield select(({ tenderReview }) => tenderReview);
      if (bidStatus.TO_FINAL_CONFIRMATION === payload) {
        const result = yield call(tenderService.checkPercent, list);
        if (result.length === 0) {
          const data = yield call(tenderService.status, { id: formData.id, prcId: formData.prcId, status: payload, items: list, advice });
          if (data.success) {
            if (formData.taskId) {
              const bpmdata = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
              if (bpmdata.success) {
                message.success(resultCode.OK);
                yield put({ type: 'cancel' });
              } else {
                throw bpmdata;
              }
            } else {
              message.success(resultCode.OK);
              yield put({ type: 'cancel' });
            }
          } else {
            throw data;
          }
        } else {
          message.warn(result[0]);
        }
      } else {
        const data = yield call(tenderService.status, { id: formData.id, prcId: formData.prcId, status: payload, items: list, advice });
        if (data.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw data;
        }
      }
    },

    * finalStatus({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ tenderReview }) => tenderReview.formData);
      const list = yield select(({ tenderReview }) => tenderReview.list);
      const advice = yield select(({ tenderReview }) => tenderReview.advice);
      if (bidStatus.FINISH !== payload && !advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(tenderService.finalDocStatus, { id: formData.id, prcId: formData.prcId, status: payload, items: list });
      if (data.success) {
        const bpmdata = yield call(bidStatus.FINISH === payload ? bpmService.doApprove : bpmService.doReject,
          { taskId: formData.taskId, advice });
        if (bpmdata.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw bpmdata;
        }
      } else {
        throw data;
      }
    },

    * suppScore({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const data = yield call(tenderService.suppScore, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            sData: data.data,
            sList: data.data.scoreList,
          },
        });
        yield put({ type: 'showModal' });
      } else {
        throw data;
      }
    },


    * hideModal({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
    },
  },

  reducers: {

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

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

    updateCell(state: object, { payload }: ReduxAction) {
      const { list } = state;
      // console.log('list1==>',list)
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      if (key === 'bidPercent') {
        if (value) {
          const tenderQty = newList[index].tenderQty;
          if (tenderQty) {
            // const bidQty = (value * tenderQty).toFixed(2);
            const bidQty = ((value / 100) * tenderQty).toFixed(2);
            const bidPrice = newList[index].taxPrice;
            const bidAmt = (bidQty * bidPrice).toFixed(2);
            newList[index].bidPrice = bidPrice;
            newList[index].bidQty = bidQty;
            newList[index].bidAmt = bidAmt;
          } else {
            newList[index].bidQty = null;
            newList[index].bidAmt = null;
          }
        } else {
          newList[index].bidQty = null;
          newList[index].bidAmt = null;
        }
      }
      return {
        ...state,
        list: newList,
      };
    },
  },
}
