<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="rmb">提现订单（RMB）</el-radio-button>
        <el-radio-button label="usdt">提现订单（USDT）</el-radio-button>
      </el-radio-group>

      <!-- 提现订单（RMB）搜索栏 -->
      <el-form v-show="activeTab === 'rmb'" :inline="true" :model="rmbSearch" class="search-form">
        <el-form-item label="会员ID">
          <el-input v-model="rmbSearch.member_id" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="会员昵称">
          <el-input v-model="rmbSearch.first_name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="rmbSearch.status" placeholder="请选择" clearable>
            <el-option v-for="item in rmbStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onRmbSubmit">搜索</el-button>
          <el-button @click="resetRmbSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 提现订单（USDT）搜索栏 -->
      <el-form v-show="activeTab === 'usdt'" :inline="true" :model="usdtSearch" class="search-form">
        <el-form-item label="会员ID">
          <el-input v-model="usdtSearch.member_id" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="会员昵称">
          <el-input v-model="usdtSearch.first_name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="usdtSearch.status" placeholder="请选择" clearable>
            <el-option v-for="item in usdtStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onUsdtSubmit">搜索</el-button>
          <el-button @click="resetUsdtSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 提现订单（RMB）板块 -->
    <div v-show="activeTab === 'rmb'">
      <YMTable
        ref="rmbTable"
        :table-key="1"
        :index="true"
        :selection="true"
        :table-options="rmbTableOptions"
        :edit-form="rmbEditForm"
        :edit-config="rmbEditConfig"
        :columns="rmbColumns"
        :actions-width="120"
        :rows-actions="rmbRowsActions"
        :show-summary="false"
        :apis="rmbApis"
        :alertTip="rmbAlertTip"
        :custom-style="{ height: 'calc(100vh - 150px)' }"
        @onResponse="onRmbResponse"
      />
    </div>

    <!-- 提现订单（USDT）板块 -->
    <div v-show="activeTab === 'usdt'">
      <YMTable
        ref="usdtTable"
        :table-key="2"
        :index="false"
        :selection="true"
        :table-options="usdtTableOptions"
        :edit-form="usdtEditForm"
        :edit-config="usdtEditConfig"
        :columns="usdtColumns"
        :rows-actions="usdtRowsActions"
        :show-summary="false"
        :apis="usdtApis"
        :custom-style="{ height: 'calc(100vh - 150px)' }"
        :alertTip="usdtAlertTip"
        @onResponse="onUsdtResponse"
      />
    </div>

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

