import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Merchant, MerchantQueryParams, MerchantStatus, MerchantAuditStatus } from '../../types/merchant'

interface MerchantState {
  merchants: Merchant[]
  currentMerchant: Merchant | null
  loading: boolean
  totalCount: number
  queryParams: MerchantQueryParams
}

export const useMerchantStore = defineStore('merchant', () => {
  // 状态
  const merchants = ref<Merchant[]>([])
  const currentMerchant = ref<Merchant | null>(null)
  const loading = ref(false)
  const totalCount = ref(0)
  const queryParams = ref<MerchantQueryParams>({
    page: 1,
    pageSize: 10,
    keyword: '',
    status: undefined,
    auditStatus: undefined,
    startDate: '',
    endDate: ''
  })

  // 获取商家列表
  const fetchMerchants = async (params?: MerchantQueryParams) => {
    loading.value = true
    try {
      // 模拟数据
      const mockMerchants: Merchant[] = [
        {
          id: 1,
          userId: 101,
          shopName: '鲜花坊',
          businessLicense: '1234567890',
          contactPerson: '张老板',
          contactPhone: '13800138001',
          contactEmail: 'flower@jiebanke.com',
          address: '北京市朝阳区',
          description: '专业鲜花销售',
          status: 'active',
          auditStatus: 'approved',
          auditTime: '2024-01-10 14:30:00',
          registerTime: '2024-01-05 09:00:00',
          category: 'flower',
          serviceScore: 4.8,
          orderCount: 156,
          totalRevenue: 12800.50
        },
        {
          id: 2,
          userId: 102,
          shopName: '快乐农场',
          businessLicense: '0987654321',
          contactPerson: '李农场主',
          contactPhone: '13900139001',
          contactEmail: 'farm@jiebanke.com',
          address: '上海市浦东新区',
          description: '动物认领和农场体验',
          status: 'active',
          auditStatus: 'approved',
          auditTime: '2024-01-12 16:20:00',
          registerTime: '2024-01-08 10:30:00',
          category: 'farm',
          serviceScore: 4.9,
          orderCount: 89,
          totalRevenue: 8900.00
        }
      ]
      
      // 应用搜索过滤
      let filteredMerchants = mockMerchants
      if (queryParams.value.keyword) {
        filteredMerchants = mockMerchants.filter((m: Merchant) => {
          return m.shopName.toLowerCase().includes(queryParams.value.keyword.toLowerCase()) ||
                 m.contactPerson.toLowerCase().includes(queryParams.value.keyword.toLowerCase())
        })
      }
      
      merchants.value = filteredMerchants
      totalCount.value = filteredMerchants.length
      
      if (params) {
        queryParams.value = { ...queryParams.value, ...params }
      }
    } catch (error) {
      console.error('获取商家列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取商家详情
  const fetchMerchantDetail = async (merchantId: number) => {
    loading.value = true
    try {
      // 模拟数据
      const mockMerchant: Merchant = {
        id: merchantId,
        userId: 100 + merchantId,
        shopName: `商家${merchantId}`,
        businessLicense: `LICENSE${merchantId}`,
        contactPerson: '联系人',
        contactPhone: '13800138000',
        contactEmail: `merchant${merchantId}@jiebanke.com`,
        address: '地址',
        description: '商家描述',
        status: 'active',
        auditStatus: 'approved',
        auditTime: '2024-01-15 10:00:00',
        registerTime: '2024-01-01 09:00:00',
        category: 'flower',
        serviceScore: 4.5,
        orderCount: 100,
        totalRevenue: 10000.00
      }
      
      currentMerchant.value = mockMerchant
      return mockMerchant
    } catch (error) {
      console.error('获取商家详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 审核商家
  const auditMerchant = async (merchantId: number, auditStatus: MerchantAuditStatus, auditRemark?: string) => {
    try {
      // 模拟审核操作
      const merchant = merchants.value.find(m => m.id === merchantId)
      if (merchant) {
        merchant.auditStatus = auditStatus
        merchant.auditTime = new Date().toISOString()
      }
      
      if (currentMerchant.value && currentMerchant.value.id === merchantId) {
        currentMerchant.value.auditStatus = auditStatus
        currentMerchant.value.auditTime = new Date().toISOString()
      }
      
      return true
    } catch (error) {
      console.error('审核商家失败:', error)
      throw error
    }
  }

  // 更新商家状态
  const updateMerchantStatus = async (merchantId: number, status: MerchantStatus) => {
    try {
      // 模拟状态更新
      const merchant = merchants.value.find(m => m.id === merchantId)
      if (merchant) {
        merchant.status = status
      }
      
      if (currentMerchant.value && currentMerchant.value.id === merchantId) {
        currentMerchant.value.status = status
      }
      
      return true
    } catch (error) {
      console.error('更新商家状态失败:', error)
      throw error
    }
  }

  // 搜索商家
  const searchMerchants = async (keyword: string) => {
    queryParams.value.keyword = keyword
    return fetchMerchants(queryParams.value)
  }

  // 重置查询参数
  const resetQueryParams = () => {
    queryParams.value = {
      page: 1,
      pageSize: 10,
      keyword: '',
      status: undefined,
      auditStatus: undefined,
      startDate: '',
      endDate: ''
    }
  }

  // 获取商家统计
  const getMerchantStatistics = async () => {
    try {
      // 模拟统计数据
      return {
        totalMerchants: 156,
        activeMerchants: 142,
        pendingAudit: 8,
        rejected: 6,
        totalRevenue: 256800.50,
        averageScore: 4.7,
        categoryDistribution: {
          flower: 45,
          farm: 32,
          activity: 23,
          other: 56
        }
      }
    } catch (error) {
      console.error('获取商家统计失败:', error)
      throw error
    }
  }

  return {
    merchants,
    currentMerchant,
    loading,
    totalCount,
    queryParams,
    fetchMerchants,
    fetchMerchantDetail,
    auditMerchant,
    updateMerchantStatus,
    searchMerchants,
    resetQueryParams,
    getMerchantStatistics
  }
})