<template>
  <ArtTableFullScreen>
    <div class="agent-recharge-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"
        >
          <template #left>
            <ElButton
              type="primary"
              @click="showCreateDialog"
              v-if="hasAuth('agent_recharge:create')"
              >创建充值订单</ElButton
            >
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="rechargeList"
          :currentPage="pagination.page"
          :pageSize="pagination.page_size"
          :total="pagination.total"
          :marginTop="10"
          :actions="getActions"
          :actionsWidth="120"
          @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="createDialogVisible"
          title="创建充值订单"
          width="500px"
          @closed="handleCreateDialogClosed"
        >
          <ElForm ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
            <ElFormItem label="充值金额" prop="amount">
              <ElInputNumber
                v-model="createForm.amount"
                :min="100"
                :max="1000000"
                :precision="2"
                :step="100"
                style="width: 100%"
                placeholder="请输入充值金额（元）"
              />
              <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary)">
                充值范围: ¥100 ~ ¥1,000,000
              </div>
            </ElFormItem>
            <ElFormItem label="支付方式" prop="payment_method">
              <ElSelect
                v-model="createForm.payment_method"
                placeholder="请选择支付方式"
                style="width: 100%"
              >
                <!-- 所有用户都显示微信在线支付 -->
                <ElOption label="微信在线支付" value="wechat" />
                <!-- 平台用户额外显示线下转账 -->
                <ElOption
                  v-if="userStore.info.user_type === 1 || userStore.info.user_type === 2"
                  label="线下转账"
                  value="offline"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="店铺" prop="shop_id">
              <ElCascader
                v-model="createForm.shop_id"
                :options="shopCascadeOptions"
                :props="shopCascadeProps"
                placeholder="请选择店铺"
                filterable
                clearable
                style="width: 100%"
                @change="handleShopChange"
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="createDialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleCreateRecharge" :loading="createLoading">
                确认创建
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 确认线下支付对话框 -->
        <ElDialog
          v-model="confirmPayDialogVisible"
          title="确认线下充值"
          width="400px"
          @closed="handleConfirmPayDialogClosed"
        >
          <ElForm
            ref="confirmPayFormRef"
            :model="confirmPayForm"
            :rules="confirmPayRules"
            label-width="100px"
          >
            <ElFormItem label="充值单号">
              <span>{{ currentRecharge?.recharge_no }}</span>
            </ElFormItem>
            <ElFormItem label="充值金额">
              <span>{{ formatCurrency(currentRecharge?.amount || 0) }}</span>
            </ElFormItem>
            <ElFormItem label="操作密码" prop="operation_password">
              <ElInput
                v-model="confirmPayForm.operation_password"
                type="password"
                placeholder="请输入操作密码"
                show-password
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="confirmPayDialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleConfirmPay" :loading="confirmPayLoading">
                确认支付
              </ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { useRouter } from 'vue-router'
  import { AgentRechargeService, ShopService } from '@/api/modules'
  import { ElMessage, ElTag, ElTreeSelect, ElButton, ElCascader } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type {
    AgentRecharge,
    AgentRechargeQueryParams,
    AgentRechargeStatus,
    AgentRechargePaymentMethod,
    CreateAgentRechargeRequest,
    ConfirmOfflinePaymentRequest,
    ShopResponse
  } from '@/types/api'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useUserStore } from '@/store/modules/user'
  import { formatDateTime } from '@/utils/business/format'
  import { RoutesAlias } from '@/router/routesAlias'
  import { useAuth } from '@/composables/useAuth'

  defineOptions({ name: 'AgentRechargeList' })

  const router = useRouter()
  const userStore = useUserStore()
  const { hasAuth } = useAuth()

  const loading = ref(false)
  const createLoading = ref(false)
  const confirmPayLoading = ref(false)
  const tableRef = ref()
  const createDialogVisible = ref(false)
  const confirmPayDialogVisible = ref(false)
  const currentRecharge = ref<AgentRecharge | null>(null)

  // 搜索表单初始值
  const initialSearchState: AgentRechargeQueryParams = {
    shop_id: undefined,
    status: undefined,
    start_date: '',
    end_date: ''
  }

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

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

  // 店铺级联选择相关
  const shopCascadeOptions = ref<any[]>([])
  const shopCascadeProps = {
    lazy: true,
    checkStrictly: true,
    lazyLoad: async (node: any, resolve: any) => {
      const { level, value } = node
      const parentId = level === 0 ? undefined : value

      try {
        const res = await ShopService.getShopsCascade({ parent_id: parentId })
        if (res.code === 0) {
          const nodes = (res.data || []).map((item: any) => ({
            value: item.id,
            label: item.shop_name,
            leaf: !item.has_children
          }))
          resolve(nodes)
        } else {
          resolve([])
        }
      } catch (error) {
        console.error('加载店铺级联数据失败:', error)
        resolve([])
      }
    },
    value: 'value',
    label: 'label',
    children: 'children'
  }

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: '店铺',
      prop: 'shop_id',
      type: 'select',
      placeholder: '请选择店铺',
      options: () =>
        shopOptions.value.map((shop) => ({
          label: shop.shop_name,
          value: shop.id
        })),
      config: {
        clearable: true,
        filterable: true
      }
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      placeholder: '请选择状态',
      options: [
        { label: '待支付', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已取消', value: 3 }
      ],
      config: {
        clearable: true
      }
    },
    {
      label: '创建时间',
      prop: 'dateRange',
      type: 'daterange',
      config: {
        clearable: true,
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  ]

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

  // 列配置
  const columnOptions = [
    { label: '充值单号', prop: 'recharge_no' },
    { label: '店铺名称', prop: 'shop_name' },
    { label: '充值金额', prop: 'amount' },
    { label: '状态', prop: 'status' },
    { label: '支付方式', prop: 'payment_method' },
    { label: '支付通道', prop: 'payment_channel' },
    { label: '创建时间', prop: 'created_at' },
    { label: '支付时间', prop: 'paid_at' },
    { label: '完成时间', prop: 'completed_at' }
  ]

  const createFormRef = ref<FormInstance>()
  const confirmPayFormRef = ref<FormInstance>()

  const createRules = reactive<FormRules>({
    amount: [{ required: true, message: '请输入充值金额', trigger: 'blur' }],
    payment_method: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
    shop_id: [{ required: true, message: '请选择目标店铺', trigger: 'change' }]
  })

  const confirmPayRules = reactive<FormRules>({
    operation_password: [{ required: true, message: '请输入操作密码', trigger: 'blur' }]
  })

  const createForm = reactive<{ amount: number; payment_method: string; shop_id: number | null }>({
    amount: 100,
    payment_method: '',
    shop_id: null
  })

  const confirmPayForm = reactive<ConfirmOfflinePaymentRequest>({
    operation_password: ''
  })

  const rechargeList = ref<AgentRecharge[]>([])

  // 格式化货币 - 将分转换为元
  const formatCurrency = (amount: number): string => {
    return `¥${(amount / 100).toFixed(2)}`
  }

  // 获取状态标签类型
  const getStatusType = (status: AgentRechargeStatus): 'warning' | 'success' | 'info' => {
    const statusMap: Record<AgentRechargeStatus, 'warning' | 'success' | 'info'> = {
      1: 'warning', // 待支付
      2: 'success', // 已完成
      3: 'info' // 已取消
    }
    return statusMap[status] || 'info'
  }

  // 获取状态文本
  const getStatusText = (status: AgentRechargeStatus): string => {
    const statusMap: Record<AgentRechargeStatus, string> = {
      1: '待支付',
      2: '已完成',
      3: '已取消'
    }
    return statusMap[status] || '-'
  }

  // 获取支付方式文本
  const getPaymentMethodText = (method: AgentRechargePaymentMethod): string => {
    const methodMap: Record<AgentRechargePaymentMethod, string> = {
      wechat: '微信在线支付',
      offline: '线下转账'
    }
    return methodMap[method] || method
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'recharge_no',
      label: '充值单号',
      minWidth: 240,
      formatter: (row: AgentRecharge) => {
        return h(
          'span',
          {
            style: 'color: var(--el-color-primary); cursor: pointer; text-decoration: underline;',
            onClick: (e: MouseEvent) => {
              e.stopPropagation()
              handleViewDetail(row)
            }
          },
          row.recharge_no
        )
      }
    },
    {
      prop: 'shop_name',
      label: '店铺名称',
      minWidth: 150
    },
    {
      prop: 'amount',
      label: '充值金额',
      width: 120,
      formatter: (row: AgentRecharge) => formatCurrency(row.amount)
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: AgentRecharge) => {
        return h(ElTag, { type: getStatusType(row.status) }, () => getStatusText(row.status))
      }
    },
    {
      prop: 'payment_method',
      label: '支付方式',
      width: 120,
      formatter: (row: AgentRecharge) => getPaymentMethodText(row.payment_method)
    },
    {
      prop: 'payment_channel',
      label: '支付通道',
      width: 120,
      formatter: (row: AgentRecharge) => row.payment_channel || '-'
    },
    {
      prop: 'created_at',
      label: '创建时间',
      width: 180,
      formatter: (row: AgentRecharge) => formatDateTime(row.created_at)
    },
    {
      prop: 'paid_at',
      label: '支付时间',
      width: 180,
      formatter: (row: AgentRecharge) => (row.paid_at ? formatDateTime(row.paid_at) : '-')
    },
    {
      prop: 'completed_at',
      label: '完成时间',
      width: 180,
      formatter: (row: AgentRecharge) => (row.completed_at ? formatDateTime(row.completed_at) : '-')
    }
  ])

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

  // 构建树形数据
  const buildTreeData = (items: ShopResponse[]) => {
    const map = new Map<number, ShopResponse & { children?: ShopResponse[] }>()
    const tree: ShopResponse[] = []

    // 先将所有项放入 map
    items.forEach((item) => {
      map.set(item.id, { ...item, children: [] })
    })

    // 构建树形结构
    items.forEach((item) => {
      const node = map.get(item.id)!
      if (item.parent_id && map.has(item.parent_id)) {
        // 有父节点，添加到父节点的 children 中
        const parent = map.get(item.parent_id)!
        if (!parent.children) parent.children = []
        parent.children.push(node)
      } else {
        // 没有父节点或父节点不存在，作为根节点
        tree.push(node)
      }
    })

    return tree
  }

  // 加载店铺列表 - 改用级联查询
  const loadShops = async () => {
    try {
      // 加载平铺列表用于搜索（保留原有逻辑）
      const res1 = await ShopService.getShops({ page: 1, page_size: 9999 })
      if (res1.code === 0) {
        shopOptions.value = res1.data.items || []
      }

      // 加载顶级店铺用于级联选择
      const res2 = await ShopService.getShopsCascade({ parent_id: undefined })
      if (res2.code === 0) {
        shopCascadeOptions.value = (res2.data || []).map((item: any) => ({
          value: item.id,
          label: item.shop_name,
          leaf: !item.has_children
        }))
      }
    } catch (error) {
      console.error('Load shops failed:', error)
    }
  }

  // 处理店铺选择变化
  const handleShopChange = (value: any) => {
    if (Array.isArray(value) && value.length > 0) {
      createForm.shop_id = value[value.length - 1]
    } else {
      createForm.shop_id = null
    }
  }

  // 获取充值订单列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params: AgentRechargeQueryParams = {
        page: pagination.page,
        page_size: pagination.page_size,
        shop_id: searchForm.shop_id,
        status: searchForm.status,
        start_date: searchForm.start_date || undefined,
        end_date: searchForm.end_date || undefined
      }
      const res = await AgentRechargeService.getAgentRecharges(params)
      if (res.code === 0) {
        rechargeList.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_date = searchForm.dateRange[0]
      searchForm.end_date = searchForm.dateRange[1]
    } else {
      searchForm.start_date = ''
      searchForm.end_date = ''
    }
    pagination.page = 1
    getTableData()
  }

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

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

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

  // 显示创建订单对话框
  const showCreateDialog = async () => {
    // 重新加载店铺列表，确保获取最新数据
    await loadShops()
    // 所有用户默认微信支付
    createForm.payment_method = 'wechat'
    createDialogVisible.value = true
  }

  // 对话框关闭后的清理
  const handleCreateDialogClosed = () => {
    createFormRef.value?.resetFields()
    createForm.amount = 100
    createForm.payment_method = ''
    createForm.shop_id = null
  }

  // 创建充值订单
  const handleCreateRecharge = async () => {
    if (!createFormRef.value) return

    await createFormRef.value.validate(async (valid) => {
      if (valid) {
        createLoading.value = true
        try {
          const data: CreateAgentRechargeRequest = {
            amount: createForm.amount * 100, // 元转分
            payment_method: createForm.payment_method as AgentRechargePaymentMethod,
            shop_id: createForm.shop_id!
          }

          await AgentRechargeService.createAgentRecharge(data)
          ElMessage.success('充值订单创建成功')
          createDialogVisible.value = false
          createFormRef.value.resetFields()
          await getTableData()
        } catch (error) {
          console.error(error)
        } finally {
          createLoading.value = false
        }
      }
    })
  }

  // 显示确认支付对话框
  const handleShowConfirmPay = (row: AgentRecharge) => {
    currentRecharge.value = row
    confirmPayDialogVisible.value = true
  }

  // 确认支付对话框关闭后的清理
  const handleConfirmPayDialogClosed = () => {
    confirmPayFormRef.value?.resetFields()
    confirmPayForm.operation_password = ''
    currentRecharge.value = null
  }

  // 确认线下支付
  const handleConfirmPay = async () => {
    if (!confirmPayFormRef.value || !currentRecharge.value) return

    await confirmPayFormRef.value.validate(async (valid) => {
      if (valid) {
        confirmPayLoading.value = true
        try {
          await AgentRechargeService.confirmOfflinePayment(currentRecharge.value.id, {
            operation_password: confirmPayForm.operation_password
          })
          ElMessage.success('确认支付成功')
          confirmPayDialogVisible.value = false
          confirmPayFormRef.value.resetFields()
          await getTableData()
        } catch (error) {
          console.error(error)
        } finally {
          confirmPayLoading.value = false
        }
      }
    })
  }

  // 查看详情
  const handleViewDetail = (row: AgentRecharge) => {
    router.push({
      name: 'AgentRechargeDetailRoute',
      params: { id: row.id }
    })
  }

  // 获取操作按钮
  const getActions = (row: AgentRecharge) => {
    const actions: any[] = []

    // 待支付且线下转账的订单可以确认支付
    if (
      row.status === 1 &&
      row.payment_method === 'offline' &&
      hasAuth('agent_recharge:confirm_payment')
    ) {
      actions.push({
        label: '确认支付',
        handler: () => handleShowConfirmPay(row),
        type: 'primary'
      })
    }

    return actions
  }
</script>

<style scoped lang="scss">
  .agent-recharge-page {
    height: 100%;
  }
</style>
