<template>
  <div class="agent-commission-container">
    <ArtTableFullScreen>
      <div class="agent-commission-page" id="table-full-screen">
        <!-- 搜索栏 -->
        <ElCard shadow="never" class="search-card">
          <ElForm :inline="true" :model="searchForm" class="search-form">
            <ElFormItem label="店铺名称">
              <ElInput
                v-model="searchForm.shop_name"
                placeholder="请输入店铺名称"
                clearable
                style="width: 200px"
              />
            </ElFormItem>
            <ElFormItem label="店铺编码">
              <ElInput
                v-model="searchForm.shop_code"
                placeholder="请输入店铺编码"
                clearable
                style="width: 200px"
              />
            </ElFormItem>
            <ElFormItem>
              <ElButton type="primary" @click="handleSearch">查询</ElButton>
              <ElButton @click="handleReset">重置</ElButton>
            </ElFormItem>
          </ElForm>
        </ElCard>

        <ElCard shadow="never" class="art-table-card">
          <!-- 表格头部 -->
          <ArtTableHeader
            :columnList="columnOptions"
            v-model:columns="columnChecks"
            @refresh="handleRefresh"
          />

          <!-- 表格 -->
          <ArtTable
            ref="tableRef"
            row-key="shop_id"
            :loading="loading"
            :data="summaryList"
            :currentPage="pagination.page"
            :pageSize="pagination.pageSize"
            :total="pagination.total"
            :marginTop="10"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <template #default>
              <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
            </template>
          </ArtTable>
        </ElCard>
      </div>
    </ArtTableFullScreen>

    <!-- 详情抽屉 -->
    <ElDrawer
      v-model="detailDrawerVisible"
      :title="`${currentShop?.shop_name || ''} - 佣金详情`"
      size="60%"
      destroy-on-close
    >
      <ElTabs v-model="activeTab" class="detail-tabs">
        <!-- 佣金明细 Tab -->
        <ElTabPane label="佣金明细" name="commission">
          <ArtTable
            ref="commissionTableRef"
            row-key="id"
            :loading="commissionLoading"
            :data="commissionRecords"
            :currentPage="commissionPagination.page"
            :pageSize="commissionPagination.pageSize"
            :total="commissionPagination.total"
            :marginTop="10"
            :height="500"
            @size-change="handleCommissionSizeChange"
            @current-change="handleCommissionCurrentChange"
          >
            <template #default>
              <ElTableColumn label="佣金金额" prop="amount" width="120">
                <template #default="scope">
                  <span style="font-weight: 500; color: var(--el-color-success)">
                    {{ formatMoney(scope.row.amount) }}
                  </span>
                </template>
              </ElTableColumn>
              <ElTableColumn label="入账后余额" prop="balance_after" width="120">
                <template #default="scope">
                  {{ formatMoney(scope.row.balance_after) }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="佣金类型" prop="commission_type" width="120">
                <template #default="scope">
                  <ElTag
                    :type="
                      CommissionTypeMap[scope.row.commission_type as keyof typeof CommissionTypeMap]
                        ?.type || 'info'
                    "
                  >
                    {{
                      CommissionTypeMap[scope.row.commission_type as keyof typeof CommissionTypeMap]
                        ?.label || scope.row.commission_type
                    }}
                  </ElTag>
                </template>
              </ElTableColumn>
              <ElTableColumn label="状态" prop="status" width="100">
                <template #default="scope">
                  <ElTag
                    :type="
                      CommissionStatusMap[scope.row.status as keyof typeof CommissionStatusMap]
                        ?.type || 'info'
                    "
                  >
                    {{
                      CommissionStatusMap[scope.row.status as keyof typeof CommissionStatusMap]
                        ?.label || scope.row.status
                    }}
                  </ElTag>
                </template>
              </ElTableColumn>
              <ElTableColumn label="订单号" prop="order_no" min-width="180" show-overflow-tooltip />
              <ElTableColumn label="ICCID" prop="iccid" min-width="150" show-overflow-tooltip />
              <ElTableColumn
                label="设备号"
                prop="device_no"
                min-width="150"
                show-overflow-tooltip
              />
              <ElTableColumn label="入账时间" prop="created_at" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.created_at) }}
                </template>
              </ElTableColumn>
            </template>
          </ArtTable>
        </ElTabPane>

        <!-- 提现记录 Tab -->
        <ElTabPane label="提现记录" name="withdrawal">
          <ArtTable
            ref="withdrawalTableRef"
            row-key="id"
            :loading="withdrawalLoading"
            :data="withdrawalRecords"
            :currentPage="withdrawalPagination.page"
            :pageSize="withdrawalPagination.pageSize"
            :total="withdrawalPagination.total"
            :marginTop="10"
            :height="500"
            @size-change="handleWithdrawalSizeChange"
            @current-change="handleWithdrawalCurrentChange"
          >
            <template #default>
              <ElTableColumn
                label="提现单号"
                prop="withdrawal_no"
                min-width="180"
                show-overflow-tooltip
              />
              <ElTableColumn label="提现金额" prop="amount" width="120">
                <template #default="scope">
                  <span style="font-weight: 500; color: var(--el-color-danger)">
                    {{ formatMoney(scope.row.amount) }}
                  </span>
                </template>
              </ElTableColumn>
              <ElTableColumn label="实际到账" prop="actual_amount" width="120">
                <template #default="scope">
                  {{ formatMoney(scope.row.actual_amount) }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="手续费" prop="fee" width="100">
                <template #default="scope">
                  {{ formatMoney(scope.row.fee) }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="提现方式" prop="withdrawal_method" width="100">
                <template #default="scope">
                  {{
                    WithdrawalMethodMap[
                      scope.row.withdrawal_method as keyof typeof WithdrawalMethodMap
                    ]?.label || scope.row.withdrawal_method
                  }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="状态" prop="status" width="100">
                <template #default="scope">
                  <ElTag
                    :type="
                      WithdrawalStatusMap[scope.row.status as keyof typeof WithdrawalStatusMap]
                        ?.type || 'info'
                    "
                  >
                    {{
                      WithdrawalStatusMap[scope.row.status as keyof typeof WithdrawalStatusMap]
                        ?.label || scope.row.status
                    }}
                  </ElTag>
                </template>
              </ElTableColumn>
              <ElTableColumn label="申请时间" prop="created_at" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.created_at) }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="处理时间" prop="processed_at" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.processed_at) }}
                </template>
              </ElTableColumn>
            </template>
          </ArtTable>
        </ElTabPane>
      </ElTabs>
    </ElDrawer>
  </div>
