<template>
  <div class="new-app-container layout-vertical">
    <YMTableSearch
      :loading="loading"
      :search-form="searchForm"
      @onValueChange="onValueChange"
      @submit="onSubmit"
    />

    <div class="tab-container">
      <el-tabs v-model="activeType" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in lotteryTypeTabs" :key="item.value" :label="item.label" :name="String(item.value)" />
      </el-tabs>
    </div>

    <YMTable
      ref="table"
      :apis="apis"
      :columns="columns"
      :custom-style="{ height: 'calc(100vh - 250px)' }"
      :index="true"
      :rows-actions="rowsActions"
      :selection="false"
      :show-summary="false"
      :table-key="1"
      :table-options="tableOptions"
    />
  </div>
</template>

<script>
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: 2 },
  { label: '澳门六合彩', value: 3 },
  { label: '极速六合彩', value: 4 },
  { label: '加拿大28', value: 5 },
  { label: '极速28', value: 6 },
  { label: '极速赛车', value: 7 },
  { label: '极速时时彩', value: 8 },
  { label: '极速飞艇', value: 9 },
  { label: 'SG时时彩', value: 10 },
  { label: 'SG飞艇', value: 11 },
  { label: '极速快3', value: 12 },
  { label: 'SG快3', value: 13 }
]

