import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { dataUtils, stringUtils, enums } from '@utils';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as quoteService from '../../../services/source/quote';
import inquiry from '../inquiry/inquiry';
import { numberUtils } from '@utils';

const { entType } = enums;

export default {

  namespace: 'quoteForm',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'update',
    filterParams: {},
    priceBtnFlag: false,
    supplier: {},
    inquiryUser:{},//是否采购专员
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen((location) => {
        // console.log("location==>", location)
        const match = pathToRegexp('/source-mgmt/qo/qo').exec(location.pathname);
        // console.log('match==>',match)
        /*if (match) {
          const queryparam = dataUtils.queryStringToJSON(location.search);
          // console.log('queryparam',queryparam+'-'+queryparam['docNo']+'-'+queryparam['suppCode'])
          if (queryparam['docNo']) {
            // console.log('queryparam2',queryparam)
            /!*dispatch({
              type: 'updateState',
              payload: {
                filterParams: {
                  // docNo: queryparam['docNo'],
                  peDocNo: queryparam['docNo'],
                  suppCode: queryparam['suppCode'],
                  // suppName: queryparam['suppCode']
                },
              },
            });*!/
            dispatch({type: 'query', payload: {peDocNo: queryparam['docNo']}});
          }
        }*/
        // if (location.pathname === '/source-mgmt/qo/qo') {
        // dispatch({ type: 'clean' });
        // dispatch({ type: 'query' });
        // }
        if (location.pathname === '/source-mgmt/qo/qo') {
          dispatch({ type: 'pageDataClean' });
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // 角色判断 soum_qo_qo_price
      let { priceBtnFlag } = yield select(({ quoteForm }) => quoteForm);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_qo_qo_price';
          })) {
          priceBtnFlag = true;
        }
      }
      const data = yield call(quoteService.query, payload);
      if (data.success) {
        if(data.data && data.data.rows){
          data.data.rows.map((i) => {
            // i.estimatedAmtStr = i.estimatedAmt
            //   ? parseFloat(i.estimatedAmt).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
            //   : null;
            const number = i.estimatedNum * i.percent/100;
            i.allowedNumber = (i.percent || i.percent===0)
              ? parseFloat(number).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              : null;
            i.allowedAmt = (i.percent || i.percent===0)
              ? parseFloat(number*i.yjPrice).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              : null;

            // 删除原因：列表渲染时也做了格式化，两边有冲突；
            // //含税单价format
            // i.price = numberUtils.round_half_up_format(i.price,4);
            // //未税单价format
            // i.netPrice = numberUtils.round_half_up_format(i.netPrice,4);

          });
        }
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            priceBtnFlag
          },
        });
        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(quoteService.getSingle, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        throw data;
      }
    },
    * getSingle({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      // console.log("getSingle-payload==>", payload)
      yield put(
        routerRedux.push(`/source-mgmt/qo/price/${payload.id}?itemId=${payload.itemId}&suppCenterId=${payload.suppCenterId}`)
      );
    },

    * delete({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(quoteService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * create({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const data = yield call(quoteService.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(({ quoteForm }) => quoteForm.currentItem.id);
      const newData = { ...payload, id };
      const data = yield call(quoteService.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: {},
        },
      });
    },
    * pageDataClean({ payload }, {call, put, select }) {
      const { user } = yield select(({ app }) => app.user);
      let { inquiryUser } = yield select(({ quoteForm }) => quoteForm);
      const data=yield call(quoteService.isPurchasingStaff);
      if(data.success){
        inquiryUser={
          inquiryUser:data.data,
          inquiryUserName:user.name,
        }
      }else{
        throw data;
      }
      yield put({
        type: 'updateState',
        payload: {
          supplier: {
            supplier: user.entType === entType.SUPP,
            suppName: user.name
          },
          inquiryUser:inquiryUser,
        },
      });
    },
  },

  reducers: {

    querySuccess(state: object, action: ReduxAction) {
      const { list, total, priceBtnFlag } = action.payload;
      return {
        ...state,
        list,
        total,
        priceBtnFlag
      };
    },

    updateCell(state: object, { payload }: ReduxAction) {
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        list: newList,
      };
    },

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

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

  },
};
