// 移除Taro依赖，使用Web API
import { Dispatch } from 'redux'
import { HistoryRecord } from '../store/types'
import * as types from '../constants/history'

const STORAGE_KEY = 'historyRecords'

// Action creators
export const loadRecordsRequest = () => ({
  type: types.LOAD_RECORDS_REQUEST
})

export const loadRecordsSuccess = (records: HistoryRecord[]) => ({
  type: types.LOAD_RECORDS_SUCCESS,
  payload: records
})

export const loadRecordsFailure = (error: string) => ({
  type: types.LOAD_RECORDS_FAILURE,
  payload: error
})

export const addRecordRequest = () => ({
  type: types.ADD_RECORD_REQUEST
})

export const addRecordSuccess = (record: HistoryRecord) => ({
  type: types.ADD_RECORD_SUCCESS,
  payload: record
})

export const addRecordFailure = (error: string) => ({
  type: types.ADD_RECORD_FAILURE,
  payload: error
})

export const updateRecordRequest = () => ({
  type: types.UPDATE_RECORD_REQUEST
})

export const updateRecordSuccess = (record: HistoryRecord) => ({
  type: types.UPDATE_RECORD_SUCCESS,
  payload: record
})

export const updateRecordFailure = (error: string) => ({
  type: types.UPDATE_RECORD_FAILURE,
  payload: error
})

export const deleteRecordRequest = () => ({
  type: types.DELETE_RECORD_REQUEST
})

export const deleteRecordSuccess = (id: string) => ({
  type: types.DELETE_RECORD_SUCCESS,
  payload: id
})

export const deleteRecordFailure = (error: string) => ({
  type: types.DELETE_RECORD_FAILURE,
  payload: error
})

export const clearRecordsRequest = () => ({
  type: types.CLEAR_RECORDS_REQUEST
})

export const clearRecordsSuccess = () => ({
  type: types.CLEAR_RECORDS_SUCCESS
})

export const clearRecordsFailure = (error: string) => ({
  type: types.CLEAR_RECORDS_FAILURE,
  payload: error
})

export const clearError = () => ({
  type: types.CLEAR_ERROR
})

// Async actions
export const loadRecords = () => {
  return async (dispatch: Dispatch) => {
    dispatch(loadRecordsRequest())
    try {
      const savedRecords = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
      dispatch(loadRecordsSuccess(savedRecords))
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '加载历史记录失败'
      dispatch(loadRecordsFailure(errorMsg))
      console.error('加载历史记录失败:', error)
    }
  }
}

export const addRecord = (recordData: Omit<HistoryRecord, 'id' | 'createTime' | 'updateTime'>) => {
  return async (dispatch: Dispatch, getState: () => any) => {
    dispatch(addRecordRequest())
    try {
      const id = `record_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      const now = new Date().toISOString()

      const newRecord: HistoryRecord = {
        ...recordData,
        id,
        createTime: now,
        updateTime: now
      }

      const currentRecords = getState().history.records
      const updatedRecords = [newRecord, ...currentRecords]

      localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedRecords))

      dispatch(addRecordSuccess(newRecord))
      return id
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '添加记录失败'
      dispatch(addRecordFailure(errorMsg))
      console.error('添加记录失败:', error)
      throw error
    }
  }
}

export const updateRecord = (id: string, updates: Partial<HistoryRecord>) => {
  return async (dispatch: Dispatch, getState: () => any) => {
    dispatch(updateRecordRequest())
    try {
      const currentRecords = getState().history.records
      const recordIndex = currentRecords.findIndex((record: HistoryRecord) => record.id === id)

      if (recordIndex === -1) {
        throw new Error('记录不存在')
      }

      const updatedRecord = {
        ...currentRecords[recordIndex],
        ...updates,
        updateTime: new Date().toISOString()
      }

      const updatedRecords = [...currentRecords]
      updatedRecords[recordIndex] = updatedRecord

      localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedRecords))

      dispatch(updateRecordSuccess(updatedRecord))
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '更新记录失败'
      dispatch(updateRecordFailure(errorMsg))
      console.error('更新记录失败:', error)
      throw error
    }
  }
}

export const deleteRecord = (id: string) => {
  return async (dispatch: Dispatch, getState: () => any) => {
    dispatch(deleteRecordRequest())
    try {
      const currentRecords = getState().history.records
      const updatedRecords = currentRecords.filter((record: HistoryRecord) => record.id !== id)

      localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedRecords))

      dispatch(deleteRecordSuccess(id))
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '删除记录失败'
      dispatch(deleteRecordFailure(errorMsg))
      console.error('删除记录失败:', error)
      throw error
    }
  }
}

export const clearRecords = () => {
  return async (dispatch: Dispatch) => {
    dispatch(clearRecordsRequest())
    try {
      localStorage.removeItem(STORAGE_KEY)
      dispatch(clearRecordsSuccess())
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '清空记录失败'
      dispatch(clearRecordsFailure(errorMsg))
      console.error('清空记录失败:', error)
      throw error
    }
  }
}
