<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"
    />

    <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'
// 开奖状态枚举 (可根据实际业务修改)
const lotteryStatusOptions = [
  { value: 0, label: '待开奖' },
  { value: 1, label: '未中奖' },
  { value: 2, label: '已中奖' },
  { value: 3, label: '合局' },
  { value: 4, label: '购物车' },
  { value: '', label: '全部' }
]

const lotteryTypeOptions = [
  { label: '新澳门六合彩', value: 1 },
  { label: '澳门六合彩', value: 3 },
  { label: '极速六合彩', value: 4 },
  { label: '香港六合彩', value: 2 },
  { value: '', label: '全部' }
]

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

      // 搜索配置
      searchForm: [
        { label: 'ID', type: 'input', prop: 'id', clearable: true },
        { label: '期号', type: 'input', prop: 'issue', clearable: true },
        { label: '订单号', type: 'input', prop: 'ordernum', clearable: true },
        { label: '会员ID', type: 'input', prop: 'member_id', clearable: true },
        {
          label: '会员昵称',
          type: 'input',
          prop: 'first_name',
          clearable: true
        },
        { label: '类型', type: 'select', prop: 'type', clearable: true, options: lotteryTypeOptions },
        { label: '游戏', type: 'input', prop: 'game', clearable: true },
        { label: '玩法', type: 'input', prop: 'gameplay', clearable: true },
        { label: '下注号码', type: 'input', prop: 'number', clearable: true },
        { label: '状态', type: 'select', prop: 'lottery_status', clearable: true, options: lotteryStatusOptions }
      ],

      // 表格列配置
      columns: [
        {
          label: 'ID',
          prop: 'id'
        },
        {
          label: '订单号', prop: 'ordernum', width: '180', link: true, click: (row) => {
            this.$router.push({
              name: 'DigitalDetail',
              query: { id: row.id }
            })
          }
        },
        { label: '期号', prop: 'issue', width: '100' },
        {
          label: '类型',
          prop: 'type',
          method: (row) => {
            if (row.type === 1) return '新澳门六合彩'
            if (row.type === 3) return '澳门六合彩'
            if (row.type === 2) return '香港六合彩'
            if (row.type === 4) return '极速六合彩'
            return row.type
          }
        },
        { label: '下单时间', prop: 'created_at', width: '160' },
        { label: '会员ID', prop: 'member_id', width: '120' },
        {
          label: '会员昵称',
          prop: 'first_name',
          width: 150
        },
        { label: '游戏', prop: 'game' },
        { label: '玩法', prop: 'gameplay' },
        {
          label: '下注号码',
          prop: 'number',
          html: true,
          method: (row) => {
            // 给号码加个样式标签，视觉效果更好
            return `<span class="el-tag el-tag--info el-tag--small">${row.number || '--'}</span>`
          }
        },
        // { label: '赔率', prop: 'odds' },
        {
          label: '下注金额(RMB)',
          prop: 'amount',
          method: (row) => row.amount ? `¥ ${row.amount}` : '--'
        },
        {
          label: '状态',
          prop: 'lottery_status',
          html: true,
          method: (row) => {
            const statusMap = {
              0: '<span style="color: #E6A23C">待开奖</span>',
              1: '<span style="color: #909399">未中奖</span>',
              2: '<span style="color: #67C23A; font-weight: bold;">已中奖</span>',
              3: '<span style="color: #F56C6C">合局</span>',
              4: '<span style="color: #F56C6C">购物车</span>'
            }
            return statusMap[row.lottery_status] || '--'
          }
        },
        {
          label: '开奖信息',
          prop: 'open_code',
          width: '300',
          html: true,
          method: (row) => {
            if (row.lottery && row.lottery.open_code) {
              const codes = row.lottery.open_code.split(',')
              return codes.map((code, index) => {
                const isLast = index === codes.length - 1
                const bgColor = isLast ? '#ED6F6E' : '#409EFF'
                return `<span style="display: inline-block; width: 24px; height: 24px; line-height: 24px; text-align: center; border-radius: 50%; background-color: ${bgColor}; color: #fff; margin-right: 4px; font-size: 12px;">${code}</span>`
              }).join('')
            }
            return '--'
          }
        },
        {
          label: '开奖时间',
          prop: 'open_time',
          width: '160',
          method: (row) => {
            return row.lottery && row.lottery.open_time ? row.lottery.open_time : '--'
          }
        },
        {
          label: '中奖金额(RMB)',
          prop: 'win_amount',
          method: (row) => row.win_amount !== null ? `¥ ${row.win_amount}` : '--'
        },
        {
          label: '盈亏(RMB)',
          prop: 'profit_and_loss',
          html: true,
          method: (row) => {
            if (row.profit_and_loss === null) return '--'
            const val = Number(row.profit_and_loss)
            const color = val > 0 ? '#67C23A' : (val < 0 ? '#F56C6C' : '#606266')
            return `<span style="color: ${color}; font-weight: bold;">${val > 0 ? '+' : ''}${val}</span>`
          }
        },
        { label: '备注', prop: 'remark' }
      ],

      // API 配置
      apis: {
        list: {
          // 注意：此处填入你后台实际的 订单列表接口路由地址 (例如 'lhc/order/list')
          // YMTable 默认会带上 page 和 limit 参数
          url: 'lhcOrder/list',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        }
      },

      tableOptions: {
        add: { show: false },
        edit: { show: false },
        delete: { show: false }
      },

      rowsActions: [
        {
          key: 'topUp',
          label: '充值',
          method: (row) => {
            this.handleWalletOrderRecharging(row)
          }
        },

        {
          key: 'deduction',
          label: '扣款',
          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' }
        ]
      }
    }
  },
  created() {
    // 如果从其他页面带了期号参数跳转过来，可以进行拦截处理
    if (this.$route.query.issue_no) {
      this.$set(this.queryData, 'issue', this.$route.query.issue_no)
      // 同步更新搜索栏的回显
      const issueItem = this.searchForm.find(item => item.prop === 'issue')
      if (issueItem) issueItem.defaultValue = this.$route.query.issue_no
    }
  },
  mounted() {
    // 初始化获取列表
    this.onSubmit(this.queryData)
  },
  methods: {
    // 监听搜索栏变化 (如需做联动可在此处理)
    onValueChange(val) {
      console.log('搜索条件变化:', val)
    },

    // 提交搜索
    onSubmit(params = {}) {
      // 过滤掉为空的参数
      const validParams = Object.keys(params).reduce((acc, key) => {
        if (params[key] !== '' && params[key] !== null && params[key] !== undefined) {
          acc[key] = params[key]
        }
        return acc
      }, {})

      this.queryData = validParams
      this.$refs.table.getList(this.queryData)
    },

    // 1. 点击列表中的【扣款】按钮触发，用于打开弹窗
    handleWalletOrderDebiting(row) {
      // 初始化表单数据
      this.debitForm = {
        amount: undefined,
        remark: '',
        // 注意：根据你的后端需求，这里取 row.id 还是 row.order_id
        order_id: row.id,
        order_type: 'lhc'
      }
      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: 'lhc'
      }
      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 scoped>
/* 此处可以按需增加针对列表的自定义样式 */
::v-deep .el-table {
  font-size: 13px;
}
</style>
