import pathToRegexp from 'path-to-regexp';
import { routerRedux } from 'dva/router';
import * as R from 'ramda';

import { getSingle } from '../../services/item/itemDetail';
import { getSupps, getWebs, query } from '../../services/item/prices';
import * as suppliers from '../../services/supplier/suppliers';
import { queryHis } from '../../services/item/priceHistory';
import { dataUtils, formUtils } from '../../utils';

export default {

  namespace: 'itemPriceHistory',

  state: {
    itemInfo: {},
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    chartData: [],
    webs: [],
    from: '',
    formData: {},
    filterParams: {},
    isSupplier: false,
    selectedWeb: 0,
    selectedSupp: 0,
    supps: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/price-mgmt/prices/:id').exec(location.pathname);
        if (match) {
          dispatch({ type: 'clean' });
          if (match[1] === 'create') {
            return 0;
          }
          dispatch({ type: 'queryItem', payload: match[1] });
          dispatch({ type: 'querySupps', payload: { id: match[1] } });
          dispatch({ type: 'query', payload: { id: match[1] } });
          dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
        }
      });
    },
  },

  effects: {
    * queryItem({ payload }, { call, select, put }) {
      const item = yield call(getSingle, payload); // 查询物料信息

      if (item.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            itemInfo: item.data,
          },
        });
      } else {
        throw item;
      }
    },

    * queryWebs({ payload }, { call, select, put }) {
      const webs = yield call(getWebs); // 查询物料外部参考网站
      if (webs.success) {
        yield put({
          type: 'updateState',
          payload: {
            webs: webs.data,
          },
        });
      } else {
        throw webs;
      }
    },

    * querySupps({ payload }, { call, select, put }) {
      const supps = yield call(getSupps, { itemId: payload.id }); // 查询供应商列表
      if (supps.success) {
        yield put({
          type: 'updateState',
          payload: {
            supps: supps.data,
          },
        });
      } else {
        throw supps;
      }
    },

    * query({ payload }, { call, select, put }) {
      const { filterParams } = yield select(({ itemPriceHistory }) => itemPriceHistory);
      filterParams.itemId = payload.id || filterParams.itemId;
      payload.itemId = payload.id || filterParams.itemId;

      const newPayload = formUtils.standardiseFormData(payload);
      if (newPayload['yearMonthDateFrom']) {
        newPayload['yearMonthDateFrom'] = newPayload['yearMonthDateFrom'].substring(0, 7);
        newPayload['yearMonthDateTo'] = newPayload['yearMonthDateTo'].substring(0, 7);
      }

      const { user } = yield select(({ app }) => app.user);
      const isSupplier = R.cond([
        [R.equals('oper'), () => false],
        [R.equals('supp'), () => true],
        [R.T, () => true]
      ])(user.entType);

      if (payload.suppCode || isSupplier) {
        const supps = yield call(suppliers.query, { suppCodeName: isSupplier ? user.name : payload.suppCode }); // 获取供应商信息
        const supplier = supps.data.rows[0];
        const supplierData = {};
        supplierData['id'] = supplier.id;
        supplierData['code'] = supplier.suppCode;
        supplierData['name'] = supplier.suppName;
        filterParams['supplier'] = supplierData;
        newPayload['suppId'] = supplier.id;
      }

      const data = yield call(query, newPayload); // 查询物料价格信息

      if (data.success) {
        yield put({
          type: 'queryInfoSuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: { ...filterParams, newPayload },
            isSupplier,
          },
        });
      } else {
        throw data;
      }
    },

    * queryHistory({ payload }, { call, select, put }) {
      const { itemInfo } = yield select(({ itemPriceHistory }) => itemPriceHistory);
      payload.itemId = itemInfo.id;

      if (payload.yearMonthDate && payload.yearMonthDate.length > 0) {
        if (typeof payload.yearMonthDate[0] === 'string') {
          payload.yearMonthDateFrom = payload.yearMonthDate[0];
          payload.yearMonthDateTo = payload.yearMonthDate[1];
        } else {
          payload.yearMonthDateFrom = payload.yearMonthDate[0].format('YYYY-MM');
          payload.yearMonthDateTo = payload.yearMonthDate[1].format('YYYY-MM');
        }
        payload.yearMonthDate = null;
      }
      payload.suppCenter = [payload.suppCenter];

      const data = yield call(queryHis, payload);
      // const data = yield call(queryHis, newPayload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            chartData: data.data,
            selectedWeb: payload.webSiteCode,
            selectedSupp: payload.suppIds,
          },
        });
      } else {
        throw data;
      }
    },

    * view({ payload }, { put }) {
      yield put({ type: 'hideModal' });
    },

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

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          itemInfo: {},
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          chartData: [],
          webs: [],
          from: '',
          formData: {},
          filterParams: {},
          isSupplier: false,
          selectedWeb: 0,
          selectedSupp: 0,
          supps: [],
        },
      });
    },

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

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

  reducers: {

    querySuccess(state, action) {
      const { itemInfo } = action.payload;
      return {
        ...state,
        itemInfo,
      };
    },

    queryInfoSuccess(state, action) {
      const { list, total, filterParams, isSupplier } = action.payload;
      return {
        ...state,
        list,
        total,
        filterParams,
        isSupplier,
      };
    },

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

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