export default {
  name: 'UnifiedOrderList',
  data() {
    return {
      loading: false,
      queryData: {},
      activeType: '',
      lotteryTypeTabs: [{ label: '全部', value: '' }, ...lotteryTypeOptions],

      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: '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', width: '80' },
        {
          label: '订单号', prop: 'ordernum', width: '180', link: true, click: (row) => {
            this.$router.push({ name: 'DigitalDetail', query: { id: row.id } })
          }
        },
        { label: '期号', prop: 'issue', width: '110' },
        {
          label: '类型',
          prop: 'type',
          method: (row) => {
            const target = lotteryTypeOptions.find(item => item.value === Number(row.type))
            return target ? target.label : row.type
          }
        },
        { label: '会员ID', prop: 'member_id', width: '100' },
        { label: '会员账号', prop: 'first_name', width: 140 },
        {
          label: '投注内容',
          prop: 'number',
          html: true,
          minWidth: '180',
          method: (row) => {
            let gameStr = row.game ? `[${row.game}] - ` : ''
            let playStr = row.gameplay || ''
            let numbers = (row.items || []).map(item => item.number).filter(n => n !== undefined && n !== null && n !== '').join(',')
            let numStr = numbers ? `<br><span class="el-tag el-tag--warning el-tag--small" style="margin-left:4px;font-weight:bold;">${numbers}</span>` : ''
            return `<div style="font-size:12px;">${gameStr}${playStr}${numStr}</div>`
          }
        },
        {
          label: '赔率',
          prop: 'odds',
          html: true,
          method: (row) => row.odds ? `<span style="color:#E6A23C;font-weight:bold;">@${row.odds}</span>` : '--'
        },
        {
          label: '下注金额',
          prop: 'amount',
          method: (row) => row.amount ? `¥ ${parseFloat(row.amount).toFixed(2)}` : '--'
        },
        {
          label: '开奖结果',
          prop: 'open_code',
          width: '320',
          html: true,
          method: (row) => this.renderOpenCode(row)
        },
        {
          label: '状态',
          prop: 'lottery_status',
          html: true,
          method: (row) => {
            const statusMap = {
              0: '<span class="el-tag el-tag--warning el-tag--small">待开奖</span>',
              1: '<span class="el-tag el-tag--info el-tag--small">未中奖</span>',
              2: '<span class="el-tag el-tag--success el-tag--small">已中奖</span>',
              3: '<span class="el-tag el-tag--info el-tag--small">合局</span>',
              4: '<span class="el-tag el-tag--danger el-tag--small">已退款</span>'
            }
            return statusMap[row.lottery_status] || '--'
          }
        },
        {
          label: '盈亏',
          prop: 'profit_and_loss',
          html: true,
          method: (row) => {
            if (row.lottery_status === 0) return '--'
            const val = Number(row.profit_and_loss || 0)
            const color = val > 0 ? '#67C23A' : (val < 0 ? '#F56C6C' : '#909399')
            const sign = val > 0 ? '+' : ''
            return `<span style="color: ${color}; font-family: monospace; font-weight: bold; font-size: 14px;">${sign}${row.profit_and_loss || '0.00'}</span>`
          }
        },
        { label: '下单时间', prop: 'created_at', width: '160' },
        { label: '备注', prop: 'remark', method: (row) => row.remark || '--' }
      ],

      apis: {
        list: {
          url: 'lhcOrder/list',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        }
      },

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

      rowsActions: [
        {
          key: 'detail',
          label: '详情',
          method: (row) => {
            this.$router.push({ name: 'DigitalDetail', query: { id: row.id } })
          }
        }
      ]
    }
  },
  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: {
    handleTabClick() {
      this.onSubmit(this.queryData)
    },
    onValueChange(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
      }, {})

      if (this.activeType !== '') {
        validParams.type = this.activeType
      }

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

    renderOpenCode(row) {
      const openCodeStr = row.lottery?.open_code || row.open_code || ''
      const otherTagsStr = row.lottery?.open_code_other || row.open_code_other || ''

      if (!openCodeStr && !otherTagsStr) return '--'

      const codes = openCodeStr ? openCodeStr.split(',') : []
      let ballsHtml = ''
      const type = Number(row.type)

      if ([1, 2, 3, 4].includes(type) && codes.length > 0) {
        ballsHtml = codes.map((code, index) => {
          const isLast = index === codes.length - 1
          const plus = isLast ? '<span class="plus-sign">+</span>' : ''
          const colorClass = this.getLhcBallColorClass(code)
          return `${plus}<div class="lhc-ball ${colorClass}">${code}</div>`
        }).join('')
      }
      else if ([12, 13].includes(type) && codes.length > 0) {
        ballsHtml = codes.map((num) => {
          let dotsHtml = ''
          for(let i = 0; i < Number(num); i++) {
            dotsHtml += '<i class="dot"></i>'
          }
          const isRed = (num == 1 || num == 4) ? 'dice-red' : ''
          return `<div class="dice-item dice-${num} ${isRed}">${dotsHtml}</div>`
        }).join('')
      }
      else if (codes.length > 0) {
        ballsHtml = codes.map((num) => {
          const colorClass = this.getJisuBallColorClass(num, type)
          return `<div class="jisu-ball ${colorClass}">${num}</div>`
        }).join('')
      }

      let tagsHtml = ''
      if (otherTagsStr) {
        const tags = otherTagsStr.split(/[\s,]+/).filter(Boolean)
        tagsHtml = tags.map(tag => `<span class="other-tag">${tag}</span>`).join('')
      }

      return `
        <div class="result-wrapper">
          <div class="balls-row">${ballsHtml}</div>
          ${tagsHtml ? `<div class="tags-row">${tagsHtml}</div>` : ''}
        </div>
      `
    },

    getLhcBallColorClass(numStr) {
      const num = parseInt(numStr, 10)
      if (isNaN(num)) return 'bg-gray'
      const reds = [1, 2, 7, 8, 12, 13, 18, 19, 23, 24, 29, 30, 34, 35, 40, 45, 46]
      const blues = [3, 4, 9, 10, 14, 15, 20, 25, 26, 31, 36, 37, 41, 42, 47, 48]
      const greens = [5, 6, 11, 16, 17, 21, 22, 27, 28, 32, 33, 38, 39, 43, 44, 49]
      if (reds.includes(num)) return 'bg-red'
      if (blues.includes(num)) return 'bg-blue'
      if (greens.includes(num)) return 'bg-green'
      return 'bg-gray'
    },

    getJisuBallColorClass(numStr, typeCode) {
      if (!numStr) return ''
      const tNum = Number(typeCode)
      if ([7, 9, 11].includes(tNum)) {
        return `color-${parseInt(numStr, 10)}`
      } else if ([5, 6, 8, 10].includes(tNum)) {
        return 'wave-blue'
      }
      return 'wave-blue'
    }
  }
}
</script>