<script>
import Dialog from '@/components/Dialog/index.vue'
import { menucheck, withdrawsetNote, withdrawStatus, usdtWithdrawSetIsLocked, audit, withdrawssetRmbNote, rmbPaymentOrderSetIsLocked } from '@/api/data'

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

      // RMB 列表相关数据
      rmbStatusOpt: [
        { value: 0, label: '待处理' },
        { value: 1, label: '处理中' },
        { value: 2, label: '成功' },
        { value: 3, label: '失败' },
        { value: 4, label: '待用户提交凭证' },
        { value: 5, label: '待人工审核' },
        { value: 6, label: '已撤回' }
      ],
      rmbSearch: {
        member_id: '',
        first_name: '',
        status: ''
      },
      rmbAlertTip: '',
      rmbColumns: [
        { label: '会员ID', prop: 'member_id', width: 120 },
        {
          label: '会员昵称',
          popover: true,
          width: 140,
          props: ['first_name'],
          tagType: (row) => row?.status === 1 ? 'danger' : '',
          options: [
            { label: '会员ID', value: ['member_id'] },
            { label: '用户名称', value: ['first_name'] },
            { label: '异常信息', vShow: (row) => row?.admin_note ? true : false, value: ['admin_note'] }
          ]
        },
        { label: '订单号', prop: 'order_no' },
        { label: '提现金额', prop: 'amount', method: (row) => Number(row.amount)?.toFixed(2) },
        {
          label: '银行卡',
          width: '180px',
          html: true,
          method: (row) => `${row?.account}（${row?.bank_name}）<br/>账户：${row?.card_no} `
        },
        { label: '手续费', prop: 'fee', method: (row) => Number(row.fee)?.toFixed(2) },
        { label: '是否加锁', prop: 'is_locked', method: (row) => row.is_locked === 1 ? '是' : '否' },
        { label: '状态', method: (row) => { return this.rmbStatusOpt.filter(item => item.value === row.status)[0]?.label } },
        { label: '原因', prop: 'remark' },
        { label: '备注', prop: 'admin_note' },
        { label: '申请时间', prop: 'created_at' }
      ],
      rmbRowsActions: [
        {
          key: 'lock',
          label: '上锁',
          vIF: (row) => row.status === 0 && row.is_locked === 0,
          method: (row) => {
            this.$confirm(`确定要上锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              rmbPaymentOrderSetIsLocked({ ids: [row.id], is_locked: 1 }).then(() => {
                this.onRmbSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'unlock',
          label: '解锁',
          vIF: (row) => row.status === 0 && row.is_locked === 1,
          method: (row) => {
            this.$confirm(`确定要解锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              rmbPaymentOrderSetIsLocked({ ids: [row.id], is_locked: 0 }).then(() => {
                this.onRmbSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'no',
          label: '驳回',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.setRmbStatus({ ids: [row.id], status: 3 })
          }
        },
        {
          key: 'yes',
          label: '通过',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.setRmbStatus({ ids: [row.id], status: 1 })
          }
        },
        {
          key: 'note',
          label: '备注',
          method: (row) => {
            this.$prompt('请输入备注', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^\S+$/,
              inputErrorMessage: '请输入备注'
            }).then(({ value }) => {
              withdrawssetRmbNote({ id: row.id, admin_note: value }).then(() => {
                this.onRmbSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            })
          }
        }
      ],
      rmbApis: {
        list: { url: 'withdraw/rmb', dataParam: 'data.data', resultParam: 'data', init: false },
        pass: { url: 'paymentOrder/audit', method: 'post', params: ['ids'], status: ['status'], statusValue: 1 },
        reject: { url: 'paymentOrder/audit', method: 'post', params: ['ids'], status: ['status'], statusValue: 3, remark: ['remark'] }
      },
      rmbTableOptions: {
        reject: { show: true },
        pass: { show: false }
      },
      rmbEditForm: [],
      rmbEditConfig: {},

      // USDT 列表相关数据
      usdtStatusOpt: [
        { value: 0, label: '申请中' },
        { value: 1, label: '成功' },
        { value: 2, label: '失败' },
        { value: 3, label: '已撤回' }
      ],
      usdtSearch: {
        member_id: '',
        first_name: '',
        status: ''
      },
      usdtAlertTip: '',
      usdtColumns: [
        { 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: 'amount', method: (row) => Number(row.amount)?.toFixed(2) + ' USDT' },
        { label: '手续费', prop: 'service_charge', method: (row) => Number(row.service_charge)?.toFixed(2) + ' USDT' },
        { label: '费率', width: 50, prop: 'exchange_rate', method: (row) => this.formatNumber(row.exchange_rate, 2) },
        {
          label: '到账金额',
          prop: 'to_account',
          html: true,
          method: (row) => {
            return `
              <div class="amount-display">
                <div class="usd-amount">${this.formatNumber(row.to_account_usdt)} USDT</div>
              </div>
            `
          }
        },
        {
          label: '扣除金额',
          html: true,
          method: (row) => {
            const amount = row.amount || 0
            const exchangeRate = row.exchange_rate || 1
            const convertedAmount = amount * exchangeRate
            return `
              <div class="amount-display">
                <div class="cny-amount">${this.formatNumber(convertedAmount)} RMB</div>
              </div>
            `
          }
        },
        { label: '提现后余额', prop: 'after_balance', method: (row) => Number(row.after_balance)?.toFixed(2) + ' RMB' },
        { label: '钱包地址', prop: 'address', width: 130 },
        { label: '是否加锁', prop: 'is_locked', method: (row) => row.is_locked === 1 ? '是' : '否' },
        { label: '状态', method: (row) => { return this.usdtStatusOpt.filter(item => item.value === row.status)[0]?.label } },
        { label: '原因', prop: 'remark' },
        { label: '申请时间', prop: 'created_at' },
        { label: '备注', prop: 'admin_note' }
      ],
      usdtRowsActions: [
        {
          key: 'lock',
          label: '上锁',
          vIF: (row) => row.status === 0 && row.is_locked === 0,
          method: (row) => {
            this.$confirm(`确定要上锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              usdtWithdrawSetIsLocked({ ids: [row.id], is_locked: 1 }).then(() => {
                this.onUsdtSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'unlock',
          label: '解锁',
          vIF: (row) => row.status === 0 && row.is_locked === 1,
          method: (row) => {
            this.$confirm(`确定要解锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              usdtWithdrawSetIsLocked({ ids: [row.id], is_locked: 0 }).then(() => {
                this.onUsdtSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'note',
          label: '备注',
          method: (row) => {
            this.$prompt('请输入备注', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^\S+$/,
              inputErrorMessage: '请输入备注'
            }).then(({ value }) => {
              withdrawsetNote({ id: row.id, admin_note: value }).then(() => {
                this.onUsdtSubmit()
                this.$message({ type: 'success', message: '操作成功' })
              })
            })
          }
        },
        {
          key: 'no',
          label: '驳回',
          vIF: (row) => row.status === 0,
          method: (row) => {
            this.setUsdtStatus({ ids: [row.id], status: 2 })
          }
        },
        {
          key: 'yes',
          label: '通过',
          vIF: (row) => row.status === 0,
          method: (row) => {
            this.setUsdtStatus({ ids: [row.id], status: 1 })
          }
        }
      ],
      usdtApis: {
        list: { url: 'withdraw', dataParam: 'data.data', resultParam: 'data', init: false },
        pass: { url: 'withdraw/setStatus', method: 'post', params: ['ids'], status: ['status'], statusValue: 1 },
        reject: { url: 'withdraw/setStatus', method: 'post', params: ['ids'], status: ['status'], statusValue: 2, remark: ['remark'] }
      },
      usdtTableOptions: {
        reject: { show: true },
        pass: { show: false }
      },
      usdtEditForm: [],
      usdtEditConfig: {}
    }
  },
  mounted() {
    this.onRmbSubmit()
    this.onUsdtSubmit()
    menucheck('admin/withdraw/setStatus').then(({ code }) => {
      if (code !== 0) {
        this.usdtRowsActions = []
      }
    })
  },
  methods: {
    // Tab栏点击跳转方法
    handleTabChange(val) {
      if (val === 'rmb') {
        this.onRmbSubmit()
      } else {
        this.onUsdtSubmit()
      }
    },

    // 公用格式化方法
    formatNumber(num, decimals = 2) {
      if (isNaN(num)) return '0.00'
      return Number(num).toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // RMB 相关方法
    onRmbResponse(data) {
      this.rmbAlertTip = `总金额：${data.total_amount}(RMB)；已处理：${data.total_success}(RMB)；失败金额：${data.total_fail}(RMB)`
    },
    onRmbSubmit() {
      const params = { ...this.rmbSearch }
      this.$nextTick(() => {
        if (this.$refs.rmbTable) {
          this.$refs.rmbTable.getList(params)
        }
      })
    },
    resetRmbSearch() {
      this.rmbSearch = { member_id: '', first_name: '', status: '' }
      this.onRmbSubmit()
    },
    setRmbStatus(row) {
      if (row.status === 3) {
        this.$prompt('请输入原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S+$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          audit({ ...row, remark: value }).then(() => {
            this.onRmbSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          audit(row).then(() => {
            this.onRmbSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      }
    },

    // USDT 相关方法
    onUsdtResponse(data) {
      this.usdtAlertTip = `总金额：${data.total_amount}(USTD)；已处理：${data.total_success}(USTD)；失败金额：${data.total_fail}(USTD)`
    },
    onUsdtSubmit() {
      const params = { ...this.usdtSearch }
      this.$nextTick(() => {
        if (this.$refs.usdtTable) {
          this.$refs.usdtTable.getList(params)
        }
      })
    },
    resetUsdtSearch() {
      this.usdtSearch = { member_id: '', first_name: '', status: '' }
      this.onUsdtSubmit()
    },
    setUsdtStatus(row) {
      if (row.status === 2) {
        this.$prompt('请输入原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S+$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          withdrawStatus({ ...row, remark: value }).then(() => {
            this.onUsdtSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          withdrawStatus(row).then(() => {
            this.onUsdtSubmit()
            this.$message({ type: 'success', message: '操作成功' })
          })
        })
      }
    }
  }
}
</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>
