<template>
  <module-page-shell title="进度跟踪">
    <div class="project-progress-page">
      <section class="panel query-list-panel">
        <div class="panel__header">
          <h3>进度跟踪</h3>
        </div>

        <div class="project-filter-bar">
          <div class="project-filter-bar__field project-filter-bar__field--project">
            <el-select v-model="queryForm.projectName" filterable placeholder="请选择项目">
              <el-option
                v-for="item in projectOptions"
                :key="item.projectId"
                :label="item.projectName"
                :value="item.projectName"
              />
            </el-select>
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--date">
            <el-date-picker
              v-model="queryForm.submittedAt"
              class="project-date-picker"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="年 / 月 / 日"
            />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-select v-model="queryForm.assessor" clearable placeholder="评估师：全部">
              <el-option label="评估师：全部" value="" />
              <el-option
                v-for="item in assessorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-select v-model="queryForm.taskName" clearable placeholder="评估任务：全部">
              <el-option label="评估任务：全部" value="" />
              <el-option
                v-for="item in taskOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-select v-model="queryForm.submissionStatus" clearable placeholder="提交情况：全部">
              <el-option label="提交情况：全部" value="" />
              <el-option label="待提交" value="待提交" />
              <el-option label="已提交" value="已提交" />
            </el-select>
          </div>
          <div class="project-filter-bar__actions">
            <el-button type="primary" class="project-filter-bar__button" @click="applyFilters">查询</el-button>
            <el-button class="project-filter-bar__button" @click="resetFilters">重置</el-button>
          </div>
        </div>

        <el-table v-loading="loading" :data="filteredRows" class="progress-table">
          <el-table-column label="项目名称" prop="projectName" min-width="260" />
          <el-table-column label="评估任务" prop="taskName" min-width="220" />
          <el-table-column label="评估师" min-width="160">
            <template slot-scope="scope">
              {{ scope.row.assignedAssessor || scope.row.currentAssessor || '待分配' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="140">
            <template slot-scope="scope">
              <span :class="['badge', scope.row.status === '已完成' ? 'badge--success' : scope.row.status === '进行中' ? 'badge--primary' : 'badge--muted']">
                {{ scope.row.status }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="评分" min-width="120">
            <template slot-scope="scope">
              {{ formatScore(scope.row.score) }}
            </template>
          </el-table-column>
          <el-table-column label="提交情况" min-width="140">
            <template slot-scope="scope">
              <span :class="['badge', scope.row.submissionStatus === '已提交' ? 'badge--success' : 'badge--warning']">
                {{ scope.row.submissionStatus }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" min-width="160">
            <template slot-scope="scope">
              {{ scope.row.submittedAt || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="120" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" :disabled="scope.row.submissionStatus === '已提交'" @click="handleRemind(scope.row)">催办</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-actions">
          <el-button type="primary" @click="simulateReceiveResult">模拟接收1条结果</el-button>
        </div>
      </section>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import { listProject } from '@/api/risk/project'
import {
  formatScore,
  getProjectTasks,
  nowString,
  readTaskStore,
  saveProjectTasks
} from '@/views/project/shared/workbench'

export default {
  name: 'ProjectProgressTracking',
  components: {
    ModulePageShell
  },
  data() {
    return {
      loading: false,
      projectOptions: [],
      taskStore: {},
      queryForm: {
        projectName: '',
        submittedAt: '',
        assessor: '',
        taskName: '',
        submissionStatus: ''
      },
      appliedFilters: {
        projectName: '',
        submittedAt: '',
        assessor: '',
        taskName: '',
        submissionStatus: ''
      }
    }
  },
  computed: {
    currentTasks() {
      return getProjectTasks(this.taskStore, this.appliedFilters.projectName || this.queryForm.projectName).map(item => ({
        ...item,
        projectName: this.appliedFilters.projectName || this.queryForm.projectName
      }))
    },
    assessorOptions() {
      const pool = new Set()
      this.currentTasks.forEach(item => {
        if (item.assignedAssessor) {
          pool.add(item.assignedAssessor)
        }
      })
      return Array.from(pool).map(item => ({ label: item, value: item }))
    },
    taskOptions() {
      const pool = new Set()
      this.currentTasks.forEach(item => {
        if (item.taskName) {
          pool.add(item.taskName)
        }
      })
      return Array.from(pool).map(item => ({ label: item, value: item }))
    },
    filteredRows() {
      return this.currentTasks.filter(item => {
        const hitDate = !this.appliedFilters.submittedAt || (item.submittedAt || '').slice(0, 10) === this.appliedFilters.submittedAt
        const hitAssessor = !this.appliedFilters.assessor || item.assignedAssessor === this.appliedFilters.assessor
        const hitTask = !this.appliedFilters.taskName || item.taskName === this.appliedFilters.taskName
        const hitSubmission = !this.appliedFilters.submissionStatus || item.submissionStatus === this.appliedFilters.submissionStatus
        return hitDate && hitAssessor && hitTask && hitSubmission
      })
    }
  },
  created() {
    this.refreshData()
  },
  activated() {
    this.refreshData()
  },
  methods: {
    formatScore,
    resolvePreferredProjectName(currentProjectName = '') {
      const routeProjectName = `${this.$route.query.projectName || ''}`.trim()
      const names = this.projectOptions.map(item => item.projectName)
      if (routeProjectName && names.includes(routeProjectName)) {
        return routeProjectName
      }
      if (currentProjectName && names.includes(currentProjectName)) {
        return currentProjectName
      }
      return this.projectOptions[0] ? this.projectOptions[0].projectName : ''
    },
    async refreshData() {
      this.loading = true
      try {
        const response = await listProject({ pageNum: 1, pageSize: 1000 })
        this.projectOptions = (response.rows || []).map(item => ({
          projectId: item.projectId,
          projectName: item.projectName || ''
        }))
        this.taskStore = readTaskStore()
        this.queryForm.projectName = this.resolvePreferredProjectName(this.queryForm.projectName)
        this.applyFilters()
      } finally {
        this.loading = false
      }
    },
    applyFilters() {
      this.appliedFilters = { ...this.queryForm }
    },
    resetFilters() {
      this.queryForm = {
        projectName: this.projectOptions[0] ? this.projectOptions[0].projectName : '',
        submittedAt: '',
        assessor: '',
        taskName: '',
        submissionStatus: ''
      }
      this.applyFilters()
    },
    handleRemind(row) {
      this.$message.success(`已提醒 ${row.assignedAssessor || row.currentAssessor || '评估师'} 尽快提交 ${row.taskName}`)
    },
    buildSimulatedScore(row, index) {
      const base = 82 + (index % 6) * 3
      if ((row.taskName || '').includes('法务')) {
        return base + 2
      }
      if ((row.taskName || '').includes('财务')) {
        return base + 4
      }
      return base
    },
    simulateReceiveResult() {
      const projectName = this.appliedFilters.projectName || this.queryForm.projectName
      if (!projectName) {
        this.$message.warning('请先选择项目')
        return
      }
      const rows = getProjectTasks(this.taskStore, projectName)
      const targetIndex = rows.findIndex(item => item.isSaved && item.submissionStatus !== '已提交')
      if (targetIndex === -1) {
        this.$message.warning('当前没有可接收的评估结果')
        return
      }
      const nextRows = rows.map((item, index) => {
        if (index !== targetIndex) {
          return item
        }
        return {
          ...item,
          status: '已完成',
          submissionStatus: '已提交',
          submittedAt: nowString(),
          score: this.buildSimulatedScore(item, index)
        }
      })
      this.taskStore = saveProjectTasks(this.taskStore, projectName, nextRows)
      this.applyFilters()
      this.$message.success('已模拟接收 1 条评估结果')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/project-filter-bar.scss";
@import "~@/styles/query-list-panel.scss";

.project-progress-page {
  display: flex;
  flex-direction: column;
}

.project-progress-page .project-filter-bar__field--project {
  flex: 0 1 280px;
  max-width: 320px;
  min-width: 220px;
}

.panel {
  border: 1px solid #e4e8ef;
  border-radius: 8px;
  background: #fff;
  padding: 14px 16px 16px;
}

.panel__header {
  margin-bottom: 12px;
}

.panel__header h3 {
  margin: 0;
  font-size: 16px;
  color: #2f3542;
}

.panel__header p {
  margin: 8px 0 0;
  color: #98a2b3;
  font-size: 13px;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-table {
  margin-bottom: 12px;
}

.badge {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  font-size: 12px;
}

.badge--primary {
  color: #1677ff;
  background: #eff6ff;
}

.badge--success {
  color: #24a148;
  background: #edf8ef;
}

.badge--warning {
  color: #f59e0b;
  background: #fff7e6;
}

.badge--muted {
  color: #6b7280;
  background: #f3f4f6;
}

@media screen and (max-width: 768px) {
  .table-actions {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
