// store/insurance.js - 保险业务状态管理
import { defineStore } from 'pinia'
import { insuranceAPI, policyAPI, claimAPI } from '@/utils/api'
import { APPLICATION_STATUS, POLICY_STATUS, CLAIM_STATUS } from '@/utils/constants'

export const useInsuranceStore = defineStore('insurance', {
  state: () => ({
    // 保险产品
    insuranceTypes: [],
    hotProducts: [],
    currentProduct: null,
    productsLoading: false,
    
    // 保险申请
    applications: [],
    currentApplication: null,
    applicationsLoading: false,
    applicationStats: {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0
    },
    
    // 保单
    policies: [],
    currentPolicy: null,
    policiesLoading: false,
    
    // 理赔
    claims: [],
    currentClaim: null,
    claimsLoading: false,
    
    // 分页信息
    pagination: {
      products: { page: 1, limit: 10, total: 0 },
      applications: { page: 1, limit: 10, total: 0 },
      policies: { page: 1, limit: 10, total: 0 },
      claims: { page: 1, limit: 10, total: 0 }
    }
  }),
  
  getters: {
    // 获取热门产品
    getHotProducts: (state) => state.hotProducts.slice(0, 6),
    
    // 根据状态获取申请
    getApplicationsByStatus: (state) => (status) => {
      return state.applications.filter(app => app.status === status)
    },
    
    // 根据状态获取保单
    getPoliciesByStatus: (state) => (status) => {
      return state.policies.filter(policy => policy.status === status)
    },
    
    // 根据状态获取理赔
    getClaimsByStatus: (state) => (status) => {
      return state.claims.filter(claim => claim.status === status)
    },
    
    // 有效保单数量
    activePoliciesCount: (state) => {
      return state.policies.filter(policy => policy.status === POLICY_STATUS.ACTIVE).length
    },
    
    // 待处理理赔数量
    pendingClaimsCount: (state) => {
      return state.claims.filter(claim => claim.status === CLAIM_STATUS.PENDING).length
    }
  },
  
  actions: {
    // 获取保险产品列表（动态调用保险端后端）
    async fetchInsuranceTypes(params = {}) {
      try {
        this.productsLoading = true
        
        // 动态调用 /api/insurance-types
        const res = await insuranceAPI.getTypes({
          page: this.pagination.products.page,
          limit: this.pagination.products.limit,
          ...params
        })
        
        if (params.page === 1) {
          this.insuranceTypes = res.data
        } else {
          this.insuranceTypes.push(...res.data)
        }
        
        // 更新分页信息
        if (res.pagination) {
          this.pagination.products = {
            ...this.pagination.products,
            ...res.pagination
          }
        }
        
        return res.data
      } catch (error) {
        console.error('获取保险产品失败:', error)
        throw error
      } finally {
        this.productsLoading = false
      }
    },
    
    // 获取热门产品（动态调用）
    async fetchHotProducts() {
      try {
        // 动态调用保险端接口获取热门产品
        const res = await insuranceAPI.getTypes({
          is_hot: true,
          status: 'active',
          limit: 8
        })
        
        this.hotProducts = res.data || []
        return this.hotProducts
      } catch (error) {
        console.error('获取热门产品失败:', error)
        throw error
      }
    },
    
    // 获取产品详情（动态调用）
    async fetchProductDetail(id) {
      try {
        // 动态调用 /api/insurance-types/:id
        const res = await insuranceAPI.getTypeDetail(id)
        this.currentProduct = res.data
        return res.data
      } catch (error) {
        console.error('获取产品详情失败:', error)
        throw error
      }
    },
    
    // 提交保险申请（动态调用保险端后端）
    async submitApplication(applicationData) {
      try {
        // 动态调用 /api/insurance/applications
        const res = await insuranceAPI.submitApplication(applicationData)
        
        // 添加到本地状态（如果需要）
        if (res.data) {
          this.applications.unshift(res.data)
          this.applicationStats.total += 1
          this.applicationStats.pending += 1
        }
        
        return res.data
      } catch (error) {
        console.error('提交保险申请失败:', error)
        throw error
      }
    },
    
    // 获取我的申请列表（动态调用）
    async fetchMyApplications(params = {}) {
      try {
        this.applicationsLoading = true
        
        // 动态调用后端扩展接口
        const res = await insuranceAPI.getMyApplications({
          page: this.pagination.applications.page,
          limit: this.pagination.applications.limit,
          ...params
        })
        
        if (params.page === 1) {
          this.applications = res.data
        } else {
          this.applications.push(...res.data)
        }
        
        // 更新分页信息
        if (res.pagination) {
          this.pagination.applications = {
            ...this.pagination.applications,
            ...res.pagination
          }
        }
        
        return res.data
      } catch (error) {
        console.error('获取我的申请失败:', error)
        throw error
      } finally {
        this.applicationsLoading = false
      }
    },
    
    // 获取申请详情（动态调用）
    async fetchApplicationDetail(id) {
      try {
        // 动态调用 /api/insurance/applications/:id
        const res = await insuranceAPI.getApplicationDetail(id)
        this.currentApplication = res.data
        return res.data
      } catch (error) {
        console.error('获取申请详情失败:', error)
        throw error
      }
    },
    
    // 获取我的保单列表（动态调用）
    async fetchMyPolicies(params = {}) {
      try {
        this.policiesLoading = true
        
        // 动态调用后端扩展接口
        const res = await policyAPI.getMyPolicies({
          page: this.pagination.policies.page,
          limit: this.pagination.policies.limit,
          ...params
        })
        
        if (params.page === 1) {
          this.policies = res.data
        } else {
          this.policies.push(...res.data)
        }
        
        // 更新分页信息
        if (res.pagination) {
          this.pagination.policies = {
            ...this.pagination.policies,
            ...res.pagination
          }
        }
        
        return res.data
      } catch (error) {
        console.error('获取我的保单失败:', error)
        throw error
      } finally {
        this.policiesLoading = false
      }
    },
    
    // 获取保单详情（动态调用）
    async fetchPolicyDetail(id) {
      try {
        // 动态调用 /api/policies/:id
        const res = await policyAPI.getPolicyDetail(id)
        this.currentPolicy = res.data
        return res.data
      } catch (error) {
        console.error('获取保单详情失败:', error)
        throw error
      }
    },
    
    // 提交理赔申请（动态调用）
    async submitClaim(claimData) {
      try {
        // 动态调用 /api/claims
        const res = await claimAPI.submitClaim(claimData)
        
        // 添加到本地状态
        if (res.data) {
          this.claims.unshift(res.data)
        }
        
        return res.data
      } catch (error) {
        console.error('提交理赔申请失败:', error)
        throw error
      }
    },
    
    // 获取我的理赔列表（动态调用）
    async fetchMyClaims(params = {}) {
      try {
        this.claimsLoading = true
        
        // 动态调用后端扩展接口
        const res = await claimAPI.getMyClaims({
          page: this.pagination.claims.page,
          limit: this.pagination.claims.limit,
          ...params
        })
        
        if (params.page === 1) {
          this.claims = res.data
        } else {
          this.claims.push(...res.data)
        }
        
        // 更新分页信息
        if (res.pagination) {
          this.pagination.claims = {
            ...this.pagination.claims,
            ...res.pagination
          }
        }
        
        return res.data
      } catch (error) {
        console.error('获取我的理赔失败:', error)
        throw error
      } finally {
        this.claimsLoading = false
      }
    },
    
    // 获取理赔详情（动态调用）
    async fetchClaimDetail(id) {
      try {
        // 动态调用 /api/claims/:id
        const res = await claimAPI.getClaimDetail(id)
        this.currentClaim = res.data
        return res.data
      } catch (error) {
        console.error('获取理赔详情失败:', error)
        throw error
      }
    },
    
    // 上传理赔材料（动态调用）
    async uploadClaimDocument(filePath, claimId) {
      try {
        // 动态调用上传接口
        const res = await claimAPI.uploadClaimDocument(filePath, claimId)
        return res.data
      } catch (error) {
        console.error('上传理赔材料失败:', error)
        throw error
      }
    },
    
    // 获取申请统计（动态调用）
    async fetchApplicationStats() {
      try {
        const res = await insuranceAPI.getApplicationStats()
        this.applicationStats = {
          ...this.applicationStats,
          ...res.data
        }
        return res.data
      } catch (error) {
        console.error('获取申请统计失败:', error)
        throw error
      }
    },
    
    // 重置分页
    resetPagination(type) {
      if (this.pagination[type]) {
        this.pagination[type].page = 1
      }
    },
    
    // 清理数据
    clearData() {
      this.insuranceTypes = []
      this.hotProducts = []
      this.currentProduct = null
      this.applications = []
      this.currentApplication = null
      this.policies = []
      this.currentPolicy = null
      this.claims = []
      this.currentClaim = null
      
      // 重置分页
      Object.keys(this.pagination).forEach(key => {
        this.pagination[key].page = 1
      })
    }
  }
})