</template>

<script setup lang="ts">
  import { h, watch, onBeforeUnmount } from 'vue'
  import { useRoute } from 'vue-router'
  import { CommissionService } from '@/api/modules'
  import { ElMessage, ElTag } from 'element-plus'
  import type {
    ShopCommissionSummaryItem,
    ShopCommissionRecordItem,
    WithdrawalRequestItem
  } from '@/types/api/commission'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { formatDateTime, formatMoney } from '@/utils/business/format'
  import {
    CommissionStatusMap,
    WithdrawalStatusMap,
    WithdrawalMethodMap,
    CommissionTypeMap
  } from '@/config/constants/commission'

  defineOptions({ name: 'AgentCommission' })

  const { hasAuth } = useAuth()

  const route = useRoute()

  // 主表格状态
  const loading = ref(false)
  const tableRef = ref()
  const summaryList = ref<ShopCommissionSummaryItem[]>([])

  // 搜索表单
  const searchForm = reactive({
    shop_name: '',
    shop_code: ''
  })

  // 主表格分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 详情抽屉状态
  const detailDrawerVisible = ref(false)
  const activeTab = ref<'commission' | 'withdrawal'>('commission')
  const currentShop = ref<ShopCommissionSummaryItem | null>(null)

  // 佣金明细状态
  const commissionLoading = ref(false)
  const commissionTableRef = ref()
  const commissionRecords = ref<ShopCommissionRecordItem[]>([])
  const commissionPagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 提现记录状态
  const withdrawalLoading = ref(false)
  const withdrawalTableRef = ref()
  const withdrawalRecords = ref<WithdrawalRequestItem[]>([])
  const withdrawalPagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 列配置
  const columnOptions = [
    { label: '店铺编码', prop: 'shop_code' },
    { label: '店铺名称', prop: 'shop_name' },
    { label: '用户名', prop: 'username' },
    { label: '手机号', prop: 'phone' },
    { label: '总佣金', prop: 'total_commission' },
    { label: '可提现', prop: 'available_commission' },
    { label: '冻结中', prop: 'frozen_commission' },
    { label: '提现中', prop: 'withdrawing_commission' },
    { label: '已提现', prop: 'withdrawn_commission' },
    { label: '未提现', prop: 'unwithdraw_commission' },
    { label: '操作', prop: 'operation' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'shop_code',
      label: '店铺编码',
      minWidth: 150
    },
    {
      prop: 'shop_name',
      label: '店铺名称',
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      prop: 'username',
      label: '用户名',
      minWidth: 120
    },
    {
      prop: 'phone',
      label: '手机号',
      width: 130
    },
    {
      prop: 'total_commission',
      label: '总佣金',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => formatMoney(row.total_commission)
    },
    {
      prop: 'available_commission',
      label: '可提现',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => {
        return h(
          'span',
          { style: 'color: var(--el-color-success); font-weight: 500' },
          formatMoney(row.available_commission)
        )
      }
    },
    {
      prop: 'frozen_commission',
      label: '冻结中',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => formatMoney(row.frozen_commission)
    },
    {
      prop: 'withdrawing_commission',
      label: '提现中',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => {
        return h(
          'span',
          { style: 'color: var(--el-color-warning)' },
          formatMoney(row.withdrawing_commission)
        )
      }
    },
    {
      prop: 'withdrawn_commission',
      label: '已提现',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => formatMoney(row.withdrawn_commission)
    },
    {
      prop: 'unwithdraw_commission',
      label: '未提现',
      width: 120,
      formatter: (row: ShopCommissionSummaryItem) => formatMoney(row.unwithdraw_commission)
    },
    {
      prop: 'operation',
      label: '操作',
      width: 120,
      fixed: 'right',
      formatter: (row: ShopCommissionSummaryItem) => {
        const buttons = []
        if (hasAuth('agent_commission:detail')) {
          buttons.push(
            h(ArtButtonTable, {
              text: '详情',
              onClick: () => showDetail(row)
            })
          )
        }
        return h('div', { style: 'display: flex; gap: 8px;' }, buttons)
      }
    }
  ])

  onMounted(() => {
    getTableData()
  })

  // 获取代理商佣金汇总列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        pageSize: pagination.pageSize,
        shop_name: searchForm.shop_name || undefined,
        shop_code: searchForm.shop_code || undefined
      }
      const res = await CommissionService.getShopCommissionSummary(params)
      if (res.code === 0) {
        summaryList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  // 重置
  const handleReset = () => {
    searchForm.shop_name = ''
    searchForm.shop_code = ''
    pagination.page = 1
    getTableData()
  }

  // 刷新
  const handleRefresh = () => {
    getTableData()
  }

  // 分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getTableData()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.page = newCurrentPage
    getTableData()
  }

  // 显示详情抽屉
  const showDetail = (row: ShopCommissionSummaryItem) => {
    currentShop.value = row
    detailDrawerVisible.value = true
    activeTab.value = 'commission'

    // 重置分页
    commissionPagination.page = 1
    withdrawalPagination.page = 1

    // 加载佣金明细
    loadCommissionRecords()
  }

  // 监听tab切换
  watch(activeTab, (newTab) => {
    if (newTab === 'commission') {
      loadCommissionRecords()
    } else if (newTab === 'withdrawal') {
      loadWithdrawalRecords()
    }
  })

  // 监听路由变化，关闭抽屉
  watch(
    () => route.path,
    () => {
      if (detailDrawerVisible.value) {
        detailDrawerVisible.value = false
      }
    }
  )

  // 组件卸载前关闭抽屉
  onBeforeUnmount(() => {
    if (detailDrawerVisible.value) {
      detailDrawerVisible.value = false
    }
  })

  // 加载佣金明细
  const loadCommissionRecords = async () => {
    if (!currentShop.value) return

    commissionLoading.value = true
    try {
      const params = {
        page: commissionPagination.page,
        pageSize: commissionPagination.pageSize
      }
      const res = await CommissionService.getShopCommissionRecords(
        currentShop.value.shop_id,
        params
      )
      if (res.code === 0) {
        commissionRecords.value = res.data.items || []
        commissionPagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取佣金明细失败')
    } finally {
      commissionLoading.value = false
    }
  }

  // 佣金明细分页
  const handleCommissionSizeChange = (newPageSize: number) => {
    commissionPagination.pageSize = newPageSize
    loadCommissionRecords()
  }

  const handleCommissionCurrentChange = (newCurrentPage: number) => {
    commissionPagination.page = newCurrentPage
    loadCommissionRecords()
  }

  // 加载提现记录
  const loadWithdrawalRecords = async () => {
    if (!currentShop.value) return

    withdrawalLoading.value = true
    try {
      const params = {
        page: withdrawalPagination.page,
        pageSize: withdrawalPagination.pageSize
      }
      const res = await CommissionService.getShopWithdrawalRequests(
        currentShop.value.shop_id,
        params
      )
      if (res.code === 0) {
        withdrawalRecords.value = res.data.items || []
        withdrawalPagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取提现记录失败')
    } finally {
      withdrawalLoading.value = false
    }
  }

  // 提现记录分页
  const handleWithdrawalSizeChange = (newPageSize: number) => {
    withdrawalPagination.pageSize = newPageSize
    loadWithdrawalRecords()
  }

  const handleWithdrawalCurrentChange = (newCurrentPage: number) => {
    withdrawalPagination.page = newCurrentPage
    loadWithdrawalRecords()
  }
</script>

<style lang="scss" scoped>
  .agent-commission-container {
    height: 100%;
  }

  .agent-commission-page {
    .search-card {
      margin-bottom: 16px;
    }

    .search-form {
      margin-bottom: 0;
    }
  }

  .detail-tabs {
    :deep(.el-tabs__content) {
      padding: 0;
    }
  }
</style>
