<template>
  <div class="new-app-container layout-vertical">
    <div class="header-container">
      <el-radio-group v-model="activeTab" size="medium" @change="handleTabChange" class="tab-group">
        <el-radio-button label="payment">充值订单（RMB）</el-radio-button>
        <el-radio-button label="topup">充值订单（USDT）</el-radio-button>
      </el-radio-group>

      <el-form v-show="activeTab === 'payment'" :inline="true" :model="paymentSearch" class="search-form" size="medium">
        <el-form-item label="会员ID">
          <el-input v-model="paymentSearch.member_id" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="会员昵称">
          <el-input v-model="paymentSearch.first_name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="paymentSearch.order_no" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="paymentSearch.status" placeholder="请选择" clearable>
            <el-option label="待处理" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="成功" :value="2"></el-option>
            <el-option label="失败" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPaymentSubmit">搜索</el-button>
          <el-button @click="resetPaymentSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-form v-show="activeTab === 'topup'" :inline="true" :model="topupSearch" class="search-form">
        <el-form-item label="会员ID">
          <el-input v-model="topupSearch.member_id" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="会员昵称">
          <el-input v-model="topupSearch.first_name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="topupSearch.status" placeholder="请选择" clearable>
            <el-option v-for="item in topupStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="topupSearch.type" placeholder="请选择" clearable>
            <el-option label="自动" :value="1"></el-option>
            <el-option label="手动" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onTopupSubmit">搜索</el-button>
          <el-button @click="resetTopupSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="activeTab === 'payment'">
      <YMTable
        ref="paymentTable"
        :table-key="1"
        :index="true"
        :selection="false"
        :table-options="paymentTableOptions"
        :edit-form="paymentEditForm"
        :edit-config="paymentEditConfig"
        :columns="paymentColumns"
        :rows-actions="paymentRowsActions"
        :show-summary="false"
        :apis="paymentApis"
        :actionsWidth="120"
        :alertTip="paymentAlertTip"
        :custom-style="{ height: 'calc(100vh - 200px)' }"
        @onResponse="onPaymentResponse"
      />
    </div>

    <div v-show="activeTab === 'topup'">
      <YMTable
        ref="topupTable"
        :table-key="2"
        :index="true"
        :selection="false"
        :table-options="topupTableOptions"
        :edit-form="topupEditForm"
        :edit-config="topupEditConfig"
        :columns="topupColumns"
        :actions-width="120"
        :rows-actions="topupRowsActions"
        :show-summary="false"
        :apis="topupApis"
        :alertTip="topupAlertTip"
        :custom-style="{ height: 'calc(100vh - 200px)' }"
        @onResponse="onTopupResponse"
      />
    </div>

    <Dialog ref="dialog">
      <template slot="content"/>
    </Dialog>
  </div>
</template>

<script>
import Dialog from '@/components/Dialog/index.vue'
import { audit, paymentOrder, menucheck, verifyRecharge } from '@/api/data'

