<template>
  <div class="new-app-container layout-vertical">
    <YMTableSearch
      :loading="loading"
      :search-form="searchForm"
      @onValueChange="onValueChange"
      @submit="onSubmit"
    />
    <YMTable
      ref="table"
      :apis="apis"
      :columns="columns"
      :custom-style="{ height: 'calc(100vh - 200px)' }"
      :index="true"
      :rows-actions="rowsActions"
      :selection="false"
      :show-summary="false"
      :table-key="1"
      :table-options="tableOptions"
    >
      <template #game_info="{ row }">
        <div v-if="row" style="line-height: 1.5; font-size: 12px;height: 70px;display: flex;flex-direction: column;justify-content: center;">
          <div>{{ row.detail ? row.detail.game_time : '--' }}</div>
          <div style="font-weight: bold; color: #303133;">
            {{ row.home_team || '--' }} vs {{ row.guest_team || '--' }}
          </div>
          <div style="opacity: 0;height: 0px;">1</div>
          <div v-if="(row.detail && row.detail.fixture_status)">
            赛况: <span v-if="(row.detail && row.detail.fixture_status)">{{ (row.detail && row.detail.fixture_status) ? row.detail.fixture_status.long : '--' }}</span>
            <span v-if="(row.detail && row.detail.fixture_status) ">
              ({{ (row.detail && row.detail.fixture_status) ? row.detail.fixture_status.seconds : '--' }})
            </span>
          </div>
          <div>
            <span v-if="row.detail && row.detail.half_score">半场: {{ row.detail ? row.detail.half_score : '--' }}</span>
            <span v-if="row.detail && row.detail.score && row.detail.half_score"> / </span>
            <span v-if="row.detail && row.detail.score">
              全场: {{ row.detail ? row.detail.score : '--' }}
            </span>
          </div>
        </div>
      </template>

      <template #odd_name="{ row }">
        <div v-if="row" style="line-height: 1.5; font-size: 12px;height: 70px;">
          <div style="font-weight: bold; color: #303133;">{{ row.odd_name || '--' }}</div>
          <div>玩法: {{ row.odd_value || '--' }}</div>
           <div style="opacity: 0;height: 0px;">1</div>
          <div>盘口: {{ row.handicap || '--' }}</div>
          <div>赔率: {{ row.odd || '--' }}</div>
        </div>
      </template>
    </YMTable>

    <el-dialog :visible.sync="debitDialogVisible" title="扣款操作" width="450px" @close="resetDebitForm">
      <el-form ref="debitForm" :model="debitForm" :rules="debitRules" label-width="100px">
        <el-form-item label="扣款金额" prop="amount">
          <el-input-number
            v-model="debitForm.amount"
            :min="0.01"
            :precision="2"
            placeholder="请输入扣款金额"
            style="width: 100%;"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="debitForm.remark"
            :rows="3"
            placeholder="请输入备注信息（选填）"
            type="textarea"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="debitDialogVisible = false">取 消</el-button>
    <el-button :loading="loading" type="primary" @click="submitDebitOrder">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog :visible.sync="rechargeDialogVisible" title="充值操作" width="450px" @close="resetRechargeForm">
      <el-form ref="rechargeForm" :model="rechargeForm" :rules="rechargeRules" label-width="100px">
        <el-form-item label="充值金额" prop="amount">
          <el-input-number
            v-model="rechargeForm.amount"
            :min="0.01"
            :precision="2"
            placeholder="请输入充值金额"
            style="width: 100%;"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="rechargeForm.remark"
            :rows="3"
            placeholder="请输入备注信息（选填）"
            type="textarea"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="rechargeDialogVisible = false">取 消</el-button>
    <el-button :loading="loading" type="primary" @click="submitRechargeOrder">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { orderRefund, walletOrderDebiting, walletOrderTopUp } from '@/api/data'

