import * as reportService from "../../services/reports/comm";
import { routerRedux } from 'dva/router';
import { stringUtils } from '../../utils';

export default {
  namespace: "priceAnalyse",

  state: {
    list: [],
    total: 0,
    filterParams: {},
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === "/report/priceanalyse") {
        }
      });
    },
  },

  effects: {
    *query({ payload }, { call, select, put }) {
      // 品类拆分
      if (payload && payload.cccCode && typeof payload.cccCode !== 'string') {
        if (payload.cccCode.length > 0) {
          payload.cccCode.map((code, index) => {
            const key = 'c' + (index + 1) + 'Code';
            payload[key] = code;
          });
        } else {
          Object.keys(payload).map((key) => {
            if (key.indexOf('Code') === 2) {
              payload[key] = '';
            }
          });
        }
      }

      // 年月格式化
      const { priceMonth } = payload;
      payload.priceMonth = priceMonth ? priceMonth.format("YYYYMM") : '';

      const data = yield call(reportService.priceAnalyse, payload);
      if (data.success) {
        yield put({
          type: "querySuccess",
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: payload,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));
      } else {
        throw data;
      }
    },

    *clean({ payload }, { call, put }) {
      yield put({
        type: "updateState",
        payload: {
          list: [],
          total: 0,
          filterParams: {},
        },
      });
    },
  },

  reducers: {
    querySuccess(state, action) {
      const { list, total, filterParams } = action.payload;
      return {
        ...state,
        list,
        total,
        filterParams,
      };
    },

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