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

    <div class="toolbar">
      <div class="segmented-control">
        <div
          v-for="item in stateOptions"
          :key="item.value"
          :class="{ active: activeState === item.value }"
          class="segmented-item"
          @click="handleSegmentChange(item.value)"
        >
          {{ item.label }}
        </div>
      </div>
      <div class="batch-actions">
        <el-button size="small" type="warning" @click="handleBatchState">批量修改状态</el-button>
        <el-button size="small" type="success" @click="handleBatchOnline">批量上架</el-button>
        <el-button size="small" type="danger" @click="handleBatchOffline">批量下架</el-button>
        </div>
    </div>

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

    <Dialog ref="dialog" :dialogActions="{ title: '修改比赛状态', width: '400px' }" @confirm="submitStateEdit">
      <template slot="content">
        <el-form label-width="100px">
          <el-form-item :rules="[{ required: true, message: '请选择比赛状态' }]" label="比赛状态">
            <el-select v-model="form.state" style="width: 100%;">
              <el-option
                v-for="item in validStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>

<script>
import Dialog from '@/components/Dialog/index.vue'
import { setSportStatus } from '@/api/data'

// 比赛状态枚举
const stateOptions = [
  { value: 0, label: '未开始' },
  { value: 1, label: '进行中' },
  { value: 2, label: '已完成' },
  { value: 3, label: '延期' },
  { value: 4, label: '取消' },
  { value: '', label: '全部' }
]

// 上下架状态枚举
const statusOptions = [
  { value: 1, label: '上架' },
  { value: 0, label: '下架' },
  { value: '', label: '全部' }
]

// 锁定状态枚举
const lockedOptions = [
  { value: 1, label: '已加锁' },
  { value: 0, label: '未加锁' },
  { value: '', label: '全部' }
]

