import * as pictureService from '../../services/resource/pictureService';
import { message } from 'antd';
import config from '../../config/config';

export default {
  namespace: "pictureModel",
  state: {
    pictureLoading: false,
    total: 0,
    currentPage: 1,
    pageSize: config.PAGE_SIZE,
    searchParams: {},
    pictureList: [],
    operateType: "add",
    selectedRowKeys: [],
    selectedRows: [],
    viewModalVisible: false,
    pictureRecord: {},
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
  },
  effects: {
    *getPictureList({ payload: params }, { select, call, put }) {
      yield put({ type: "updateState", payload: { pictureLoading: true }});
      params.currentPage = params.currentPage ? params.currentPage : 1;
      params.pageSize = params.pageSize ? params.pageSize : config.PAGE_SIZE;
      const res = yield call(pictureService.getFilesList, { ...params });
      if (res.code == 200) {
        yield put({
          type: "updateState",
          payload: { pictureList: res.data.records, total: res.data.total,
            currentPag: params.currentPage, pageSize: params.pageSize }
        });
      }
      yield put({ type: "updateState", payload: { pictureLoading: false }});
    },

    *onDelete({ payload: params }, { select, call, put }) {
      const { searchParams } = yield select(state => state.pictureModel);
      const res = yield call(pictureService.onDelete, params);
      if (res.code == 200) {
        yield put({ type: "getPictureList", payload: { ...params, ...searchParams }});
        yield put({ type: "updateState", payload: { selectedRowKeys: [], selectedRows: [] }});
        message.success("刪除成功！");
      } else {
        message.error("刪除失敗！")
      }
    },

    *onUpload({ payload: params }, { select, call, put }) {
      const { searchParams } = yield select(state => state.pictureModel);
      const res = yield call(pictureService.onUpload, params);
      if (res.data.code == 200) {
        yield put({ type: "getPictureList", payload: { ...params, ...searchParams }});
        message.success("上传成功！");
      } else {
        message.error("上传失败！");
      }
    },

    *onDownload({ payload: params }, { select, call, put }) {
      const res = yield call(pictureService.onDownload, { ...params });
      console.log("onDownload res => ", res);
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === "/resource/picture") {
          dispatch({ type: 'getPictureList', payload: {} });
        }
      });
    },
  },
};
