import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as bpmService from '@services/common/bpm';
import * as adjustService from '@services/item/priceAdjust';
import { dataUtils } from '@utils';
import { numberUtils } from '@utils';

export default {

  namespace: 'priceAdjust',

  state: {
    mode: 'create',
    formData: {},
    advice: '',
    remoteCfg: null,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/price-mgmt/adjust/:id').exec(location.pathname);
        console.log(match);
        if (match) {
          dispatch({ type: 'clean' });
          const mode = dataUtils.queryStringToJSON(location.search).mode;
          dispatch({ type: 'query', payload: { id: match[1], mode } });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      let { id, mode } = payload;
      let data;
      if (mode === 'create') {
        data = yield call(adjustService.initial, id);
      } else {
        data = yield call(adjustService.getSingle, id);
      }
      if (mode === 'approval') {
        const status = yield call(bpmService.doCheckActived, data.data.prcId);
        if (status.success) {
          if (!status.data) {
            Modal.error({
              title: '您不是当前处理人',
              okText: '确认'
            });
            mode = 'view';
          }
        }
      }
      const formData = data.data;
      const params = {
        defId: 'PriceAdjust:2:1669476',
        nodeId: 'initiator',
        mode: formData.taskKey === 'initiator' ? mode === 'view' ? mode : 'create' : mode,
      };
      const cfgData = yield call(adjustService.remoteCfg, params);
      if (data.success) {
        formData.validDate = dataUtils.ymd(formData.validDateFrom) + '-' + dataUtils.ymd(formData.validDateTo);
        formData.taxPriceStr = numberUtils.round_half_up_format(formData.taxPrice, 4);
        yield put({
          type: 'updateState',
          payload: {
            formData: formData,
            mode: formData.taskKey === 'initiator' ? mode === 'view' ? mode : 'create' : mode,
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw data;
      }
    },

    * submit({ payload }, { select, call, put }) {
      const formData = yield select(({ priceAdjust }) => priceAdjust.formData);
      if (!formData.adjustPrice) {
        message.error('调整后价格必填');
        return;
      }
      if (formData.adjustPrice === formData.taxPrice) {
        message.error('调整后价格不可和执行价格相等');
        return;
      }
      const data = yield call(adjustService.submit, formData);
      if (data.success) {
        yield put(routerRedux.goBack());
      } else {
        throw data;
      }
    },

    * approve({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ priceAdjust }) => priceAdjust);
      // if (!advice.trim()) {
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      if (data.success) {
        yield put(routerRedux.push('/price-mgmt/adjust'));
      } else {
        throw data;
      }
    },

    * reject({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ priceAdjust }) => priceAdjust);
      if (!advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      if (data.success) {
        yield put(routerRedux.push('/price-mgmt/adjust'));
      } else {
        throw data;
      }
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: 'create',
          formData: {},
          advice: '',
          remoteCfg: null,
        },
      });
    },

    * cancel({ payload }, { put, select }) {
      yield put({ type: 'clean' });
      yield put(routerRedux.goBack());
    },
  },

  reducers: {

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

    updateForm(state, { payload }) {
      const { key, value } = payload;
      const formData = state.formData;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },

  }
};