export default {
  name: 'SportList',
  components: {
    Dialog
  },
  data() {
    return {
      loading: false,
      queryData: {},

      stateOptions, // 引入供模板分段控制器使用
      activeState: 1, // 当前选中的比赛状态，默认全部
      customLoading: true,

      // 修改状态的表单
      form: {
        id: [], // 改为数组格式以支持批量
        state: null
      },

      // 供弹窗使用的有效状态（去除"全部"选项）
      validStateOptions: stateOptions.filter(item => item.value !== ''),

      // 搜索配置 (已去除比赛状态)
      searchForm: [
        { label: '赛事ID', type: 'input', prop: 'data_id', clearable: true, placeholder: '请输入' },
        { label: '球队名称', type: 'input', prop: 'team_name', clearable: true, placeholder: '请输入' },
        { label: '赛事名称', type: 'input', prop: 'league', clearable: true, placeholder: '请输入' },
        // { label: '主队名称', type: 'input', prop: 'home_team', clearable: true, placeholder: '请输入主队' },
        // { label: '客队名称', type: 'input', prop: 'guest_team', clearable: true, placeholder: '请输入客队' },
        {
          label: '赔率玩法',
          type: 'select',
          prop: 'odds',
          clearable: true,
          options: [{ value: 0, label: '无' }, { value: 1, label: '有' }]
        },
        { label: '上架状态', type: 'select', prop: 'status', clearable: true, options: statusOptions },
        { label: '锁定状态', type: 'select', prop: 'is_locked', clearable: true, options: lockedOptions },
        {
          label: '比赛时间',
          type: 'daterange',
          prop: 'timeRange',
          clearable: true,
          valueFormat: 'yyyy-MM-dd'
        }
      ],

      // 表格列配置
      columns: [
        { label: '赛事ID', prop: 'data_id', width: '80' },
        {
          label: '联赛名称', prop: 'league', width: '150',
          link: true,
          click: (row) => {
            this.$router.push({
              name: 'EventDetail',
              query: { id: row.id }
            })
          }
        },
        {
          label: '对阵信息 (主队 VS 客队)',
          prop: 'match_info',
          width: '380',
          html: true,
          method: (row) => {
            const homeLogo = row.home_team_logo || ''
            const guestLogo = row.guest_team_logo || ''
            return `
              <div style="display: flex; align-items: center; justify-content: center; width: 100%;">
                <div style="flex: 1; text-align: right; display: flex; align-items: center; justify-content: flex-end;">
                  <span style="margin-right: 8px;">${row.home_team}</span>
                  <img src="${homeLogo}" style="width: 24px; height: 24px; object-fit: contain;" onerror="this.style.display='none'">
                </div>
                <div style="padding: 0 10px; color: #909399; font-weight: bold; font-size: 12px;">VS</div>
                <div style="flex: 1; text-align: left; display: flex; align-items: center;">
                  <img src="${guestLogo}" style="width: 24px; height: 24px; object-fit: contain;" onerror="this.style.display='none'">
                  <span style="margin-left: 8px;">${row.guest_team}</span>
                </div>
              </div>
            `
          }
        },

        {
          label: '赔率玩法',
          prop: 'odds',
          html: true,
          method: (row) => {
            return row.odds && row.odds.length > 0
              ? `<span class="el-tag el-tag--success el-tag--small el-tag--light">有</span>`
              : `<span class="el-tag el-tag--info el-tag--small el-tag--light">无</span>`
          }
        },

        {
          label: '比赛状态',
          prop: 'state',
          width: '100',
          html: true,
          method: (row) => {
            const map = {
              0: { text: '未开始', color: '#909399' },
              1: { text: '进行中', color: '#409EFF' },
              2: { text: '已完成', color: '#67C23A' },
              3: { text: '延期', color: '#E6A23C' },
              4: { text: '取消', color: '#F56C6C' }
            }
            const status = map[row.state] || { text: '未知', color: '#303133' }
            return `<span style="color: ${status.color}; font-weight: bold;">${status.text}</span>`
          }
        },
        {
          label: '上架状态',
          prop: 'status',
          width: '90',
          html: true,
          method: (row) => {
            return row.status === 1
              ? `<span class="el-tag el-tag--success el-tag--small el-tag--light">已上架</span>`
              : `<span class="el-tag el-tag--info el-tag--small el-tag--light">已下架</span>`
          }
        },
        {
          label: '加锁状态',
          prop: 'is_locked',
          width: '90',
          html: true,
          method: (row) => {
            return row.is_locked === 1
              ? `<span style="color: #F56C6C;"><i class="el-icon-lock"></i> 已加锁</span>`
              : `<span style="color: #909399;"><i class="el-icon-unlock"></i> 未加锁</span>`
          }
        },
        {
          label: '进行时长',
          prop: 'fixture_status',
          width: '100',
          html: true,
          method: (row) => {
            let secondsText = ''
            if (row.fixture_status) {
              secondsText = row.fixture_status.elapsed
            }

            if (secondsText) {
              return `<span style="color: #E6A23C; font-weight: bold;"><i class="el-icon-timer"></i> ${secondsText}</span>`
            }
            return '--'
          }
        },

        {
          label: '直播中进行时长',
          prop: 'odd_fixture_status',
          width: '100',
          html: true,
          method: (row) => {
            const status = JSON.parse(row.odd_fixture_status)
            let secondsText = ''
            if (status) {
              secondsText = status.seconds
            } else {
              secondsText = ''
            }
            if (secondsText) {
              return `<span style="color: #E6A23C; font-weight: bold;"><i class="el-icon-timer"></i> ${secondsText}</span>`
            }
            return '--'
          }
        },

        {
          label: '比分 (半场/全场)',
          prop: 'score',
          minWidth: '120',
          html: true,
          method: (row) => {
            const half = row.half_score || '-'
            const full = row.score || '-'
            return `<span style="color: #409EFF; font-weight: bold;">${half} / ${full}</span>`
          }
        },

        { label: '比赛时间', prop: 'game_time', minWidth: '160' }
      ],

      // 分开编辑：独立的操作按钮
      rowsActions: [
        {
          key: 'viewDetail',
          label: '查看详情',
          html: true,
          method: (row) => {
            this.$router.push({
              name: 'EventDetail',
              query: { id: row.id }
            })
          }
        },
        {
          key: 'viewInfo',
          label: '对比赛事信息',
          html: true,
          method: (row) => {
            this.$router.push({
              name: 'EventInformationIndex',
              query: { data_id: row.data_id }
            })
          }
        },
        {
          key: 'changeState',
          label: '修改状态',
          html: true,
          method: (row) => {
            this.form = {
              id: [row.id],
              state: row.state
            }
            this.$refs.dialog.open()
          }
        },
        {
          key: 'toggleRec',
          vIF: (row) => row.is_rec === 0,
          label: '置顶',
          method: (row) => {
            this.quickEditAPI(row, { is_rec: 1 }, '置顶', 'is_rec')
          }
        },
        {
          key: 'toggleRec1',
          vIF: (row) => row.is_rec === 1,
          label: '取消置顶',
          method: (row) => {
            this.quickEditAPI(row, { is_rec: 0 }, '取消置顶', 'is_rec')
          }
        },
        {
          key: 'toggleStatus',
          vIF: (row) => row.status === 1,
          label: '下架',
          method: (row) => {
            const targetStatus = row.status === 1 ? 0 : 1
            const actionName = targetStatus === 1 ? '上架' : '下架'
            this.quickEditAPI(row, { status: targetStatus }, actionName, 'status')
          }
        },
        {
          key: 'toggleStatus1',
          vIF: (row) => row.status === 0,
          label: '上架',
          method: (row) => {
            const targetStatus = row.status === 1 ? 0 : 1
            const actionName = targetStatus === 1 ? '上架' : '下架'
            this.quickEditAPI(row, { status: targetStatus }, actionName, 'status')
          }
        }
      ],

      // API 配置
      apis: {
        list: {
          url: 'sport/list',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        }
      },

      tableOptions: {
        add: { show: false },
        edit: { show: false },
        delete: { show: false }
      }
    }
  },
  mounted() {
    this.onSubmit()
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    onValueChange(val) {
    },

    // 分段控制器切换
    handleSegmentChange(val) {
      this.activeState = val
      this.onSubmit(this.queryData)
    },

    // 列表查询
    onSubmit(params = {}) {
      const searchParams = { ...params }
      // 注入分段控制器选择的比赛状态
      searchParams.state = this.activeState

      if (searchParams.timeRange && searchParams.timeRange.length === 2) {
        searchParams.start_time = searchParams.timeRange[0]
        searchParams.end_time = searchParams.timeRange[1]
      } else {
        searchParams.start_time = undefined
        searchParams.end_time = undefined
      }
      delete searchParams.timeRange

      const validParams = Object.keys(searchParams).reduce((acc, key) => {
        if (searchParams[key] !== '' && searchParams[key] !== null && searchParams[key] !== undefined) {
          acc[key] = searchParams[key]
        }
        return acc
      }, {})

      this.queryData = validParams

      if (this.$refs.table) {
        this.$refs.table.getList(this.queryData)
      }
    },

    // 弹窗提交：修改比赛状态 (单行或批量)
    submitStateEdit() {
      if (this.form.state === null) {
        return this.$message.warning('请选择比赛状态')
      }
      this.loading = true
      // form.id 已统一为数组
      setSportStatus({ id: this.form.id, state: this.form.state }).then(() => {
        this.$message.success('比赛状态修改成功')
        this.$refs.dialog.close()
        this.onSubmit(this.queryData)
      }).catch(() => {
        this.$message.error('比赛状态修改失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 快捷编辑统一下发接口
    quickEditAPI(row, updatePayload, actionName, filed) {
      let confirmText = `确认要对该赛事执行【${actionName}】操作吗？`
      if (actionName === '下架') {
        confirmText += '（注意：该操作会将款退回）'
      }
      this.$confirm(confirmText, '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        // 根据要求：只传id和filed所需的字段
        const params = {
          id: [row.id],
          ...updatePayload
        }

        setSportStatus(params).then(() => {
          this.$message.success(`${actionName}成功`)
          this.onSubmit(this.queryData)
        }).catch(() => {
          this.$message.error(`${actionName}失败`)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },

    // ---------------- 批量操作方法 ----------------
    getSelectionIds() {
      return this.$refs.table?.selectionList || []
    },
    handledGoRrror() {
      this.$router.push({ name: 'EventErrorList' })
    },
    handleBatchState() {
      const ids = this.getSelectionIds()
      if (!ids.length) return this.$message.warning('请先选择数据')
      this.form = { id: ids, state: null }
      this.$refs.dialog.open()
    },
    handleBatchOnline() {
      const ids = this.getSelectionIds()
      if (!ids.length) return this.$message.warning('请先选择数据')
      this.batchRequest(ids, { status: 1 }, '批量上架')
    },
    handleBatchOffline() {
      const ids = this.getSelectionIds()
      if (!ids.length) return this.$message.warning('请先选择数据')
      this.batchRequest(ids, { status: 0 }, '批量下架')
    },
    handleBatchLock() {
      const ids = this.getSelectionIds()
      if (!ids.length) return this.$message.warning('请先选择数据')
      this.batchRequest(ids, { is_locked: 1 }, '批量加锁')
    },
    handleBatchUnlock() {
      const ids = this.getSelectionIds()
      if (!ids.length) return this.$message.warning('请先选择数据')
      this.batchRequest(ids, { is_locked: 0 }, '批量解锁')
    },
    batchRequest(ids, payload, actionName) {
      let confirmText = `确认要执行【${actionName}】操作吗？`
      if (actionName === '批量下架') {
        confirmText += '（注意：该操作会将款退回）'
      }
      this.$confirm(confirmText, '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        setSportStatus({ id: ids, ...payload }).then(() => {
          this.$message.success(`${actionName}成功`)
          this.onSubmit(this.queryData)
        }).catch(() => {
          this.$message.error(`${actionName}失败`)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-table {
  font-size: 13px;
}

::v-deep .el-table__row td {
  padding: 8px 0;
}

/* 优化后的工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  box-sizing: border-box;
  padding: 10px 20px;
  width: calc(100% - 30px);
  margin-left: 15px;
  border-radius: 8px;
}

.segmented-control {
  display: inline-flex;
  background-color: #f0f2f5;
  border-radius: 4px;
  padding: 3px;
}

.segmented-item {
  padding: 6px 16px;
  cursor: pointer;
  border-radius: 3px;
  font-size: 13px;
  color: #606266;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.segmented-item:hover {
  color: #409EFF;
}

.segmented-item.active {
  background-color: #ffffff;
  color: #409EFF;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  font-weight: bold;
}

.batch-actions {
  display: flex;
  gap: 10px;
}
</style>
