/*
 * @Author: your name
 * @Date: 2022-01-12 10:12:55
 * @LastEditTime: 2024-06-18 09:47:56
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/userManage/model.ts
 */

import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {
  addUsers,
  delUsers,
  editUsers,
  getUsertemplate,
  importUserData,
  resetUserPwd,
} from '@/service/user';
import { TableListItem } from './typings';
import axios from 'axios';

export enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
}

export interface userManageModelState {
  name: string;
  tableAct: TableActType;
  isShowModal: boolean;
  reloadTable: boolean;
  currentEditUser: TableListItem | undefined;
  record: TableListItem | undefined;
}

export interface userManageModelType {
  namespace: 'userManageModel';
  state: userManageModelState;
  effects: {
    query: Effect;
    postAddUserData: Effect;
    postEditUserData: Effect;
    delUsersRequest: Effect;
    getUserTemplateReq: Effect;
    importUsers: Effect;
    resetUserPwd: Effect;
  };
  reducers: {
    save: Reducer<userManageModelState>;
    addUser: Reducer<userManageModelState>;
    cancelTableAct: Reducer<userManageModelState>;
    reloadTable: Reducer<userManageModelState>;
    editUser: Reducer<userManageModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const userManageModel: userManageModelType = {
  namespace: 'userManageModel',

  state: {
    name: '',
    tableAct: TableActType.NOACT,
    isShowModal: false,
    reloadTable: false,
    currentEditUser: undefined,
    record: undefined, //当前操作对象
  },

  effects: {
    *query({ payload }, { call, put }) {},

    *postAddUserData({ payload }, { call, put }) {
      yield addUsers(payload);
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *resetUserPwd({ payload }) {
      yield resetUserPwd({ userId: payload.id });
    },
    // *postEditUserData({ payload }:any, { call, put, select }:any) {
    //   const currentEditUserOld = yield select(
    //     ({ userManageModel: state }: { userManageModel: userManageModelState }) => {
    //       return state.currentEditUser;
    //     },
    //   );

    //   yield editUsers({ ...currentEditUserOld, ...payload });
    //   yield put({
    //     type: 'reloadTable',
    //     payload: true,
    //   });
    // },
    *postEditUserData(
      { payload }: any,
      { call, put, select }: any
    ): Generator<any, void, any> {
      const currentEditUserOld = yield select(
        ({ userManageModel: state }: { userManageModel: userManageModelState }) => {
          return state.currentEditUser;
        },
      );
    
      yield call(editUsers, { ...currentEditUserOld, ...payload });
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *delUsersRequest({ payload }, { put }) {
      yield delUsers(payload);
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *getUserTemplateReq() {
      let path = '/gateway/centerSys/user/exportUserTemplate';

      const userData = localStorage.getItem('userData');
      const { token = '' } = JSON.parse(userData as string);
      
      axios({
          method: 'get',
          url: path,
          responseType: 'blob',
          headers: { token },
      })
          .then(function (response) {
              //console.log({ 'chunk': response });
              const filename = decodeURI(response.headers["content-disposition"]);
              const objectUrl = URL.createObjectURL(
                  new Blob([response.data], {
                      type: 'application/vnd.ms-excel',
                  })
              )
              const link = document.createElement('a')
              // 设置导出的文件名称
              link.download = `${filename}` + '.xls'
              link.style.display = 'none'
              link.href = objectUrl
              link.click()
              document.body.appendChild(link)
    
          });
    },
    *importUsers({ payload }, { call, put, select }) {
      // const formData: any = new FormData();
      // formData.append('file', payload);
      yield importUserData(payload);
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
  },
  reducers: {
    reloadTable(state, action) {
      return {
        ...state,
        reloadTable: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    addUser(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    cancelTableAct(state) {
      return {
        ...state,
        isShowModal: false,
      };
    },
    editUser(state, action) {
      return {
        ...state,
        tableAct: action.payload.act,
        isShowModal: action.payload.isShowModal,
        currentEditUser: action.payload.userData,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default userManageModel;
