<template>
  <div class="crowd-task-list">
    <el-card>
      <template #header>
        <div class="search-section">
        <div class="search-row">
          <el-form :model="searchForm" label-width="90px" inline>
            <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-item label="类型:">
              <el-select v-model="searchForm.type" placeholder="全部" clearable style="width: 160px">
                <el-option label="规则组圈选" value="rule_group" />
                <el-option label="指定客户号" value="name_list" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="action-row">
          <el-dropdown trigger="click" @command="handleCreateByType">
            <el-button type="primary">
              <el-icon><Plus /></el-icon>新增任务<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="rule_group">规则组圈选</el-dropdown-item>
                <el-dropdown-item command="name_list">指定客户号</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        </div>
      </template>

      <el-table
        :data="pagedData"
        stripe border
        style="width: 100%"
      >
        <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="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'rule_group' ? '' : 'warning'" size="small">
              {{ typeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row)" size="small">
              {{ statusLabel(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="人数" width="80" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 'name_list'">{{ (scope.row.members || []).length }}</span>
            <span v-else class="muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="审核人" width="100">
          <template #default="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 #default="scope">
            <span v-if="scope.row.type === 'rule_group'">
              {{ scope.row.startDate }} / {{ scope.row.endDate }}
            </span>
            <span v-else class="muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="170" />
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <!-- 规则组圈选 -->
            <template v-if="scope.row.type === 'rule_group'">
              <el-button
                v-if="canDoTask(scope.row, 'edit')"
                type="primary" circle size="small" title="编辑"
                @click.stop="handleEditTask(scope.row)"
              ><el-icon><Edit /></el-icon></el-button>
              <el-button
                v-if="canDoTask(scope.row, 'run')"
                type="success" circle size="small" title="运行"
                @click.stop="handleRun(scope.row)"
              ><el-icon><VideoPlay /></el-icon></el-button>
              <el-button
                v-if="canDoTask(scope.row, 'publish')"
                type="success" circle size="small" title="上线"
                @click.stop="handlePublish(scope.row)"
              ><el-icon><Upload /></el-icon></el-button>
              <el-button
                v-if="canDoTask(scope.row, 'stop')"
                type="warning" circle size="small" title="停止"
                @click.stop="handleStop(scope.row)"
              ><el-icon><Close /></el-icon></el-button>
              <el-button
                v-if="canDoTask(scope.row, 'detail')"
                type="info" circle size="small" title="详情"
                @click.stop="handleDetail(scope.row)"
              ><el-icon><View /></el-icon></el-button>
              <el-button
                type="primary" plain circle size="small" title="复制"
                @click.stop="handleCopy(scope.row)"
              ><el-icon><DocumentCopy /></el-icon></el-button>
            </template>
            <!-- 指定客户号 -->
            <template v-else>
              <el-button
                v-if="scope.row.status === 'draft'"
                type="success" circle size="small" title="启用"
                @click.stop="handleActivate(scope.row)"
              ><el-icon><Check /></el-icon></el-button>
              <el-button
                v-if="scope.row.status !== 'stopped'"
                type="primary" circle size="small" title="编辑"
                @click.stop="handleEditNameList(scope.row)"
              ><el-icon><Edit /></el-icon></el-button>
              <el-button
                v-if="scope.row.status !== 'stopped'"
                type="primary" plain circle size="small" title="人员调整"
                @click.stop="openAdjust(scope.row)"
              ><el-icon><User /></el-icon></el-button>
              <el-button
                v-if="scope.row.status !== 'stopped'"
                type="primary" plain circle size="small" title="上传调整文件"
                @click.stop="openUpload(scope.row)"
              ><el-icon><Upload /></el-icon></el-button>
              <el-button
                v-if="scope.row.status !== 'stopped'"
                type="warning" circle size="small" title="停止"
                @click.stop="handleStopNameList(scope.row)"
              ><el-icon><Close /></el-icon></el-button>
              <span v-if="scope.row.status === 'stopped'" class="muted">无可执行操作</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

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

    <adjust-member-dialog
      v-model="adjustVisible"
      :default-list-id="adjustListId"
    />
    <upload-adjust-dialog
      v-model="uploadVisible"
      :default-list-id="adjustListId"
    />
  </div>
</template>

<script>
import crowdTaskStore from '@/store/crowdTaskStore'
import crowdNameListStore from '@/store/crowdNameListStore'
import AdjustMemberDialog from '@/components/crowdNameList/AdjustMemberDialog.vue'
import UploadAdjustDialog from '@/components/crowdNameList/UploadAdjustDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CrowdTaskList',
  components: { AdjustMemberDialog, UploadAdjustDialog },
  data() {
    return {
      searchForm: { id: '', name: '', type: '' },
      page: { current: 1, size: 10 },
      adjustVisible: false,
      adjustListId: '',
      uploadVisible: false
    }
  },
  computed: {
    filteredData() {
      const { id, name, type } = this.searchForm
      const tasks = type === 'name_list'
        ? []
        : crowdTaskStore.query({ id, name }).map((r) => ({ ...r, type: 'rule_group' }))
      const lists = type === 'rule_group'
        ? []
        : crowdNameListStore.query({ id, name }).map((r) => ({ ...r, type: 'name_list' }))
      const merged = [...tasks, ...lists]
      merged.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
      return merged
    },
    pagedData() {
      const start = (this.page.current - 1) * this.page.size
      return this.filteredData.slice(start, start + this.page.size)
    }
  },
  methods: {
    typeLabel(t) {
      return t === 'rule_group' ? '规则组圈选' : '指定客户号'
    },
    statusLabel(row) {
      if (row.type === 'name_list') {
        return { draft: '新建', active: '已生效', stopped: '已停止' }[row.status] || row.status
      }
      return { draft: '新建', verifying: '校验', online: '上线', stopped: '已停止' }[row.status] || row.status
    },
    statusTagType(row) {
      if (row.type === 'name_list') {
        return { draft: 'info', active: 'success', stopped: 'danger' }[row.status] || ''
      }
      return { draft: 'info', verifying: 'warning', online: 'success', stopped: 'danger' }[row.status] || ''
    },
    canDoTask(row, action) {
      return crowdTaskStore.allowedActions(row).includes(action)
    },
    handleSearch() {
      this.page.current = 1
    },
    handleCreateByType(type) {
      if (type === 'rule_group') {
        this.$router.push('/customization/hsbc/crowd-tasks/add')
      } else {
        this.$router.push('/customization/hsbc/crowd-name-lists/add')
      }
    },
    handleCopy(row) {
      ElMessageBox.confirm(
        `确定要复制任务「${row.name}」吗？将生成一条状态为「新建」的副本。`,
        '复制任务',
        { confirmButtonText: '复制', cancelButtonText: '取消', type: 'info' }
      ).then(() => {
        const copy = crowdTaskStore.copyFrom(row.id)
        if (copy) ElMessage.success(`已复制为 ${copy.id}`)
      }).catch(() => {})
    },
    openAdjust(row) {
      this.adjustListId = row.id
      this.adjustVisible = true
    },
    openUpload(row) {
      this.adjustListId = row.id
      this.uploadVisible = true
    },
    handleEditTask(row) {
      this.$router.push(`/customization/hsbc/crowd-tasks/edit/${row.id}`)
    },
    handleEditNameList(row) {
      this.$router.push(`/customization/hsbc/crowd-name-lists/edit/${row.id}`)
    },
    handleDetail(row) {
      this.$router.push(`/customization/hsbc/crowd-tasks/view/${row.id}`)
    },
    handleRun(row) {
      ElMessageBox.confirm(
        '点击运行后将向行内提交规则，等待返回 count/sample 结果。',
        '运行任务',
        { confirmButtonText: '运行', cancelButtonText: '取消', type: 'info' }
      ).then(() => {
        crowdTaskStore.run(row.id)
        ElMessage.success('已触发运行，请稍候查看详情')
      }).catch(() => {})
    },
    handlePublish(row) {
      ElMessageBox.confirm(
        '点击上线后将运行 fullist，审核通过后任务进入上线状态。',
        '上线任务',
        { confirmButtonText: '上线', cancelButtonText: '取消', type: 'warning' }
      ).then(() => {
        crowdTaskStore.publish(row.id)
        ElMessage.success('已提交审核并触发上线运行')
      }).catch(() => {})
    },
    handleStop(row) {
      ElMessageBox.confirm(
        `停止后任务不可恢复，仅可查看详情。确认停止「${row.name}」？`,
        '停止任务',
        { confirmButtonText: '停止', cancelButtonText: '取消', type: 'warning' }
      ).then(() => {
        crowdTaskStore.stop(row.id)
        ElMessage.success('已停止')
      }).catch(() => {})
    },
    handleActivate(row) {
      ElMessageBox.confirm(`启用名单「${row.name}」需通过审核后生效，确认提交？`, '启用', {
        confirmButtonText: '提交', cancelButtonText: '取消', type: 'info'
      }).then(() => {
        crowdNameListStore.activate(row.id)
        ElMessage.success('已生效（demo 默认通过审核）')
      }).catch(() => {})
    },
    handleStopNameList(row) {
      ElMessageBox.confirm(`停止后名单不可再调整，确认停止「${row.name}」？`, '停止', {
        confirmButtonText: '停止', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        crowdNameListStore.stop(row.id)
        ElMessage.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; }

.muted { color: #c0c4cc; font-size: 12px; }

.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>
