import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as quoteService from '../../../services/source/quote';
import * as compareService from '../../../services/source/compare';
import { dataUtils, formUtils } from '../../../utils';
import { numberUtils } from '@utils';

export default {

  namespace: 'quoteDetails',

  state: {
    formData: {},
    list: [],
    substituteList: [],
    total: 0,
    currentItem: {},
    mode: 'update',
    itemId: null,
    suppCenterId: null,
    confirmBtnFlag: false
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen((location) => {
        // dispatch({ type: 'clean' });
        // dispatch({ type: 'query' });
        const match = pathToRegexp('/source-mgmt/qo/price').exec(location.pathname);
        // console.log('match==>',match)
        // console.log('querystring',dataUtils.queryStringToJSON(location.search))
        // dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
        if (match) {
          const queryparam = dataUtils.queryStringToJSON(location.search);
          // dispatch({ type: 'query', payload: { itemId: queryparam.itemId, suppCenterId: queryparam.suppCenterId } });
          dispatch({ type: 'query', payload: { peDocIds: queryparam.peDocIds } });
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // 角色判断 soum_qo_qo_confirm
      let { confirmBtnFlag } = yield select(({ quoteDetails }) => quoteDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_qo_confirm';
        })) {
          confirmBtnFlag = true;
        }
      }
      // console.log("query==>",payload);
      yield put({
        type: 'updateState',
        payload: {
          confirmBtnFlag
        },
      });
      const formData = yield call(quoteService.getSingle, payload);
      // console.log("formData==>",formData)
      if (formData.success) {
        formData.data.priceInterval = formData.data.priceEffectDate + "--" + formData.data.priceExpireDate;
        //格式化数字
        if (formData.data.srmCompItemsInfoList) {
          formData.data.srmCompItemsInfoList.map((i) => {
            i.estimatedNumStr = i.estimatedNum ? numberUtils.round_half_up_format(i.estimatedNum, 2) : null;
            i.minNumStr = i.minNum ? numberUtils.round_half_up_format(i.minNum, 2) : null;
            i.bargainWithTaxStr = i.bargainWithTax ? numberUtils.round_half_up_format(i.bargainWithTax,4) : null;
            i.quoteWithTaxStr = i.quoteWithTax ? numberUtils.round_half_up_format(i.quoteWithTax,4) : null;
            i.marginPriceStr = i.marginPrice ? numberUtils.round_half_up_format(i.marginPrice,4) : null;
            i.netPriceStr = i.netPrice ? numberUtils.round_half_up_format(i.netPrice,4) : null;
            i.amtStr = i.amt ? numberUtils.round_half_up_format(i.amt,2) : null;
            i.netAmtStr = i.netAmt ? numberUtils.round_half_up_format(i.netAmt,2) : null;
            i.taxAmtStr = i.taxAmt ? numberUtils.round_half_up_format(i.taxAmt,2) : null;
            i.maxProvideNumStr = i.maxProvideNum ? numberUtils.round_half_up_format(i.maxProvideNum,2) : null;
            i.lastPriceStr = i.lastPrice ? numberUtils.round_half_up_format(i.lastPrice,4) : null;
            i.lastYearPriceStr = i.lastYearPrice ? numberUtils.round_half_up_format(i.lastYearPrice,4) : null;
            i.itemOuterPriceStr = i.itemOuterPrice ? numberUtils.round_half_up_format(i.itemOuterPrice,4) : null;
            i.allottedQuantityStr = i.allottedQuantity ? numberUtils.round_half_up_format(i.allottedQuantity,2) : null;
            i.allottedAmtStr = i.allottedAmt ? numberUtils.round_half_up_format(i.allottedAmt,2) : null;
          });
        }
        yield put({
          type: 'updateState',
          payload: {
            formData: formData.data,
            list: formData.data.srmCompItemsInfoList ? formData.data.srmCompItemsInfoList : [],
            substituteList: formData.data.substituteList ? formData.data.substituteList : [],
          },
        });
      } else {
        throw formData;
      }
    },
    * update({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const detailView = yield select(({ quoteDetails }) => quoteDetails.formData);
      // const list = yield select(({ quoteDetails }) => quoteDetails.list);
      // const newList = [];
      // for (const ids of payload.selectedRowKeys) {
      //   for (const item of list) {
      //     if (item.pqdId === ids) {
      //       newList.push(item);
      //     }
      //   }
      // }
      // const newData = {
      //   compareList: list,
      // };
      const data = yield call(compareService.submit, detailView);
      if (data.success) {
        message.success('操作成功');
        // const itemId = yield select(({ quoteDetails }) => quoteDetails.itemId);
        // const suppCenterId = yield select(({ quoteDetails }) => quoteDetails.suppCenterId);
        yield put({ type: 'cancel' });
        // yield put({
        //   type: 'query', payload: {
        //     itemId,
        //     suppCenterId
        //   }
        // });
      } else {
        throw data;
      }
    },

    //获取替代料列表
    * substitutes({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const result = yield call(compareService.substitutes, payload);
      if (result.success) {
        result.data.priceInterval = result.data.fromDate + "--" + result.data.toDate;
        yield put({
          type: 'updateState',
          payload: {
            substituteList: result.data ? result.data : []
          },
        });
      } else {
        throw result;
      }
    },

    * redirect({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put(routerRedux.push(`/source-mgmt/qo/qo`));
    },
    * cancel({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put({ type: 'clean' });
      // yield put({ type: 'redirect' });
      yield put(routerRedux.goBack());
    },
    * clean({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          list: [],
          substituteList: [],
          total: 0,
          currentItem: {},
          mode: 'update',
          itemId: null,
          suppCenterId: null,
        },
      });
    },
  },

  reducers: {
    updateCell(state: object, { payload }: ReduxAction) {
      console.log("updateCell-payload==>",payload);
      console.log("updateCell-state==>",state);
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      if (key === 'percent' && (value===0 || value)) {
        const number = newList[index]['estimatedNum'] * value/100;
        newList[index]['allottedQuantity'] = parseFloat(number).toFixed(2);
        newList[index]['allottedQuantityStr'] = newList[index]['allottedQuantity'].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        newList[index]['allottedAmt'] = parseFloat(number * newList[index]['bargainWithTax']).toFixed(2);
        newList[index]['allottedAmtStr'] = newList[index]['allottedAmt'].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }else{
        newList[index]['allottedQuantity']=null;
        newList[index]['allottedQuantityStr']=null;
        newList[index]['allottedAmt']=null;
        newList[index]['allottedAmtStr']=null;
      }
      return {
        ...state,
        list: newList,
      };
    },

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