import { listConvert } from '@/api/system/convert.js'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义计量单位接口
export interface UnitItem {
  id: number
  unitType: string
  unitName: string
  conversionFactor: number
  unitOrder: number
  baseUnit: string
  status: string
  unitTypeName: string
}

export interface UnitQueryParams {
  pageNum: number
  pageSize: number
  unitType: string | null
  unitName: string | null
  baseUnit: string | null
  conversionFactor: number | null
  unitTypeName: string | null
  status: string | null
  unitOrder: number | null
}

// 定义按类型分组的单位数据结构
export interface GroupedUnitData {
  [unitType: string]: UnitItem[]
}

export const useUnitStore = defineStore('unit', {
  state: () => ({
    // 单位数据列表
    unitData: [] as UnitItem[],
    // 按类型分组后的单位数据
    groupedUnitData: {} as GroupedUnitData,
    // 查询参数
    queryParams: {
      pageNum: 1,
      pageSize: 1000,
      unitType: null,
      unitName: null,
      baseUnit: null,
      conversionFactor: null,
      unitTypeName: null,
      status: null,
      unitOrder: null
    } as UnitQueryParams,
    // 加载状态
    loading: false,
    // 总条数
    total: 0
  }),

  getters: {
    // 获取所有单位类型
    unitTypes: (state) => {
      return Object.keys(state.groupedUnitData)
    },

    // 获取特定类型的单位列表
    getUnitsByType: (state) => {
      return (unitType: string) => {
        return state.groupedUnitData[unitType] || []
      }
    },

    // 获取基本单位
    getBaseUnit: (state) => {
      return (unitType: string) => {
        const units = state.groupedUnitData[unitType] || []
        return units.find(unit => unit.baseUnit === '1') || units[0]
      }
    },

    // 按类型排序的单位数据
    sortedUnitTypes: (state) => {
      return Object.keys(state.groupedUnitData).sort()
    }
  },

  actions: {
    // 按单位类型分组
    groupByUnitType(data: UnitItem[]): GroupedUnitData {
      return data.reduce((acc: GroupedUnitData, unit: UnitItem) => {
        const type = unit.unitType
        if (!acc[type]) {
          acc[type] = []
        }
        acc[type].push({
          id: unit.id,
          unitType: unit.unitType,
          unitName: unit.unitName,
          conversionFactor: unit.conversionFactor,
          unitOrder: unit.unitOrder,
          baseUnit: unit.baseUnit,
          status: unit.status,
          unitTypeName: unit.unitTypeName
        })
        // 按单位排序
        acc[type].sort((a, b) => (a.unitOrder || 0) - (b.unitOrder || 0))
        return acc
      }, {})
    },

    // 设置查询参数
    setQueryParams(params: Partial<UnitQueryParams>) {
      this.queryParams = { ...this.queryParams, ...params }
    },

    // 重置查询参数
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 1000,
        unitType: null,
        unitName: null,
        baseUnit: null,
        conversionFactor: null,
        unitTypeName: null,
        status: null,
        unitOrder: null
      }
    },

    // 获取单位列表
    async getList() {
      this.loading = true
      try {
        const response = await listConvert(this.queryParams)
        this.unitData = response.rows || []
        this.total = response.total || 0
        this.groupedUnitData = this.groupByUnitType(this.unitData)        
        // 保存到localStorage
        localStorage.setItem('unitData', JSON.stringify(this.groupedUnitData))
        
        return response
      } catch (error) {
        console.error('获取单位数据失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 从localStorage加载缓存的单位数据
    loadFromLocalStorage() {
      try {
        const storedData = localStorage.getItem('unitData')
        if (storedData) {
          this.groupedUnitData = JSON.parse(storedData)
          // 从分组数据中提取所有单位
          this.unitData = Object.values(this.groupedUnitData).flat()
          return true
        }
      } catch (error) {
        console.error('从localStorage加载单位数据失败:', error)
      }
      return false
    },

    // 清除localStorage中的单位数据
    clearLocalStorage() {
      localStorage.removeItem('unitData')
    },

    // 单位转换方法
    convertUnit(value: number, fromUnit: UnitItem, toUnit: UnitItem): number {
      if (fromUnit.unitType !== toUnit.unitType) {
        throw new Error('单位类型不匹配，无法转换')
      }
      
      // 先转换到基本单位，再从基本单位转换到目标单位
      const valueInBaseUnit = value * (fromUnit.conversionFactor || 1)
      return valueInBaseUnit / (toUnit.conversionFactor || 1)
    },

    // 根据单位名称查找单位
    findUnitByName(unitName: string): UnitItem | undefined {
      return this.unitData.find(unit => unit.unitName === unitName)
    },

    // 根据ID查找单位
    findUnitById(id: number): UnitItem | undefined {
      return this.unitData.find(unit => unit.id === id)
    },

    // 刷新单位数据
    async refresh() {
      await this.getList()
    },

    // 获取有效的单位列表（状态为正常的）
    getActiveUnits(unitType?: string): UnitItem[] {
      const units = unitType 
        ? (this.groupedUnitData[unitType] || [])
        : this.unitData
      
      return units.filter(unit => unit.status === '0') // 假设 '0' 表示正常状态
    },

    // 根据类型和名称模糊查询单位
    searchUnits(type: string, keyword: string): UnitItem[] {
      const units = this.groupedUnitData[type] || []
      return units.filter(unit => 
        unit.unitName.includes(keyword) || 
        (unit.unitTypeName && unit.unitTypeName.includes(keyword))
      )
    }
  }
})

export default useUnitStore