/*
 * @Author: your name
 * @Date: 2022-01-12 10:12:55
 * @LastEditTime: 2023-09-18 17:59:16
 * @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 {
  addRoles,
  delRoles,
  editRoles,
  roleBindMenus,
  roleBindUsers,
} from '@/service/role';
import { getMainHosp } from '@/service/hospList';
import type { RoleItemType as TableListItem } from '@/service/role';
import { getDictByDictTypeAndSysid } from '@/service/dictionary';
import { KcimCenterSysId } from '@/constant';

enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
  EDITMENU, //编辑菜单绑定
  EDITRELAUSER, //编辑人员绑定
}

export interface roleManageModelState {
  name: string;
  tableAct: TableActType;
  isShowModal: boolean;
  reloadTable: boolean;
  currentEdit: TableListItem | undefined;
  hospId: number | undefined;
}

export interface roleManageModelType {
  namespace: 'roleManageModel';
  state: roleManageModelState;
  effects: {
    query: Effect;
    postAddData: Effect;
    postEditData: Effect;
    delRequest: Effect;
    getMainHospHandle: Effect;
    addEffect: Effect;
  };
  reducers: {
    save: Reducer<roleManageModelState>;
    add: Reducer<roleManageModelState>;
    cancelTableAct: Reducer<roleManageModelState>;
    reloadTable: Reducer<roleManageModelState>;
    edit: Reducer<roleManageModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const roleManageModel: roleManageModelType = {
  namespace: 'roleManageModel',
  state: {
    name: '',
    tableAct: TableActType.NOACT,
    isShowModal: false,
    reloadTable: false,
    currentEdit: undefined,
    hospId: undefined,
  },

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

    *postAddData({ payload }, { call, put }) {
      yield addRoles({ ...payload });
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *postEditData({ payload }, { call, put, select }) {
      const {
        tableAct,
        currentEdit: currentEditOld,
      }: { tableAct: TableActType; currentEdit: TableListItem } = yield select(
        ({
          roleManageModel: state,
        }: {
          roleManageModel: roleManageModelState;
        }) => {
          return {
            tableAct: state.tableAct,
            currentEdit: state.currentEdit,
          };
        },
      );

      if (tableAct == TableActType.EDITMENU) {
        //角色绑定菜单
        yield roleBindMenus({
          hospId: Number(currentEditOld.hospId),
          menuIds: payload.bindMenuIds,
          roleId: Number(currentEditOld.roleId),
        }); //menuId集合
        yield put({
          type: 'reloadTable',
          payload: true,
        });
      } else if (tableAct == TableActType.EDITRELAUSER) {
        //绑定角色和人员
        yield roleBindUsers({
          hospId: Number(currentEditOld.hospId),
          userIds: payload.bindUserIds,
          roleId: Number(currentEditOld.roleId),
        }); //menuId集合
        
        yield put({
          type: 'reloadTable',
          payload: true,
        });
      } else {
        //编辑角色信息
        yield editRoles({ ...currentEditOld, ...payload });

        yield put({
          type: 'reloadTable',
          payload: true,
        });
      }
    },
    *delRequest({ payload }, { put }) {
      yield delRoles(payload);
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *getMainHospHandle() {
      const { id } = yield getMainHosp();
      return id;
    },
    *addEffect({ payload }, { put }) {
      // const { id } = yield getMainHosp();
      const currentHosp = localStorage.getItem('currentSelectedSubHop');
      if(currentHosp){
           const {id} = JSON.parse(currentHosp);
           yield put({
            type: 'add',
            payload: { hospId: id },
          });
      }
    },
  },
  reducers: {
    reloadTable(state, action) {
      return {
        ...state,
        reloadTable: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    add(state, action) {
      return {
        ...state,
        tableAct: TableActType.ADD,
        isShowModal: true,
        ...action.payload,
      };
    },
    cancelTableAct(state) {
      return {
        ...state,
        isShowModal: false,
      };
    },
    edit(state, action) {
      return {
        ...state,
        tableAct: action.payload.act,
        isShowModal: action.payload.isShowModal,
        currentEdit: action.payload.data,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default roleManageModel;