<style scoped lang="scss">
.tab-container {
  background: #ffffff;
  padding: 0 15px;
  margin: 0 15px;
  border-radius: 6px;
}
::v-deep .el-table {
  font-size: 13px;
}
::v-deep .result-wrapper {
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  justify-content: center;
  .balls-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
    gap: 4px;
  }
  .tags-row {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 4px;
  }
  .other-tag {
    font-size: 12px;
    background: #f4f4f5;
    color: #909399;
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid #e9e9eb;
  }
  .plus-sign {
    font-size: 16px;
    font-weight: bold;
    color: #909399;
    margin: 0 2px;
  }
  .lhc-ball {
    width: 26px;
    height: 26px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    font-weight: 900;
    color: #fff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.3), inset 0 -2px 2px rgba(0,0,0,0.2);
    &.bg-red { background: linear-gradient(135deg, #ff6b6b 0%, #dc2626 100%); }
    &.bg-blue { background: linear-gradient(135deg, #60a5fa 0%, #2563eb 100%); }
    &.bg-green { background: linear-gradient(135deg, #34d399 0%, #059669 100%); }
    &.bg-gray { background: linear-gradient(135deg, #9ca3af 0%, #4b5563 100%); }
  }
  .jisu-ball {
    width: 22px;
    height: 22px;
    color: #ffffff;
    font-size: 12px;
    font-family: monospace;
    font-weight: bold;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ccc;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    &.wave-blue { background: linear-gradient(135deg, #42a5f5, #1e88e5); box-shadow: 0 1px 3px rgba(66, 165, 245, 0.3); }
    &.color-1 { background: #E6DE00; text-shadow: 0 1px 1px rgba(0,0,0,0.3); }
    &.color-2 { background: #0092FF; }
    &.color-3 { background: #4D4D4D; }
    &.color-4 { background: #FF7600; }
    &.color-5 { background: #17E2E5; }
    &.color-6 { background: #5234FF; }
    &.color-7 { background: #BFBFBF; }
    &.color-8 { background: #FF2600; }
    &.color-9 { background: #780B00; }
    &.color-10 { background: #07BF00; }
  }
  .dice-item {
    width: 24px;
    height: 24px;
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: grid;
    padding: 2px;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    box-shadow: inset 0 -2px 0 rgba(0,0,0,0.05);
    box-sizing: border-box;
    .dot {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      background-color: #303133;
      justify-self: center;
      align-self: center;
    }
    &.dice-1 { .dot:nth-child(1) { grid-column: 2; grid-row: 2; width: 6px; height: 6px; } }
    &.dice-2 { .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 3; grid-row: 3; } }
    &.dice-3 { .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 2; grid-row: 2; } .dot:nth-child(3) { grid-column: 3; grid-row: 3; } }
    &.dice-4 {
      .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 3; grid-row: 1; }
      .dot:nth-child(3) { grid-column: 1; grid-row: 3; } .dot:nth-child(4) { grid-column: 3; grid-row: 3; }
    }
    &.dice-5 {
      .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 3; grid-row: 1; }
      .dot:nth-child(3) { grid-column: 2; grid-row: 2; }
      .dot:nth-child(4) { grid-column: 1; grid-row: 3; } .dot:nth-child(5) { grid-column: 3; grid-row: 3; }
    }
    &.dice-6 {
      .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 1; grid-row: 2; }
      .dot:nth-child(3) { grid-column: 1; grid-row: 3; } .dot:nth-child(4) { grid-column: 3; grid-row: 1; }
      .dot:nth-child(5) { grid-column: 3; grid-row: 2; } .dot:nth-child(6) { grid-column: 3; grid-row: 3; }
    }
    &.dice-red .dot { background-color: #f56c6c; }
  }
}
</style>
