/**
 * 账单管理状态模块
 *
 * 提供账单列表/详情/统计、筛选条件、批量选择等状态管理能力。
 *
 * @module store/modules/billingStore
 */
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
  batchUpdateStatus as apiBatchUpdateStatus,
  cancelBilling as apiCancelBilling,
  createBilling as apiCreateBilling,
  fetchBillingDetail as apiFetchBillingDetail,
  fetchBillingList as apiFetchBillingList,
  fetchBillingPayments as apiFetchBillingPayments,
  fetchBillingStatistics as apiFetchBillingStatistics,
  fetchOverdueBillings as apiFetchOverdueBillings,
  exportBillings as apiExportBillings,
  recordPayment as apiRecordPayment,
  updateBillingStatus as apiUpdateBillingStatus,
  verifyPayment as apiVerifyPayment
} from '@/api/billing'
import { TenantBillingStatus } from '@/enums/Billing'

interface BillingPagination {
  page: number
  pageSize: number
  totalCount: number
  totalPages: number
}

/**
 * 账单管理 Store
 */
export const useBillingStore = defineStore('billingStore', () => {
  // ==================== State ====================

  /** 账单列表 */
  const billings = ref<Api.Billing.BillingListDto[]>([])

  /** 当前账单详情 */
  const currentBilling = ref<Api.Billing.BillingDetailDto | null>(null)

  /** 账单支付记录（可独立于 currentBilling 使用） */
  const payments = ref<Api.Billing.PaymentRecordDto[]>([])

  /** 统计数据 */
  const statistics = ref<Api.Billing.BillingStatisticsDto | null>(null)

  /** 逾期账单列表（用于逾期提醒/排行榜等，避免与 getter 同名冲突） */
  const overdueList = ref<Api.Billing.BillingListDto[]>([])

  /** 筛选条件（与后端 Query 保持一致） */
  const filters = ref<Partial<Api.Billing.BillingListParams>>({
    PageNumber: 1,
    PageSize: 20,
    SortBy: 'CreatedAt',
    SortDesc: true
  })

  /** 分页信息（来自后端 PageResult） */
  const pagination = ref<BillingPagination>({
    page: 1,
    pageSize: 20,
    totalCount: 0,
    totalPages: 0
  })

  /** 选中的账单 ID 集合 */
  const selectedIds = ref<string[]>([])

  /** 加载状态 */
  const loading = ref(false)

  // ==================== Getters ====================

  /** 待支付账单 */
  const pendingBillings = computed(() =>
    billings.value.filter((b) => b.status === TenantBillingStatus.Pending)
  )

  /** 逾期账单 */
  const overdueBillings = computed(() =>
    billings.value.filter((b) => b.status === TenantBillingStatus.Overdue)
  )

  /** 当前列表合计金额（应付） */
  const totalAmount = computed(() => billings.value.reduce((sum, b) => sum + (b.amountDue || 0), 0))

  /** 已选数量 */
  const selectedCount = computed(() => selectedIds.value.length)

  // ==================== Actions ====================

  /**
   * 获取账单列表
   * @param params 查询参数（可选）
   */
  const fetchBillings = async (params?: Partial<Api.Billing.BillingListParams>) => {
    // 1. 进入加载态
    loading.value = true

    try {
      // 2. 合并参数（以传入 params 覆盖 filters）
      const query: Partial<Api.Billing.BillingListParams> = {
        ...filters.value,
        ...(params || {})
      }

      // 3. 请求列表数据
      const res = await apiFetchBillingList(query)

      // 4. 写入列表与分页
      billings.value = res.items || []
      pagination.value = {
        page: res.page ?? query.PageNumber ?? 1,
        pageSize: res.pageSize ?? query.PageSize ?? 20,
        totalCount: res.totalCount ?? 0,
        totalPages: res.totalPages ?? 0
      }

      // 5. 更新筛选条件（保持 UI 与 Store 一致）
      filters.value = query
    } finally {
      // 6. 退出加载态
      loading.value = false
    }
  }

  /**
   * 获取账单详情
   * @param id 账单 ID
   */
  const fetchBillingDetail = async (id: string) => {
    // 1. 进入加载态
    loading.value = true

    try {
      // 2. 请求详情
      currentBilling.value = await apiFetchBillingDetail(id)

      // 3. 同步支付记录（便于页面复用）
      payments.value = currentBilling.value?.payments || []
    } finally {
      // 4. 退出加载态
      loading.value = false
    }
  }

  /**
   * 创建账单
   * @param data 创建账单参数
   */
  const createBilling = async (data: Api.Billing.CreateBillingCommand) => {
    // 1. 创建
    const created = await apiCreateBilling(data)

    // 2. 刷新列表（保持 UI 一致）
    await fetchBillings({ PageNumber: 1 })

    return created
  }

  /**
   * 更新账单状态
   * @param id 账单 ID
   * @param status 新状态
   * @param notes 备注（可选）
   */
  const updateStatus = async (
    id: string,
    status: Api.Billing.TenantBillingStatus,
    notes?: string
  ) => {
    // 1. 更新状态
    const updated = await apiUpdateBillingStatus(id, { status, notes })

    // 2. 同步列表项
    const index = billings.value.findIndex((b) => b.id === id)
    if (index !== -1) {
      billings.value[index] = { ...billings.value[index], ...updated }
    }

    // 3. 同步详情
    if (currentBilling.value?.id === id) {
      currentBilling.value = { ...currentBilling.value, ...updated }
    }

    return updated
  }

  /**
   * 记录支付
   * @param billingId 账单 ID
   * @param data 支付参数
   */
  const recordPayment = async (billingId: string, data: Api.Billing.RecordPaymentCommand) => {
    // 1. 记录支付
    const payment = await apiRecordPayment(billingId, data)

    // 2. 刷新详情（保证支付列表最新）
    await fetchBillingDetail(billingId)

    return payment
  }

  /**
   * 获取支付记录列表
   * @param billingId 账单 ID
   */
  const fetchPayments = async (billingId: string) => {
    // 1. 进入加载态
    loading.value = true

    try {
      // 2. 拉取支付记录
      payments.value = (await apiFetchBillingPayments(billingId)) || []

      // 3. 若当前详情一致，则同步
      if (currentBilling.value?.id === billingId) {
        currentBilling.value = { ...currentBilling.value, payments: payments.value }
      }
    } finally {
      // 4. 退出加载态
      loading.value = false
    }
  }

  /**
   * 审核支付记录
   * @param paymentId 支付记录 ID
   * @param approved 是否通过
   * @param notes 备注（可选）
   */
  const verifyPayment = async (paymentId: string, approved: boolean, notes?: string) => {
    // 1. 请求审核
    const updated = await apiVerifyPayment(paymentId, { approved, notes })

    // 2. 同步本地支付记录
    const index = payments.value.findIndex((p) => p.id === paymentId)
    if (index !== -1) payments.value[index] = { ...payments.value[index], ...updated }

    // 3. 若当前详情存在，则同步详情 payments
    if (currentBilling.value?.payments) {
      const idx = currentBilling.value.payments.findIndex((p) => p.id === paymentId)
      if (idx !== -1) {
        currentBilling.value = {
          ...currentBilling.value,
          payments: currentBilling.value.payments.map((p) =>
            p.id === paymentId ? { ...p, ...updated } : p
          )
        }
      }
    }

    return updated
  }

  /**
   * 作废账单（若后端支持 DELETE 作废）
   * @param id 账单 ID
   * @param reason 作废原因
   */
  const cancelBilling = async (id: string, reason: string) => {
    // 1. 发起作废
    await apiCancelBilling(id, { reason })

    // 2. 刷新列表/详情，保证状态一致
    await fetchBillings()
    if (currentBilling.value?.id === id) {
      await fetchBillingDetail(id)
    }
  }

  /**
   * 批量更新账单状态
   * @param data 批量更新命令
   */
  const batchUpdateStatus = async (data: Api.Billing.BatchUpdateStatusCommand) => {
    // 1. 发起更新
    await apiBatchUpdateStatus(data)

    // 2. 刷新列表
    await fetchBillings()
  }

  /**
   * 拉取逾期账单列表（用于排行榜/提醒）
   * @param params 查询参数
   */
  const fetchOverdueList = async (params?: Partial<Api.Billing.BillingListParams>) => {
    // 1. 进入加载态
    loading.value = true

    try {
      // 2. 拉取逾期账单
      const res = await apiFetchOverdueBillings(params)
      overdueList.value = res.items || []
      return res
    } finally {
      // 3. 退出加载态
      loading.value = false
    }
  }

  /**
   * 导出账单（后端导出接口）
   * @param data 导出参数
   */
  const exportBillings = async (data: Api.Billing.ExportParams) => {
    // 1. 获取文件流
    return apiExportBillings(data)
  }

  /**
   * 获取统计数据
   * @param params 统计查询参数
   */
  const fetchStatistics = async (params: Api.Billing.BillingStatisticsParams) => {
    // 1. 进入加载态
    loading.value = true

    try {
      // 2. 请求统计数据
      statistics.value = await apiFetchBillingStatistics(params)
    } finally {
      // 3. 退出加载态
      loading.value = false
    }
  }

  /**
   * 设置筛选条件（不自动请求）
   * @param nextFilters 新筛选条件
   */
  const setFilters = (nextFilters: Partial<Api.Billing.BillingListParams>) => {
    // 1. 合并筛选条件
    filters.value = { ...filters.value, ...nextFilters }
  }

  /**
   * 选中/取消选中某条账单（切换）
   * @param id 账单 ID
   */
  const selectBilling = (id: string) => {
    // 1. 切换选中状态
    if (selectedIds.value.includes(id)) {
      selectedIds.value = selectedIds.value.filter((x) => x !== id)
      return
    }

    selectedIds.value = [...selectedIds.value, id]
  }

  /**
   * 全选当前列表
   */
  const selectAll = () => {
    // 1. 全选当前页数据
    selectedIds.value = billings.value.map((b) => b.id)
  }

  /**
   * 清空选择
   */
  const clearSelection = () => {
    // 1. 清空已选
    selectedIds.value = []
  }

  return {
    // State
    billings,
    currentBilling,
    payments,
    statistics,
    overdueList,
    filters,
    pagination,
    selectedIds,
    loading,

    // Getters
    pendingBillings,
    overdueBillings,
    totalAmount,
    selectedCount,

    // Actions
    fetchBillings,
    fetchBillingDetail,
    createBilling,
    updateStatus,
    recordPayment,
    fetchPayments,
    verifyPayment,
    cancelBilling,
    batchUpdateStatus,
    fetchOverdueList,
    exportBillings,
    fetchStatistics,
    setFilters,
    selectBilling,
    selectAll,
    clearSelection
  }
})
