<template>
  <ArtTableFullScreen>
    <div class="withdrawal-approval-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        show-expand
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

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

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="withdrawalList"
          :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>

        <!-- 拒绝提现对话框 -->
        <ElDialog v-model="rejectDialogVisible" title="拒绝提现申请" width="500px">
          <ElForm ref="rejectFormRef" :model="rejectForm" :rules="rejectRules" label-width="100px">
            <ElFormItem label="拒绝原因" prop="reject_reason">
              <ElInput
                v-model="rejectForm.reject_reason"
                type="textarea"
                :rows="4"
                placeholder="请输入拒绝原因"
              />
            </ElFormItem>
            <ElFormItem label="备注" prop="remark">
              <ElInput
                v-model="rejectForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="rejectDialogVisible = false">{{ $t('common.cancel') }}</ElButton>
              <ElButton type="primary" @click="handleRejectSubmit" :loading="rejectSubmitLoading">
                {{ $t('common.confirm') }}
              </ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { CommissionService, ShopService } from '@/api/modules'
  import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type {
    WithdrawalRequestItem,
    WithdrawalStatus,
    WithdrawalMethod
  } from '@/types/api/commission'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { formatDateTime, formatMoney } from '@/utils/business/format'
  import { WithdrawalStatusMap, WithdrawalMethodMap } from '@/config/constants'
  import { useI18n } from 'vue-i18n'

  defineOptions({ name: 'WithdrawalApproval' })

  const { t } = useI18n() // 仅保留用于 common.tips, common.confirm, common.cancel

  const rejectDialogVisible = ref(false)
  const loading = ref(false)
  const rejectSubmitLoading = ref(false)
  const tableRef = ref()
  const currentWithdrawalId = ref<number>(0)

  // 店铺选项
  const shopOptions = ref<any[]>([])

  // 搜索表单初始值
  const initialSearchState = {
    withdrawal_no: '',
    shop_name: '',
    status: undefined as WithdrawalStatus | undefined,
    dateRange: [],
    start_time: '',
    end_time: ''
  }

  // 搜索表单
  const searchForm = reactive({ ...initialSearchState })

  // 提现状态选项
  const withdrawalStatusOptions = [
    { label: '待审核', value: 1 },
    { label: '已通过', value: 2 },
    { label: '已拒绝', value: 3 },
    { label: '已到账', value: 4 }
  ]

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: '提现单号',
      prop: 'withdrawal_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入提现单号'
      }
    },
    {
      label: '店铺名称',
      prop: 'shop_name',
      type: 'select',
      placeholder: '请输入店铺名称搜索',
      options: () =>
        shopOptions.value.map((shop) => ({
          label: shop.shop_name,
          value: shop.shop_name
        })),
      config: {
        clearable: true,
        filterable: true,
        remote: true,
        remoteMethod: (query: string) => searchShops(query)
      }
    },
    {
      label: '审核状态',
      prop: 'status',
      type: 'select',
      options: withdrawalStatusOptions,
      config: {
        clearable: true,
        placeholder: '请选择审核状态'
      }
    },
    {
      label: '起止时间',
      prop: 'dateRange',
      type: 'date',
      config: {
        type: 'daterange',
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  ]

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

  // 列配置
  const columnOptions = [
    { label: '提现单号', prop: 'withdrawal_no' },
    { label: '店铺名称', prop: 'shop_name' },
    { label: '申请人', prop: 'applicant_name' },
    { label: '提现金额', prop: 'amount' },
    { label: '手续费', prop: 'fee' },
    { label: '实际到账', prop: 'actual_amount' },
    { label: '提现方式', prop: 'withdrawal_method' },
    { label: '状态', prop: 'status' },
    { label: '申请时间', prop: 'created_at' },
    { label: '审批时间', prop: 'processed_at' },
    { label: '操作', prop: 'operation' }
  ]

  const rejectFormRef = ref<FormInstance>()

  const rejectRules = reactive<FormRules>({
    reject_reason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }],
    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
  })

  const rejectForm = reactive({
    reject_reason: '',
    remark: ''
  })

  const withdrawalList = ref<WithdrawalRequestItem[]>([])

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'withdrawal_no',
      label: '提现单号',
      minWidth: 180
    },
    {
      prop: 'shop_name',
      label: '店铺名称',
      minWidth: 150
    },
    {
      prop: 'applicant_name',
      label: '申请人',
      width: 120
    },
    {
      prop: 'amount',
      label: '提现金额',
      width: 120,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.amount)
    },
    {
      prop: 'fee',
      label: '手续费',
      width: 100,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.fee)
    },
    {
      prop: 'actual_amount',
      label: '实际到账',
      width: 120,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.actual_amount)
    },
    {
      prop: 'withdrawal_method',
      label: '提现方式',
      width: 120,
      formatter: (row: WithdrawalRequestItem) => {
        const method = WithdrawalMethodMap[row.withdrawal_method as WithdrawalMethod]
        return method?.label || row.withdrawal_method
      }
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: WithdrawalRequestItem) => {
        const statusInfo = WithdrawalStatusMap[row.status as keyof typeof WithdrawalStatusMap]
        return h(ElTag, { type: statusInfo?.type || 'info' }, () => statusInfo?.label || '未知')
      }
    },
    {
      prop: 'created_at',
      label: '申请时间',
      width: 180,
      formatter: (row: WithdrawalRequestItem) => formatDateTime(row.created_at)
    },
    {
      prop: 'processed_at',
      label: '审批时间',
      width: 180,
      formatter: (row: WithdrawalRequestItem) => formatDateTime(row.processed_at)
    },
    {
      prop: 'operation',
      label: '操作',
      width: 150,
      fixed: 'right',
      formatter: (row: WithdrawalRequestItem) => {
        // 只有待审核状态才显示操作按钮
        if (row.status === 1) {
          return h('div', { style: 'display: flex; gap: 8px;' }, [
            h(ArtButtonTable, {
              text: '审批通过',
              iconColor: '#67C23A',
              onClick: () => handleApprove(row)
            }),
            h(ArtButtonTable, {
              text: '拒绝',
              iconColor: '#F56C6C',
              onClick: () => showRejectDialog(row)
            })
          ])
        }
        return '-'
      }
    }
  ])

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

  // 搜索店铺
  const searchShops = async (query: string) => {
    try {
      const params: any = {
        page: 1,
        page_size: 20
      }
      if (query) {
        params.shop_name = query
      }
      const res = await ShopService.getShops(params)
      if (res.code === 0) {
        shopOptions.value = res.data.items || []
      }
    } catch (error) {
      console.error('Search shops failed:', error)
    }
  }

  // 获取提现申请列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        page_size: pagination.pageSize,
        withdrawal_no: searchForm.withdrawal_no || undefined,
        shop_name: searchForm.shop_name || undefined,
        status: searchForm.status,
        start_time: searchForm.start_time || undefined,
        end_time: searchForm.end_time || undefined
      }
      const res = await CommissionService.getWithdrawalRequests(params)
      if (res.code === 0) {
        withdrawalList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    getTableData()
  }

  // 搜索
  const handleSearch = () => {
    // 处理日期范围
    if (searchForm.dateRange && Array.isArray(searchForm.dateRange)) {
      searchForm.start_time = searchForm.dateRange[0]
      searchForm.end_time = searchForm.dateRange[1]
    } else {
      searchForm.start_time = ''
      searchForm.end_time = ''
    }
    pagination.page = 1
    getTableData()
  }

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

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

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

  // 审批通过
  const handleApprove = (row: WithdrawalRequestItem) => {
    ElMessageBox.confirm('确定要通过该提现申请吗？', t('common.tips'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
      .then(async () => {
        try {
          await CommissionService.approveWithdrawal(row.id)
          ElMessage.success('审批通过成功')
          getTableData()
        } catch (error) {
          console.error(error)
        }
      })
      .catch(() => {
        // 用户取消
      })
  }

  // 显示拒绝对话框
  const showRejectDialog = (row: WithdrawalRequestItem) => {
    currentWithdrawalId.value = row.id
    rejectForm.reject_reason = ''
    rejectForm.remark = ''
    rejectDialogVisible.value = true
  }

  // 提交拒绝
  const handleRejectSubmit = async () => {
    if (!rejectFormRef.value) return

    await rejectFormRef.value.validate(async (valid) => {
      if (valid) {
        rejectSubmitLoading.value = true
        try {
          await CommissionService.rejectWithdrawal(currentWithdrawalId.value, {
            reject_reason: rejectForm.reject_reason,
            remark: rejectForm.remark
          })
          ElMessage.success('拒绝成功')
          rejectDialogVisible.value = false
          rejectFormRef.value?.resetFields()
          getTableData()
        } catch (error) {
          console.error(error)
        } finally {
          rejectSubmitLoading.value = false
        }
      }
    })
  }
</script>

<style lang="scss" scoped>
  .withdrawal-approval-page {
    // 可以在这里添加提现审批页面特定样式
  }
</style>