export default {
  data() {
    return {
      loading: false,
      queryData: {},

      // 搜索表单配置
      searchForm: [
        { label: 'ID', type: 'input', prop: 'id', clearable: true },
        { label: '订单号', prop: 'order_id', type: 'input' },
        // { label: '用户ID', prop: 'user_id', type: 'input' },
        {
          label: '会员昵称',
          type: 'input',
          prop: 'first_name',
          clearable: true
        },
        { label: '会员ID', prop: 'member_id', type: 'input', clearable: true },
        { label: '赛事ID', prop: 'issue', type: 'input' },
        {
          label: '支付状态',
          prop: 'pay_status',
          type: 'select',
          options: [
            { label: '待付款', value: 0 },
            { label: '已支付', value: 1 }
          ]
        },
        {
          label: '订单状态',
          prop: 'status',
          type: 'select',
          options: [
            { label: '已取消', value: -1 },
            { label: '下注中', value: 0 },
            { label: '下注成功', value: 1 } // 注：根据你下面的字段映射，这里1对应“已支付”或“已成功”
          ]
        },
        {
          label: '中奖状态',
          prop: 'is_win',
          type: 'select',
          options: [
            { label: '未中奖', value: 0 },
            { label: '已中奖', value: 1 },
            { label: '和局', value: 2 }
          ]
        },
        {
          label: '结算状态',
          prop: 'settlement_status',
          type: 'select',
          options: [
            { label: '未结算', value: 0 },
            { label: '已结算', value: 1 },
            { label: '已取消', value: 2 }
          ]
        },
        {
          label: '退款状态',
          prop: 'return_status',
          type: 'select',
          options: [
            { label: '未退款', value: 0 },
            { label: '申请中', value: 1 },
            { label: '已同意', value: 2 },
            { label: '已驳回', value: 3 }
          ]
        }
      ],

      // API 接口配置
      apis: {
        list: {
          url: 'order/list', // 请将此处替换为实际的接口地址
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        }
      },

      // 表格整体配置
      tableOptions: {
        add: {
          show: false
        }
      },

      // 表格列配置
      columns: [
        {
          label: 'ID',
          prop: 'id',
        },
        {
          label: '订单号',
          prop: 'order_id',
          width: 190,
          link: true,
          click: (row) => {
            this.$router.push({
              name: 'orderDetail',
              query: { order_id: row.order_id }
            })
          }
        },
        // { label: '用户ID', prop: 'user_id', width: 100 },
         {
          label: '会员ID',
          prop: 'member_id',
          width: 120
        },
          {
          label: '会员昵称',
          prop: 'first_name',
          width: 150
        },
        // {
        //   label: '账户类型',
        //   prop: 'is_faker',
        //   width: 90,
        //   html: true,
        //   method: (row) => {
        //     const isFaker = row.is_faker === 1
        //     const color = isFaker ? '#F56C6C' : '#67C23A'
        //     const text = isFaker ? '虚拟账户' : '真实账户'
        //     return `<span style="color: ${color}">${text}</span>`
        //   }
        // },
        { label: '赛事ID', prop: 'issue', width: 120 },
        {
          label: '赛事信息',
          prop: 'game_info',
          width: 220,
          slot: true,
          className: 'custom-game-col' // 给该列表格单元格增加自定义类名
        },
        {
          label: '滚球',
          prop: 'is_roll',
          width: 80,
          html: true,
          method: (row) => {
            const isRoll = row.is_roll === 1
            const color = isRoll ? '#E6A23C' : '#909399'
            const text = isRoll ? '滚球' : '非滚球'
            return `<span style="color: ${color}">${text}</span>`
          }
        },
        {
          label: '玩法',
          prop: 'odd_name',
          width: 180,
          slot: true // 开启插槽
        },
           {
          label: '订单状态',
          prop: 'status',
          width: 90,
          html: true,
          method: (row) => {
            const map = {
              0: { text: '下注中', color: '#909399' },
              1: { text: '下注成功', color: '#67C23A' },
              2: { text: '已退款', color: '#E6A23C' },
              '-1': { text: '已取消', color: '#F56C6C' }
            }
            const match = map[row.status]
            return match ? `<span style="color: ${match.color}">${match.text}</span>` : '--'
          }
        },
        // 这里移除了原来的 '赔率'(odd)、'赔率玩法'(odd_value)、'盘口'(handicp) 三列
        { label: '下注失败的原因', prop: 'failure' },
        { label: '下注金额(RMB)', prop: 'amount', width: 100 },
        // { label: 'RMB汇率', prop: 'cny_rate', width: 100 },
        { label: '派奖金额(RMB)', prop: 'win_amount', width: 100 },
        { label: '盈亏金额(RMB)', prop: 'profit_and_loss', width: 100 },
        {
          label: '中奖状态',
          prop: 'is_win',
          width: 90,
          html: true,
          method: (row) => {
            const map = {
              0: { text: '未中奖', color: '#909399' },
              1: { text: '已中奖', color: '#67C23A' },
              2: { text: '和局', color: '#E6A23C' }
            }
            const match = map[row.is_win]
            return match ? `<span style="color: ${match.color}">${match.text}</span>` : '--'
          }
        },

        {
          label: '结算状态',
          prop: 'settlement_status',
          width: 90,
          html: true,
          method: (row) => {
            const map = {
              0: { text: '未结算', color: '#909399' },
              1: { text: '已结算', color: '#67C23A' },
              2: { text: '已取消', color: '#F56C6C' }
            }
            const match = map[row.settlement_status]
            return match ? `<span style="color: ${match.color}">${match.text}</span>` : '--'
          }
        },
        {
          label: '支付状态',
          prop: 'pay_status',
          width: 90,
          html: true,
          method: (row) => {
            const isPay = row.pay_status === 1
            const color = isPay ? '#67C23A' : '#909399'
            const text = isPay ? '已支付' : '待付款'
            return `<span style="color: ${color}">${text}</span>`
          }
        },
        { label: '支付时间', prop: 'pay_time', width: 160 },
        {
          label: '退款状态',
          prop: 'return_status',
          width: 100,
          html: true,
          method: (row) => {
            const map = {
              0: { text: '未退款', color: '#909399' },
              1: { text: '退款申请中', color: '#E6A23C' },
              2: { text: '退款已同意', color: '#67C23A' },
              3: { text: '退款已驳回', color: '#F56C6C' }
            }
            const match = map[row.return_status]
            return match ? `<span style="color: ${match.color}">${match.text}</span>` : '--'
          }
        },
        { label: '备注', prop: 'remark' },
        { label: '退款申请时间', prop: 'return_apply_time', width: 160 },
        { label: '退款处理时间', prop: 'return_operation_time', width: 160 },
        { label: '创建时间', prop: 'create_time', width: 160 }
      ],

      // 表格右侧操作列
      rowsActions: [
        {
          key: 'refund',
          label: '退款',
          // 判断是否禁用按钮
          disabled: (row) => {
            // 条件: 1.支付状态已支付(1) 2.结算状态未结算(0) 3.订单状态已支付(1) 4.退款状态未退款(0)
            const canRefund =
              row.pay_status === 1 &&
              row.settlement_status === 0 &&
              row.status === 1 &&
              row.return_status === 0

            // disabled 为 true 时禁用按钮，所以这里取反
            return !canRefund
          },
          method: (row) => {
            this.handleRefund(row)
          }
        },

        {
          key: 'topUp',
          label: '充值',
          // 判断是否禁用按钮
          disabled: (row) => {
            // 条件: 1.支付状态已支付(1) 2.结算状态未结算(0) 3.订单状态已支付(1) 4.退款状态未退款(0)
            const canRefund =
              row.pay_status === 1

            // disabled 为 true 时禁用按钮，所以这里取反
            return !canRefund
          },
          method: (row) => {
            this.handleWalletOrderRecharging(row)
          }
        },

        {
          key: 'deduction',
          label: '扣款',
          // 判断是否禁用按钮
          disabled: (row) => {
            // 条件: 1.支付状态已支付(1) 2.结算状态未结算(0) 3.订单状态已支付(1) 4.退款状态未退款(0)
            const canRefund =
              row.pay_status === 1

            // disabled 为 true 时禁用按钮，所以这里取反
            return !canRefund
          },
          method: (row) => {
            this.handleWalletOrderDebiting(row)
          }
        }

      ],

      // 扣款弹窗相关的状态
      debitDialogVisible: false,
      debitForm: {
        amount: undefined,
        remark: '',
        order_id: '',
        order_type: 'sport' // 默认传 sport
      },
      debitRules: {
        amount: [
          { required: true, message: '请输入扣款金额', trigger: 'blur' }
        ]
      },

      // 充值弹窗相关的状态
      rechargeDialogVisible: false,
      rechargeForm: {
        amount: undefined,
        remark: '',
        order_id: '',
        order_type: 'sport' // 默认传 sport
      },
      rechargeRules: {
        amount: [
          { required: true, message: '请输入充值金额', trigger: 'blur' }
        ]
      }

    }
  },
  mounted() {
    this.onSubmit()
  },
  methods: {
    onValueChange(val) {
      // 可以在此处处理额外的数据联动逻辑
    },
    onSubmit(params = {}) {
      this.queryData = params
      this.$refs.table.getList(params)
    },
    // 处理退款逻辑
    handleRefund(row) {
      this.$confirm(`确定要对订单号 ${row.order_id} 进行退款操作吗？`, '退款确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          this.loading = true
          // 调用接口，传入参数 id
          const res = await orderRefund({ id: [row.id] })

          // 这里的判断条件 (res.code === 200) 请根据你实际的后端返回格式进行调整
          if (res.code === 0) {
            this.$message.success('退款成功')
            // 刷新当前表格数据
            this.onSubmit(this.queryData)
          } else {
            this.$message.error(res.msg || '退款失败')
          }
        } catch (error) {
          console.error(error)
          this.$message.error('退款请求异常')
        } finally {
          this.loading = false
        }
      }).catch(() => {
        // 取消弹窗
      })
    },
    // 1. 点击列表中的【扣款】按钮触发，用于打开弹窗
    handleWalletOrderDebiting(row) {
      // 初始化表单数据
      this.debitForm = {
        amount: undefined,
        remark: '',
        // 注意：根据你的后端需求，这里取 row.id 还是 row.order_id
        order_id: row.id,
        order_type: 'sport'
      }
      this.debitDialogVisible = true
    },

    // 2. 弹窗内的【确定】按钮触发，用于提交接口
    submitDebitOrder() {
      this.$refs.debitForm.validate(async(valid) => {
        if (valid) {
          try {
            this.loading = true
            // 提交接口，传入拼装好的表单数据
            const res = await walletOrderDebiting(this.debitForm)

            if (res.code === 0 || res.success) {
              this.$message.success('扣款成功')
              this.debitDialogVisible = false // 关闭弹窗
              // 刷新当前表格数据
              this.onSubmit(this.queryData)
            } else {
              this.$message.error(res.msg || '扣款失败')
            }
          } catch (error) {
            console.error(error)
            this.$message.error('扣款请求异常')
          } finally {
            this.loading = false
          }
        } else {
          return false
        }
      })
    },

    // 3. 弹窗关闭时重置表单校验状态
    resetDebitForm() {
      if (this.$refs.debitForm) {
        this.$refs.debitForm.resetFields()
      }
    },


    // 1. 点击列表中的【充值】按钮触发，用于打开弹窗
    handleWalletOrderRecharging(row) {
      // 初始化表单数据
      this.rechargeForm = {
        amount: undefined,
        remark: '',
        // 注意确认这里是取 row.id 还是 row.order_id
        order_id: row.id,
        order_type: 'sport'
      }
      this.rechargeDialogVisible = true
    },

    // 2. 弹窗内的【确定】按钮触发，用于提交充值接口
    submitRechargeOrder() {
      this.$refs.rechargeForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            // 提交接口，注意这里替换为你真实的充值接口方法名
            const res = await walletOrderTopUp(this.rechargeForm)

            if (res.code === 0 || res.success) {
              this.$message.success('充值成功')
              this.rechargeDialogVisible = false // 关闭弹窗
              // 刷新当前表格数据
              this.onSubmit(this.queryData)
            } else {
              this.$message.error(res.msg || '充值失败')
            }
          } catch (error) {
            console.error(error)
            this.$message.error('充值请求异常')
          } finally {
            this.loading = false
          }
        } else {
          return false
        }
      })
    },

    // 3. 弹窗关闭时重置表单校验状态
    resetRechargeForm() {
      if (this.$refs.rechargeForm) {
        this.$refs.rechargeForm.resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 强制覆盖 element-ui 表格单元格默认的截断样式 */
::v-deep .custom-game-col .cell {
  white-space: normal !important;
  overflow: visible !important;
  text-overflow: clip !important;
}
</style>