export default {
  components: {
    Dialog
  },
  data() {
    return {
      activeTab: 'payment',
      loading: false,

      paymentSearch: {
        member_id: '',
        first_name: '',
        order_no: '',
        status: ''
      },
      paymentAlertTip: '',
      paymentColumns: [
        { label: '会员ID', prop: 'member_id', width: 120 },
        {
          label: '会员昵称',
          popover: true,
          width: 140,
          props: ['first_name'],
          options: [
            { label: '会员ID', value: ['member_id'] },
            { label: '用户名称', value: ['username'] },
            { label: '异常信息', vShow: (row) => row?.user_admin_note ? true : false, value: ['user_admin_note'] }
          ]
        },
        { label: '订单号', prop: 'order_no' },
        { label: '金额', prop: 'amount' },
        { label: '渠道', prop: 'bank_name' },
        { label: '手续费', prop: 'fee', method: (row) => row.fee.substring(0, 5) },
        { label: '状态', prop: 'status', method: (row) => this.formatPaymentStatus(row) },
        { label: '备注', prop: 'remark' },
        { label: '更新时间', prop: 'updated_at' },
        { label: '创建时间', prop: 'created_at' }
      ],
      paymentRowsActions: [
        {
          key: 'check',
          label: '订单同步',
          vIF: (row) => row.type === 1 && row.status === 1,
          method: (row) => {
            this.$confirm('确定同步该订单，是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              paymentOrder({ id: row.id }).then((res) => {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                this.onPaymentSubmit()
              })
            })
          }
        }
      ],
      paymentApis: {
        list: {
          url: 'paymentOrder',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        }
      },
      paymentTableOptions: {},
      paymentEditForm: [],
      paymentEditConfig: {
        addTip: '注：备注',
        editTip: '注：备注'
      },

      topupStatusOpt: [
        { value: 0, label: '待确认' },
        { value: 1, label: '已确认' },
        { value: 2, label: '失败' },
        { value: 3, label: '已忽略' }
      ],
      topupSearch: {
        member_id: '',
        first_name: '',
        status: '',
        type: ''
      },
      topupAlertTip: '',
      topupColumns: [
        { label: '会员ID', prop: 'member_id', width: 120 },
        {
          label: '会员昵称',
          popover: true,
          width: 140,
          tagType: (row) => row?.member.status === 1 ? 'danger' : '',
          props: ['member.first_name'],
          options: [
            { label: '会员ID', value: ['member.member_id'] },
            { label: '用户名称', value: ['member.username'] },
            { label: '异常信息', vShow: (row) => row?.member.admin_note ? true : false, value: ['member.admin_note'] }
          ]
        },
        { label: '链接类型', prop: 'net' },
        { label: '币种', prop: 'coin' },
        { label: '费率', prop: 'exchange_rate', method: (row) => this.formatNumber(row.exchange_rate, 2) },
        {
          label: '充值数量',
          html: true,
          width: 150,
          prop: 'amount',
          method: (row) => {
            const amount = row.amount || 0
            const exchangeRate = row.exchange_rate || 1
            const convertedAmount = amount * exchangeRate
            return `
              <div class="amount-display">
                <div class="usd-amount">${this.formatNumber(amount)} USDT</div>
                <div class="cny-amount">${this.formatNumber(convertedAmount)} RMB</div>
              </div>
            `
          }
        },
        { label: '充值地址（平台地址）', prop: 'to_address' },
        { label: '状态', prop: 'status', method: (row) => { return this.topupStatusOpt.find(item => item.value === row.status)?.label || '' } },
        { label: '图片', image: true, prop: 'image' },
        { label: '类型', method: (row) => row.type === 1 ? '自动' : row.type === 2 ? '手动' : '其他' },
        { label: '更新时间', prop: 'updated_at' },
        { label: '创建时间', prop: 'created_at' }
      ],
      topupRowsActions: [
        {
          key: 'no',
          label: '驳回',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.handleTopupVerify({ id: row.id.toString(), status: 2 })
          }
        },
        {
          key: 'yes',
          label: '通过',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.handleTopupVerify({ id: row.id.toString(), status: 1 })
          }
        }
      ],
      topupApis: {
        list: {
          url: 'wallet',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        },
        add: { url: '', cover: true, coverMethod: (row, node) => { return row.year + '、' + node[0].label } },
        edit: { url: '', cover: true, coverMethod: (row, node) => { return row.year + '、' + node[0].label } },
        preview: { url: '', dataParam: 'datas', keyParam: 'cache_key' },
        import: { url: '', params: 'cache_key' },
        batchDelete: { url: '', params: 'ids' },
        delete: { url: '', params: 'ids' }
      },
      topupTableOptions: {
        add: { show: false, initData: () => { return { test: 'test' } } },
        import: { show: false, tip: '注：备注', columns: [{ label: '严控', prop: 0, required: true }] },
        export: { show: false, dataName: 'xxx.xlsx', baseApi: process.env.VUE_APP_BASE_IMG + '/', theadMap: [{ xxxx: {} }], theadProps: { xxxx: {} } },
        download: { show: false, url: '/static/template.xlsx' },
        batchDelete: { show: false }
      },
      topupEditForm: [
        {
          body: [
            {
              label: '年度',
              type: 'year',
              prop: 'year',
              clearable: false,
              rules: [{ required: true, message: '请选择年度', trigger: 'change' }]
            }
          ]
        }
      ],
      topupEditConfig: {
        addTip: '注：备注',
        editTip: '注：备注'
      }
    }
  },
  mounted() {
    this.onPaymentSubmit()
    this.onTopupSubmit()
    menucheck('admin/wallet/verifyRecharge').then(({ code }) => {
      if (code !== 0) {
        this.topupRowsActions = []
      }
    })
  },
  methods: {
    handleTabChange(val) {
      if (val === 'payment') {
        this.onPaymentSubmit()
      } else {
        this.onTopupSubmit()
      }
    },

    onPaymentResponse(data) {
      this.paymentAlertTip = `总金额：${data.total_amount}(RMB)；已处理：${data.total_success}(RMB)；失败金额：${data.total_fail}(RMB)`
    },
    onPaymentSubmit() {
      const params = { type: 0, ...this.paymentSearch }
      this.$nextTick(() => {
        if (this.$refs.paymentTable) {
          this.$refs.paymentTable.getList(params)
        }
      })
    },
    resetPaymentSearch() {
      this.paymentSearch = { member_id: '', first_name: '', order_no: '', status: '' }
      this.onPaymentSubmit()
    },
    handlePaymentAudit(row) {
      if (row.status === 2) {
        this.$prompt('请输入原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S+$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          audit({ ...row, remark: value }).then(() => {
            this.onPaymentSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          audit(row).then(() => {
            this.onPaymentSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      }
    },
    formatPaymentStatus(row) {
      const TIMEOUT_MINUTES = 10
      const STATUS_MAP = { 1: '处理中', 2: '成功', 3: '失败' }
      const diffMinutes = Math.floor((Date.now() - new Date(row.created_at)) / (1000 * 60))
      if (diffMinutes > TIMEOUT_MINUTES && row.type === 1 && row.status === 1) {
        const hours = Math.floor(diffMinutes / 60)
        return hours > 0 ? `超时${hours}小时` : `超时${diffMinutes}分钟`
      }
      return STATUS_MAP[row.status] || '待处理'
    },

    onTopupResponse(data) {
      this.topupAlertTip = `总金额：${data.total_amount}(USTD)；已处理：${data.total_success}(USTD)；失败金额：${data.total_fail}(USTD)`
    },
    onTopupSubmit() {
      const params = { ...this.topupSearch }
      this.$nextTick(() => {
        if (this.$refs.topupTable) {
          this.$refs.topupTable.getList(params)
        }
      })
    },
    resetTopupSearch() {
      this.topupSearch = { member_id: '', first_name: '', status: '', type: '' }
      this.onTopupSubmit()
    },
    handleTopupVerify(row) {
      if (row.status === 2) {
        this.$prompt('请输入原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S+$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          verifyRecharge({ ...row, remark: value }).then(() => {
            this.onTopupSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          verifyRecharge(row).then(() => {
            this.onTopupSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      }
    },
    formatNumber(num, decimals = 2) {
      if (isNaN(num)) return '0.00'
      return Number(num).toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  }
}
</script>

<style scoped>
/* 头部容器使用 flex 布局，支持换行 */
.header-container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 10px;
  padding-left: 20px;
  box-sizing: border-box;
}
.tab-group {
  margin-top: 3px; /* 稍微往下微调，使其与表单项在视觉上对齐 */
}
.search-form {
  margin-bottom: 0;
}
</style>
