<template>
  <div class="crowd-task-list">
    <el-card>
      <div slot="header" class="search-section">
        <div class="search-row">
          <el-form :model="searchForm" label-width="90px" inline>
            <el-form-item label="所属银行:" required>
              <el-select v-model="searchForm.bank" placeholder="请选择" style="width: 160px" disabled>
                <el-option label="汇丰银行" value="hsbc" />
              </el-select>
            </el-form-item>
            <el-form-item label="客群编号:">
              <el-input v-model="searchForm.id" placeholder="请输入" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item label="客群名称:">
              <el-input v-model="searchForm.name" placeholder="请输入" clearable style="width: 180px" />
            </el-form-item>
          </el-form>
        </div>
        <div class="action-row">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新增任务</el-button>
          <el-button type="primary" icon="el-icon-plus" plain @click="handleCopy">复制任务</el-button>
        </div>
      </div>

      <el-table
        :data="pagedData"
        stripe border highlight-current-row
        style="width: 100%"
        @current-change="onRowSelect"
      >
        <el-table-column prop="id" label="客群编号" width="160" />
        <el-table-column prop="name" label="客群名称" min-width="160" show-overflow-tooltip />
        <el-table-column label="客群类型" width="110" align="center">
          <template slot-scope="scope">{{ typeLabel(scope.row.type) }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.status)" size="small">
              {{ statusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="审核人" width="100">
          <template slot-scope="scope">{{ scope.row.reviewer || '-' }}</template>
        </el-table-column>
        <el-table-column prop="createdAt" label="任务创建时间" width="170" />
        <el-table-column label="任务开始/结束日期" width="190" align="center">
          <template slot-scope="scope">
            {{ scope.row.startDate }} / {{ scope.row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="170" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="canDo(scope.row, 'edit')"
              type="primary" circle size="mini" icon="el-icon-edit" title="编辑"
              @click.stop="handleEdit(scope.row)"
            />
            <el-button
              v-if="canDo(scope.row, 'run')"
              type="success" circle size="mini" icon="el-icon-video-play" title="运行"
              @click.stop="handleRun(scope.row)"
            />
            <el-button
              v-if="canDo(scope.row, 'publish')"
              type="success" circle size="mini" icon="el-icon-upload2" title="上线"
              @click.stop="handlePublish(scope.row)"
            />
            <el-button
              v-if="canDo(scope.row, 'stop')"
              type="warning" circle size="mini" icon="el-icon-close" title="停止"
              @click.stop="handleStop(scope.row)"
            />
            <el-button
              v-if="canDo(scope.row, 'detail')"
              type="info" circle size="mini" icon="el-icon-view" title="详情"
              @click.stop="handleDetail(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-section">
        <span class="total">共 {{ filteredData.length }} 条</span>
        <el-pagination
          layout="prev, pager, next, sizes, jumper"
          :current-page.sync="page.current"
          :page-size.sync="page.size"
          :page-sizes="[10, 20, 50]"
          :total="filteredData.length"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import crowdTaskStore from '@/store/crowdTaskStore'

export default {
  name: 'CrowdTaskList',
  data() {
    return {
      searchForm: { bank: 'hsbc', id: '', name: '' },
      page: { current: 1, size: 10 },
      selectedRow: null
    }
  },
  computed: {
    filteredData() {
      return crowdTaskStore.query({ id: this.searchForm.id, name: this.searchForm.name })
    },
    pagedData() {
      const start = (this.page.current - 1) * this.page.size
      return this.filteredData.slice(start, start + this.page.size)
    }
  },
  methods: {
    typeLabel(t) {
      return { display: '展示规则', reward: '奖励规则' }[t] || t
    },
    statusLabel(s) {
      return { draft: '新建', verifying: '校验', online: '上线', stopped: '已停止' }[s] || s
    },
    statusTagType(s) {
      return { draft: 'info', verifying: 'warning', online: 'success', stopped: 'danger' }[s] || ''
    },
    canDo(row, action) {
      return crowdTaskStore.allowedActions(row).includes(action)
    },
    onRowSelect(row) {
      this.selectedRow = row
    },
    handleSearch() {
      this.page.current = 1
    },
    handleCreate() {
      this.$router.push('/customization/hsbc/crowd-tasks/add')
    },
    handleCopy() {
      if (!this.selectedRow) {
        this.$message.warning('请先在列表中选择一条任务再点击复制')
        return
      }
      this.$confirm(
        `确定要复制任务「${this.selectedRow.name}」吗？将生成一条状态为「新建」的副本。`,
        '复制任务',
        { confirmButtonText: '复制', cancelButtonText: '取消', type: 'info' }
      ).then(() => {
        const copy = crowdTaskStore.copyFrom(this.selectedRow.id)
        if (copy) {
          this.$message.success(`已复制为 ${copy.id}`)
          this.selectedRow = null
        }
      }).catch(() => {})
    },
    handleEdit(row) {
      this.$router.push(`/customization/hsbc/crowd-tasks/edit/${row.id}`)
    },
    handleDetail(row) {
      this.$router.push(`/customization/hsbc/crowd-tasks/view/${row.id}`)
    },
    handleRun(row) {
      this.$confirm(
        '点击运行后将向行内提交规则，等待返回 count/sample 结果。',
        '运行任务',
        { confirmButtonText: '运行', cancelButtonText: '取消', type: 'info' }
      ).then(() => {
        crowdTaskStore.run(row.id)
        this.$message.success('已触发运行，请稍候查看详情')
      }).catch(() => {})
    },
    handlePublish(row) {
      this.$confirm(
        '点击上线后将运行 fullist，审核通过后任务进入上线状态。',
        '上线任务',
        { confirmButtonText: '上线', cancelButtonText: '取消', type: 'warning' }
      ).then(() => {
        crowdTaskStore.publish(row.id)
        this.$message.success('已提交审核并触发上线运行')
      }).catch(() => {})
    },
    handleStop(row) {
      this.$confirm(
        `停止后任务不可恢复，仅可查看详情。确认停止「${row.name}」？`,
        '停止任务',
        { confirmButtonText: '停止', cancelButtonText: '取消', type: 'warning' }
      ).then(() => {
        crowdTaskStore.stop(row.id)
        this.$message.success('已停止')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.crowd-task-list { padding: 0; }

.search-section { display: flex; flex-direction: column; }
.search-row .el-form { display: flex; flex-wrap: wrap; gap: 8px 0; }
.search-row .el-form-item { margin-right: 8px; margin-bottom: 8px; }

.action-row { margin-top: 8px; display: flex; gap: 8px; }

.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}
.pagination-section .total { color: #606266; font-size: 13px; }
</style>
