<template>
  <module-page-shell title="任务下发">
    <div class="task-dispatch-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="projectForm.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__actions">
            <el-button type="primary" class="project-filter-bar__button" @click="applyProjectSelection">查询</el-button>
            <el-button class="project-filter-bar__button" @click="resetProjectSelection">重置</el-button>
          </div>
        </div>
      </section>

      <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--keyword">
            <el-input
              v-model="filterForm.keyword"
              placeholder="评估任务关键词"
              clearable
            />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-select v-model="filterForm.assignedAssessor" placeholder="评估师：全部" clearable>
              <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--narrow">
            <el-select v-model="filterForm.status" placeholder="状态：全部" clearable>
              <el-option label="状态：全部" value="" />
              <el-option label="未开始" value="未开始" />
              <el-option label="进行中" value="进行中" />
            </el-select>
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--date">
            <el-date-picker
              v-model="filterForm.deadline"
              class="project-date-picker"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="年 / 月 / 日"
            />
          </div>
          <div class="project-filter-bar__actions">
            <el-button type="primary" class="project-filter-bar__button" @click="applyTaskFilters">查询</el-button>
            <el-button class="project-filter-bar__button" @click="resetTaskFilters">重置</el-button>
          </div>
        </div>

        <el-table :data="filteredTasks" class="dispatch-table">
          <el-table-column label="评估任务" min-width="260">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.taskName"
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入评估任务"
                class="table-select"
                :disabled="scope.row.isSaved"
              >
                <el-option
                  v-for="item in taskOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="当前评估师" min-width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.currentAssessor || '待分配' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分配给评估师" min-width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.assignedAssessor" placeholder="请选择评估师" class="table-select" :disabled="scope.row.isSaved">
                <el-option
                  v-for="item in assessorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="截止" min-width="120">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.deadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="截止日期"
                class="project-date-picker deadline-picker"
                :disabled="scope.row.isSaved"
              />
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="120">
            <template slot-scope="scope">
              <span :class="['status-pill', statusClass(scope.row.status)]">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="190" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="scope.row.isSaved"
                @click="handleSaveAssignment(scope.row)"
              >
                保存分配
              </el-button>
              <el-button
                size="mini"
                :disabled="!scope.row.isSaved || scope.row.isDispatched"
                @click="handleDispatch(scope.row)"
              >
                下发
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-actions">
          <el-button type="primary" @click="handleDispatchAll">一键下发任务</el-button>
          <el-button @click="handleAddRow">新增行</el-button>
        </div>
      </section>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import cache from '@/plugins/cache'
import { listProject } from '@/api/risk/project'

const TASK_STORAGE_KEY = 'project-task-dispatch-records-v1'

const DEFAULT_TASKS = [
  { key: 'industry', taskName: '行业风险评估', deadlineOffset: 13, status: '进行中', isSaved: true, isDispatched: true },
  { key: 'finance', taskName: '企业财务评估', deadlineOffset: 13, status: '未开始', isSaved: false, isDispatched: false },
  { key: 'legal', taskName: '法务政策评估', deadlineOffset: 12, status: '未开始', isSaved: false, isDispatched: false }
]

const DEFAULT_ASSESSORS = ['评估师A', '评估师B', '评估师C', '评估师D']

const TASK_LIBRARY = [
  '行业风险评估',
  '企业财务评估',
  '法务政策评估',
  '担保品合规审查',
  '估值复核',
  '综合结论汇总'
]

