/*
 * @Author: your name
 * @Date: 2022-01-12 10:12:55
 * @LastEditTime: 2023-08-18 21:37:40
 * @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 {
  addHosp,
  delHosp,
  editHosp,
  GetHospYoushuAccountsType,
  hospBindMenu,
  hospBindYoushuAccount,
  YoushuAccountsType,
  YoushuUserSaveDTOs,
} from '@/service/hospList';
import type { getUsersParams } from '@/service/user';
import { HospTableItem as TableListItem } from '@/service/hospList';
// import { TableActType } from '.';

enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
  EDITMENU,
  BINDACCOUNT, //绑定有数账号
}

type CurrentSelectedData = TableListItem & GetHospYoushuAccountsType&{[key:string]:any};
export interface hospManageModelState {
  name: string;
  tableAct: TableActType;
  isShowModal: boolean;
  reloadTable: boolean;
  currentEdit: CurrentSelectedData | undefined;
}

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

const hospManageModel: hospManageModelType = {
  namespace: 'hospManageModel',
  state: {
    name: '',
    tableAct: TableActType.NOACT,
    isShowModal: false,
    reloadTable: false,
    currentEdit: undefined,
  },

  effects: {
    *query({ payload }, { call, put }) {},
    *postAddData({ payload }, { call, put }) {
      yield addHosp({ mainHospId: 0, ...payload });
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    *postEditData({ payload }, { call, put, select }) {
      // console.log({payload});
      const {
        tableAct,
        currentEdit: currentEditOld,
      }: { tableAct: TableActType; currentEdit: TableListItem } = yield select(
        ({ hospManageModel: state }: { hospManageModel: hospManageModelState }) => {
          return {
            tableAct: state.tableAct,
            currentEdit: state.currentEdit,
          };
        },
      );

      if (tableAct == TableActType.BINDACCOUNT) {
        const defaultAccount = payload.dataSource.filter((t: YoushuAccountsType) => t.isDefault);
        //  return;
        yield hospBindYoushuAccount({
          hospId: currentEditOld.id,
          reportId: payload.reportId,
          reportUrl: payload.reportUrl,
          userId: defaultAccount.length > 0 ? defaultAccount[0].id : 0,
          youshuUserSaveDTOs: payload.dataSource.map((t: YoushuUserSaveDTOs) => ({
            account: t.account,
            password: t.password,
          })),
        });
        yield put({
          type: 'reloadTable',
          payload: true,
        });
      }

      if (tableAct == TableActType.EDITMENU) {
        //绑定菜单
        yield hospBindMenu({
          hospId: currentEditOld.id,
          menuIds: payload.bindMenuIds,
        }); //menuId集合
        yield put({
          type: 'reloadTable',
          payload: true,
        });
      }

      if (tableAct == TableActType.EDIT) {
        //编辑院区信息
        yield editHosp({ ...currentEditOld, ...payload });

        yield put({
          type: 'reloadTable',
          payload: true,
        });
      }
    },
    *delRequest({ payload }, { put }) {
      yield delHosp(payload);
      yield put({
        type: 'reloadTable',
        payload: true,
      });
    },
    
  },
  reducers: {
    reloadTable(state, action) {
      return {
        ...state,
        reloadTable: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    add(state, action) {
      return {
        ...state,
        ...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 hospManageModel;
