<template>
  <ArtTableFullScreen>
    <div class="withdrawal-approval-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        @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="$t('commission.dialog.reject')"
          width="500px"
        >
          <ElForm ref="rejectFormRef" :model="rejectForm" :rules="rejectRules" label-width="100px">
            <ElFormItem :label="$t('commission.form.rejectReason')" prop="reject_reason">
              <ElInput
                v-model="rejectForm.reject_reason"
                type="textarea"
                :rows="4"
                :placeholder="$t('commission.form.rejectReasonPlaceholder')"
              />
            </ElFormItem>
            <ElFormItem :label="$t('commission.form.remark')" prop="remark">
              <ElInput
                v-model="rejectForm.remark"
                type="textarea"
                :rows="3"
                :placeholder="$t('commission.form.remarkPlaceholder')"
              />
            </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 } 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()

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

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

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

  // 提现状态选项
  const withdrawalStatusOptions = [
    { label: t('commission.status.pending'), value: 1 },
    { label: t('commission.status.approved'), value: 2 },
    { label: t('commission.status.rejected'), value: 3 },
    { label: t('commission.status.completed'), value: 4 }
  ]

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: t('commission.searchForm.status'),
      prop: 'status',
      type: 'select',
      options: withdrawalStatusOptions,
      config: {
        clearable: true,
        placeholder: t('commission.searchForm.statusPlaceholder')
      }
    },
    {
      label: t('commission.searchForm.withdrawalNo'),
      prop: 'withdrawal_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: t('commission.searchForm.withdrawalNoPlaceholder')
      }
    },
    {
      label: t('commission.searchForm.shopName'),
      prop: 'shop_name',
      type: 'input',
      config: {
        clearable: true,
        placeholder: t('commission.searchForm.shopNamePlaceholder')
      }
    },
    {
      label: t('commission.searchForm.dateRange'),
      prop: 'dateRange',
      type: 'daterange',
      config: {
        clearable: true,
        startPlaceholder: t('commission.searchForm.dateRangePlaceholder.0'),
        endPlaceholder: t('commission.searchForm.dateRangePlaceholder.1'),
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        onChange: (val: [string, string] | null) => {
          if (val && val.length === 2) {
            searchForm.start_time = val[0]
            searchForm.end_time = val[1]
          } else {
            searchForm.start_time = ''
            searchForm.end_time = ''
          }
        }
      }
    }
  ]

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

  // 列配置
  const columnOptions = [
    { label: t('commission.table.withdrawalNo'), prop: 'withdrawal_no' },
    { label: t('commission.table.shopName'), prop: 'shop_name' },
    { label: t('commission.table.applicant'), prop: 'applicant_name' },
    { label: t('commission.table.withdrawalAmount'), prop: 'amount' },
    { label: t('commission.table.fee'), prop: 'fee' },
    { label: t('commission.table.actualAmount'), prop: 'actual_amount' },
    { label: t('commission.table.withdrawalMethod'), prop: 'withdrawal_method' },
    { label: t('commission.table.status'), prop: 'status' },
    { label: t('commission.table.applyTime'), prop: 'created_at' },
    { label: t('commission.table.approveTime'), prop: 'processed_at' },
    { label: t('commission.table.actions'), prop: 'operation' }
  ]

  const rejectFormRef = ref<FormInstance>()

  const rejectRules = reactive<FormRules>({
    reject_reason: [
      { required: true, message: t('commission.validation.rejectReasonRequired'), trigger: 'blur' }
    ],
    remark: [
      { required: true, message: t('commission.validation.remarkRequired'), trigger: 'blur' }
    ]
  })

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

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

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'withdrawal_no',
      label: t('commission.table.withdrawalNo'),
      minWidth: 180
    },
    {
      prop: 'shop_name',
      label: t('commission.table.shopName'),
      minWidth: 150
    },
    {
      prop: 'applicant_name',
      label: t('commission.table.applicant'),
      width: 120
    },
    {
      prop: 'amount',
      label: t('commission.table.withdrawalAmount'),
      width: 120,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.amount)
    },
    {
      prop: 'fee',
      label: t('commission.table.fee'),
      width: 100,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.fee)
    },
    {
      prop: 'actual_amount',
      label: t('commission.table.actualAmount'),
      width: 120,
      align: 'right',
      formatter: (row: WithdrawalRequestItem) => formatMoney(row.actual_amount)
    },
    {
      prop: 'withdrawal_method',
      label: t('commission.table.withdrawalMethod'),
      width: 120,
      formatter: (row: WithdrawalRequestItem) => {
        const method = WithdrawalMethodMap[row.withdrawal_method as WithdrawalMethod]
        return method?.label || row.withdrawal_method
      }
    },
    {
      prop: 'status',
      label: t('commission.table.status'),
      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: t('commission.table.applyTime'),
      width: 180,
      formatter: (row: WithdrawalRequestItem) => formatDateTime(row.created_at)
    },
    {
      prop: 'processed_at',
      label: t('commission.table.approveTime'),
      width: 180,
      formatter: (row: WithdrawalRequestItem) => formatDateTime(row.processed_at)
    },
    {
      prop: 'operation',
      label: t('commission.table.actions'),
      width: 150,
      fixed: 'right',
      formatter: (row: WithdrawalRequestItem) => {
        // 只有待审核状态才显示操作按钮
        if (row.status === 1) {
          return h('div', { style: 'display: flex; gap: 8px;' }, [
            h(ArtButtonTable, {
              text: t('commission.buttons.approve'),
              iconColor: '#67C23A',
              onClick: () => handleApprove(row)
            }),
            h(ArtButtonTable, {
              text: t('commission.buttons.reject'),
              iconColor: '#F56C6C',
              onClick: () => showRejectDialog(row)
            })
          ])
        }
        return '-'
      }
    }
  ])

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

  // 获取提现申请列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        pageSize: 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 = () => {
    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('commission.messages.approveConfirm'), t('common.tips'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
      .then(async () => {
        try {
          await CommissionService.approveWithdrawal(row.id)
          ElMessage.success(t('commission.messages.approveSuccess'))
          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(t('commission.messages.rejectSuccess'))
          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>