export default {
  name: 'ProjectTaskDispatch',
  components: {
    ModulePageShell
  },
  data() {
    return {
      projectOptions: [],
      projectForm: {
        projectName: ''
      },
      currentProjectName: '',
      filterForm: {
        keyword: '',
        assignedAssessor: '',
        status: '',
        deadline: ''
      },
      appliedFilters: {
        keyword: '',
        assignedAssessor: '',
        status: '',
        deadline: ''
      },
      taskStore: {}
    }
  },
  computed: {
    currentProject() {
      return this.projectOptions.find(item => item.projectName === this.currentProjectName) || null
    },
    assessorOptions() {
      const pool = new Set(DEFAULT_ASSESSORS)
      const tasks = this.taskStore[this.currentProjectName] || []
      tasks.forEach(item => {
        if (item.currentAssessor) {
          pool.add(item.currentAssessor)
        }
        if (item.assignedAssessor) {
          pool.add(item.assignedAssessor)
        }
      })
      if (this.currentProject && this.currentProject.assessor) {
        pool.add(this.currentProject.assessor)
      }
      return Array.from(pool).map(item => ({ label: item, value: item }))
    },
    taskOptions() {
      const options = new Set(TASK_LIBRARY)
      const tasks = this.taskStore[this.currentProjectName] || []
      tasks.forEach(item => {
        if (item.taskName) {
          options.add(item.taskName)
        }
      })
      return Array.from(options).map(item => ({ label: item, value: item }))
    },
    filteredTasks() {
      const tasks = this.taskStore[this.currentProjectName] || []
      const keyword = (this.appliedFilters.keyword || '').trim().toLowerCase()
      return tasks.filter(item => {
        const hitKeyword = !keyword || `${item.taskName || ''}`.toLowerCase().includes(keyword)
        const hitAssessor = !this.appliedFilters.assignedAssessor || item.assignedAssessor === this.appliedFilters.assignedAssessor
        const hitStatus = !this.appliedFilters.status || item.status === this.appliedFilters.status
        const hitDeadline = !this.appliedFilters.deadline || item.deadline === this.appliedFilters.deadline
        return hitKeyword && hitAssessor && hitStatus && hitDeadline
      })
    }
  },
  created() {
    this.initPage()
  },
  activated() {
    this.initPage()
  },
  methods: {
    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 initPage() {
      const response = await listProject({ pageNum: 1, pageSize: 1000 })
      this.projectOptions = (response.rows || []).map(item => ({
        projectId: item.projectId,
        projectName: item.projectName,
        assessor: item.assessor || ''
      }))
      this.taskStore = cache.local.getJSON(TASK_STORAGE_KEY) || {}
      this.projectForm.projectName = this.resolvePreferredProjectName(this.projectForm.projectName)
      this.applyProjectSelection()
    },
    applyProjectSelection() {
      this.currentProjectName = this.projectForm.projectName
      if (!this.currentProjectName) {
        return
      }
      if (!Array.isArray(this.taskStore[this.currentProjectName])) {
        this.$set(this.taskStore, this.currentProjectName, this.buildDefaultTasks())
        this.persistTaskStore()
      }
    },
    resetProjectSelection() {
      this.projectForm.projectName = this.projectOptions[0] ? this.projectOptions[0].projectName : ''
      this.applyProjectSelection()
    },
    buildDefaultTasks() {
      const assessors = this.resolveAssessorPool()
      return DEFAULT_TASKS.map((item, index) => ({
        rowId: `${this.currentProjectName || 'project'}-${item.key}-${index}`,
        taskName: item.taskName,
        currentAssessor: assessors[index] || assessors[0] || '',
        assignedAssessor: assessors[index] || assessors[0] || '',
        deadline: this.buildDeadline(item.deadlineOffset),
        status: item.status,
        isSaved: item.isSaved,
        isDispatched: item.isDispatched,
        isNew: false
      }))
    },
    resolveAssessorPool() {
      const pool = [...DEFAULT_ASSESSORS]
      if (this.currentProject && this.currentProject.assessor && !pool.includes(this.currentProject.assessor)) {
        pool.unshift(this.currentProject.assessor)
      }
      return pool
    },
    buildDeadline(offsetDays) {
      const now = new Date()
      now.setDate(now.getDate() + offsetDays)
      const year = now.getFullYear()
      const month = `${now.getMonth() + 1}`.padStart(2, '0')
      const day = `${now.getDate()}`.padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    persistTaskStore() {
      cache.local.setJSON(TASK_STORAGE_KEY, this.taskStore)
    },
    applyTaskFilters() {
      this.appliedFilters = { ...this.filterForm }
    },
    resetTaskFilters() {
      this.filterForm = {
        keyword: '',
        assignedAssessor: '',
        status: '',
        deadline: ''
      }
      this.appliedFilters = { ...this.filterForm }
    },
    statusClass(status) {
      if (status === '进行中') {
        return 'status-pill--progress'
      }
      return 'status-pill--pending'
    },
    getCurrentRows() {
      return this.taskStore[this.currentProjectName] || []
    },
    updateCurrentRows(rows) {
      this.$set(this.taskStore, this.currentProjectName, rows)
      this.persistTaskStore()
    },
    handleAddRow() {
      if (!this.currentProjectName) {
        this.$message.warning('请先选择项目')
        return
      }
      const rows = this.getCurrentRows().slice()
      const now = Date.now()
      rows.push({
        rowId: `${this.currentProjectName}-new-${now}`,
        taskName: '',
        currentAssessor: '待分配',
        assignedAssessor: '',
        deadline: this.buildDeadline(10),
        status: '未开始',
        isSaved: false,
        isDispatched: false,
        isNew: true
      })
      this.updateCurrentRows(rows)
    },
    validateTaskRow(row) {
      if (!row.taskName || !`${row.taskName}`.trim()) {
        this.$message.warning('请先填写评估任务')
        return false
      }
      if (!row.assignedAssessor) {
        this.$message.warning('请先选择评估师')
        return false
      }
      return true
    },
    handleSaveAssignment(row) {
      if (!this.validateTaskRow(row)) {
        return
      }
      const rows = this.getCurrentRows().map(item => {
        if (item.rowId !== row.rowId) {
          return item
        }
        return {
          ...item,
          currentAssessor: item.assignedAssessor,
          isSaved: true
        }
      })
      this.updateCurrentRows(rows)
      this.$message.success('保存分配成功')
    },
    handleDispatch(row) {
      const rows = this.getCurrentRows().map(item => {
        if (item.rowId !== row.rowId) {
          return item
        }
        return {
          ...item,
          status: '进行中',
          isDispatched: true
        }
      })
      this.updateCurrentRows(rows)
      this.$message.success('任务已下发')
    },
    handleDispatchAll() {
      const rows = this.getCurrentRows().slice()
      const pendingRows = rows.filter(item => item.isSaved && !item.isDispatched)
      if (pendingRows.length === 0) {
        this.$message.warning('当前没有可一键下发的任务')
        return
      }
      const nextRows = rows.map(item => ({
        ...item,
        status: item.isSaved ? '进行中' : item.status,
        isDispatched: item.isSaved ? true : item.isDispatched
      }))
      this.updateCurrentRows(nextRows)
      this.$message.success('已完成一键下发')
    }
  }
}
</script>

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

.task-dispatch-page {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

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

.task-dispatch-page .project-filter-bar__field--keyword {
  flex: 0 1 300px;
  max-width: 340px;
  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;
}

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

.table-select,
.deadline-picker {
  width: 100%;
}

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

.status-pill--progress {
  color: #1677ff;
  background: #eff6ff;
}

.status-pill--pending {
  color: #6b7280;
  background: #f3f4f6;
}

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