import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getConsultation_information_list, getConsultation_information_detail, getPrescription_detail, getUserinfo } from '@/api'
import type { PageListParamsType, ConsultationOrderListItemType, PageListType, ConsultationOrderDetailType, PrescriptionDetailType, UserInfoType } from '@/types'
import type { RootState } from '@/store'

// createAsyncThunk<返回值类型, 接受参数类型>  参数为payload
export const fetchOrderDataAction = createAsyncThunk<void, PageListParamsType>(
  'fetchdata', (payload, { dispatch }) => {
    getConsultation_information_list(payload).then(({ result }: { result: PageListType<ConsultationOrderListItemType[]> }) => {
      console.log(result, '问诊订单列表')
      dispatch(changeConsultationOrderAction(result?.records))
      dispatch(changeConsultationOrderNumAction(result?.total))
    })
  }
)

export const fetchConsultationOrderDetailAction = createAsyncThunk<void, { id: string | number }>(
  'ConsultationOrderDetailType', (payload, { dispatch }) => {
    getConsultation_information_detail(payload).then(({ result }: { result: ConsultationOrderDetailType }) => {
      dispatch(changeConsultationOrderDetailAction(result))
    })
  }
)

export const fetchPrescriptionDetailAction = createAsyncThunk<void, { id: string | number }>(
  'PrescriptionDetail', (payload, { dispatch }) => {
    getPrescription_detail(payload).then(({ result }: { result: PrescriptionDetailType }) => {
      dispatch(changePrescriptionDetailAction(result))
    })
  }
)

export const fetchUserinfoAction = createAsyncThunk<void, void>('UserInfo', (payload, { dispatch }) => {
  getUserinfo().then(({ result }: { result: UserInfoType }) => {
    dispatch(changeUserInfoAction(result))
  })
})

const orderSlice = createSlice({
  name: 'order',
  initialState: {
    count: 100,
    message: 'hello Redux',
    name: 'HachimanC',
    ConsultationOrderList: [],
    ConsultationOrderDetailData: {},
    PrescriptionDetailData: {},
    UserInfo: {},
    total: 0
  },
  reducers: {
    changeConsultationOrderAction(state, { payload }) {
      state.ConsultationOrderList = payload
    },
    changeConsultationOrderNumAction(state, { payload }) {
      state.total = payload
    },
    changeConsultationOrderDetailAction(state, { payload }) {
      state.ConsultationOrderDetailData = payload
    },
    changePrescriptionDetailAction(state, { payload }) {
      state.PrescriptionDetailData = payload
    },
    changeUserInfoAction(state, { payload }) {
      state.UserInfo = payload
    }
  }
})

export default orderSlice.reducer

export const { changeConsultationOrderAction, changeConsultationOrderNumAction, changeConsultationOrderDetailAction, changePrescriptionDetailAction, changeUserInfoAction } = orderSlice.actions