<template>
  <div class="supervision-result-manage">
    <!-- 页面标题 -->
    <!-- <h2>成本监审督办结果管理</h2> -->

    <!-- 查询区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="年度：">
          <el-date-picker
            v-model="searchForm.year"
            type="year"
            placeholder="请选择年度"
            format="yyyy"
            value-format="yyyy"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="在办" value="在办"></el-option>
            <el-option label="办结" value="办结"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="督办人：">
          <el-input
            v-model="searchForm.supervisor"
            placeholder="请输入督办人"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="督办项目名称：">
          <el-input
            v-model="searchForm.project"
            placeholder="请输入督办项目名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch">
            搜索
          </el-button>
          <el-button
            plain
            type="primary"
            icon="el-icon-refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      :row-class-name="getRowClassName"
    >
      <el-table-column
        prop="serialNumber"
        label="序号"
        width="60"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="planYear"
        label="立项年度"
        width="100"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="projectName"
        label="成本监审项目名称"
        header-align="center"
        align="left"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.projectName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auditedUnit"
        label="被监审单位"
        header-align="center"
        align="left"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.auditedUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auditPeriod"
        label="监审期间"
        width="150"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.auditPeriod }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="expectedDeadline"
        label="预计截止时间"
        width="150"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="taskStatus"
        label="任务状态"
        width="100"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.taskStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="supervisor"
        label="督办人"
        width="100"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supervisionStatus"
        label="督办状态"
        width="100"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supervisionMessage"
        label="督办消息"
        width="150"
        header-align="center"
        align="left"
      >
        <template slot-scope="scope">
          <span
            v-if="scope.row.supervisionMessage.includes('新报告')"
            style="color: red"
          >
            {{ scope.row.supervisionMessage }}
          </span>
          <span v-else>{{ scope.row.supervisionMessage }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="260"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <template v-if="scope.row.isSubTask">
            <el-button size="mini" type="text" @click="handleView(scope.row)">
              查看
            </el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              @click="handleTaskDetail(scope.row)"
            >
              任务详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleSupervisionDetail(scope.row)"
            >
              督办情况
            </el-button>
            <el-button
              v-if="scope.row.supervisionStatus === '0'"
              size="mini"
              type="text"
              @click="handleEndSupervision(scope.row)"
            >
              结束督办
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 督办情况弹窗 -->
    <el-dialog
      title="督办情况"
      :visible.sync="isSupervisionDetail"
      width="80%"
      @close="handleBack"
    >
      <div class="detail-content">
        <el-table :data="supervisionRecords" border style="width: 100%">
          <el-table-column
            prop="serialNumber"
            label="序号"
            width="60"
            header-align="center"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="supervisor"
            label="督办人"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="reportTime"
            label="报告时间"
            width="150"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="reportContent"
            label="报告内容"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="relatedFiles"
            label="相关附件"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.relatedFiles"
                style="color: #409eff; cursor: pointer"
                @click="handleDownload(scope.row.relatedFiles)"
              >
                {{ scope.row.relatedFiles }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="button-group">
          <el-button @click="handleBack">返回</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 任务详情弹窗（子项“查看”） -->
    <task-detail
      ref="taskDetail"
      :visible.sync="taskDetailVisible"
      :is-view="isView"
    />

    <!-- 成本监审任务制定弹窗（母项“任务详情”） -->
    <task-customized-release-dialog
      :visible.sync="taskReleaseDialogVisible"
      :project="project"
      :is-view="true"
      @backToList="taskReleaseDialogVisible = false"
      @close="taskReleaseDialogVisible = false"
    />
  </div>
</template>

<script>
  import {
    deleteSuperviseTask,
    getSuperviseReportList,
    getSuperviseReportDetail,
  } from '@/api/audit/supervise'
  import TaskDetail from '@/components/task/taskDetail.vue'
  import TaskCustomizedReleaseDialog from '@/components/task/TaskCustomizedReleaseDialog.vue'
  import { getCostProjectDetail } from '@/api/taskCustomizedRelease.js'
  export default {
    data() {
      return {
        loading: false,
        searchForm: {
          year: '2025',
          status: '在办',
          supervisor: '',
          project: '',
        },
        projectList: [
          // 示例数据
          {
            id: 1,
            serialNumber: 1,
            planYear: '2025',
            projectName: '省内油气管道运输成本监审',
            auditedUnit: '山西省油气管道公司、太原市油气公司',
            auditPeriod: '2023年；2024年',
            expectedDeadline: '2025年7月31日',
            taskStatus: '资料初审',
            supervisor: '张**',
            supervisionStatus: '在办',
            supervisionMessage: '新报告',
            isSubTask: false,
            subTasks: [
              {
                id: 101,
                serialNumber: '',
                planYear: '',
                projectName: '子任务',
                auditedUnit: '山西省油气管道公司',
                auditPeriod: '2023年；2024年',
                expectedDeadline: '',
                taskStatus: '通过',
                supervisor: '',
                supervisionStatus: '',
                supervisionMessage: '',
                isSubTask: true,
              },
              {
                id: 102,
                serialNumber: '',
                planYear: '',
                projectName: '子任务',
                auditedUnit: '太原市油气公司',
                auditPeriod: '2023年；2024年',
                expectedDeadline: '',
                taskStatus: '待补充材料',
                supervisor: '',
                supervisionStatus: '',
                supervisionMessage: '',
                isSubTask: true,
              },
            ],
          },
          {
            id: 2,
            serialNumber: 2,
            planYear: '2025',
            projectName: '太原市电网输配电成本监审',
            auditedUnit: '太原市热电厂、****热电厂',
            auditPeriod: '2023年',
            expectedDeadline: '2025年7月31日',
            taskStatus: '集体审议',
            supervisor: '李**',
            supervisionStatus: '办结',
            supervisionMessage: '',
            isSubTask: false,
            subTasks: [
              {
                id: 201,
                serialNumber: '',
                planYear: '',
                projectName: '子任务',
                auditedUnit: '太原市热电厂',
                auditPeriod: '2023年',
                expectedDeadline: '',
                taskStatus: '通过',
                supervisor: '',
                supervisionStatus: '',
                supervisionMessage: '',
                isSubTask: true,
              },
              {
                id: 202,
                serialNumber: '',
                planYear: '',
                projectName: '子任务',
                auditedUnit: '****热电厂',
                auditPeriod: '2023年',
                expectedDeadline: '',
                taskStatus: '通过',
                supervisor: '',
                supervisionStatus: '',
                supervisionMessage: '',
                isSubTask: true,
              },
            ],
          },
        ],
        tableData: [],
        currentTask: null,
        supervisionRecords: [],
        isSupervisionDetail: false,
        // 统一与其它页面一致的弹窗控制
        isView: true,
        taskDetailVisible: false,
        taskReleaseDialogVisible: false,
        project: {},
      }
    },
    mounted() {
      this.generateTableData()
    },
    methods: {
      handleReset() {
        this.searchForm = {
          year: '',
          status: '',
          supervisor: '',
          project: '',
        }
        this.generateTableData()
      },
      generateTableData() {
        this.loading = true
        const statusLabel = (this.searchForm.status || '').toString().trim()
        const status =
          statusLabel === '在办'
            ? '0'
            : statusLabel === '办结'
            ? '1'
            : statusLabel
        const params = {
          year: (this.searchForm.year || '').toString().trim(),
          status,
          supervisor: (this.searchForm.supervisor || '').toString().trim(),
          project: (this.searchForm.project || '').toString().trim(),
          pageNum: 1,
          pageSize: 9999,
        }
        getSuperviseReportList(params)
          .then((res) => {
            // 兼容不同返回结构
            const raw =
              (res &&
                res.value &&
                (res.value.records || res.value.list || res.value)) ||
              (res &&
                res.data &&
                (res.data.records || res.data.list || res.data)) ||
              []
            const arr = Array.isArray(raw) ? raw : []

            const mapStatus = (s) => {
              const v = s != null ? String(s) : ''
              if (v === '100') return '待提交'
              if (v === '200') return '审核中'
              if (v === '300') return '中止'
              if (v === '400') return '办结'
              return v
            }
            const mapSupervise = (s) => {
              const v = s != null ? String(s) : ''
              if (v === '0') return '在办'
              if (v === '1') return '办结'
              return v || ''
            }

            const flat = []
            arr.forEach((item, idx) => {
              const parent = {
                ...item,
                serialNumber: idx + 1,
                isSubTask: false,
                // 映射列字段，避免后端字段名不一致
                planYear: item.planYear || item.year || '',
                auditedUnit:
                  item.auditedUnit ||
                  item.auditedUnitName ||
                  item.auditedUnitNames ||
                  '',
                expectedDeadline:
                  item.expectedDeadline ||
                  item.processDeadline ||
                  item.deadline ||
                  '',
                taskStatus:
                  item.taskStatus || item.statusName || mapStatus(item.status),
                supervisionStatus:
                  item.supervisionStatus || mapSupervise(item.superviseStatus),
                supervisionMessage:
                  item.supervisionMessage || item.message || item.remark || '',
              }
              flat.push(parent)
              const children =
                (item && (item.children || item.subTasks || item.childTasks)) ||
                []
              if (Array.isArray(children) && children.length > 0) {
                children.forEach((c) => {
                  flat.push({
                    ...c,
                    isSubTask: true,
                    serialNumber: '',
                    style: { paddingLeft: '40px' },
                    planYear: c.planYear || c.year || '',
                    auditedUnit:
                      c.auditedUnit ||
                      c.auditedUnitName ||
                      c.auditedUnitNames ||
                      '',
                    expectedDeadline:
                      c.expectedDeadline ||
                      c.processDeadline ||
                      c.deadline ||
                      '',
                    taskStatus:
                      c.taskStatus || c.statusName || mapStatus(c.status),
                    supervisionStatus:
                      c.supervisionStatus || mapSupervise(c.superviseStatus),
                    supervisionMessage:
                      c.supervisionMessage || c.message || c.remark || '',
                  })
                })
              }
            })
            this.tableData = flat
          })
          .catch(() => {
            this.$message.error('获取数据失败')
            this.tableData = []
          })
          .finally(() => {
            this.loading = false
          })
      },
      getRowClassName({ row }) {
        if (row.isSubTask) {
          return 'sub-task-row'
        }
        return ''
      },
      handleSearch() {
        this.generateTableData()
      },
      handleView(row) {
        // 子项“查看”：打开任务详情弹窗
        this.isView = true
        this.taskDetailVisible = true
        this.$nextTick(() => {
          this.$refs.taskDetail && this.$refs.taskDetail.open(row, 'chengben')
        })
      },
      handleTaskDetail(row) {
        // 母项“任务详情”：打开成本监审任务制定弹窗（只读）
        this.openTaskReleaseDialog(row)
      },
      openTaskReleaseDialog(row) {
        if (!row) return
        const projectId =
          row.projectId || row.projectID || row.id || row.taskId || ''
        if (!projectId) {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('缺少项目ID，无法查看详情')
          return
        }
        this.isView = true
        getCostProjectDetail({ id: projectId })
          .then((res) => {
            this.project = (res && res.value) || {}
            this.taskReleaseDialogVisible = true
          })
          .catch(() => {
            this.project = row || {}
            this.taskReleaseDialogVisible = true
          })
      },
      handleSupervisionDetail(row) {
        this.isSupervisionDetail = true
        this.currentTask = row
        const id = row && (row.superviseId || row.id || row.ID)
        if (!id) {
          this.supervisionRecords = []
          return
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)',
        })
        getSuperviseReportDetail({ id })
          .then((res) => {
            const raw = (res && (res.value || res.data)) || []
            const arr = Array.isArray(raw)
              ? raw
              : Array.isArray(raw?.records)
              ? raw.records
              : []
            this.supervisionRecords = arr.map((it, idx) => ({
              serialNumber: idx + 1,
              supervisor: it.supervisor || it.supervisorName || '',
              reportTime: it.reportTime || it.createTime || it.reportDate || '',
              reportContent: it.reportContent || it.content || '',
              relatedFiles:
                it.attachmentUrls || it.attachmentIds || it.relatedFiles || '',
            }))
          })
          .catch(() => {
            this.$message.error('获取督办情况失败')
            this.supervisionRecords = []
          })
          .finally(() => {
            loading && loading.close && loading.close()
          })
      },
      handleDownload(paths) {
        if (!paths) return
        const base =
          window.context && window.context.form ? window.context.form : ''
        const list = String(paths)
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean)
        list.forEach((p) => {
          const url = p.startsWith('http') ? p : base + p
          window.open(url)
        })
      },
      handleEndSupervision(row) {
        console.log('结束督办:', row)
        this.$confirm('确定要结束督办吗？', '结束督办', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const loading = this.$loading({
              lock: true,
              text: '处理中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)',
            })
            const id = row && (row.superviseId || row.ID)
            if (!id) {
              loading && loading.close && loading.close()
              this.$message.error('缺少ID，无法结束督办')
              return
            }
            deleteSuperviseTask({ id })
              .then((res) => {
                if (res && Number(res.code) === 200) {
                  this.$message.success('已结束督办')
                  this.generateTableData()
                } else {
                  this.$message.error((res && res.message) || '操作失败')
                }
              })
              .catch(() => {
                this.$message.error('操作失败')
              })
              .finally(() => {
                loading && loading.close && loading.close()
              })
          })
          .catch(() => {
            this.$message.info('已取消')
          })
      },
      handleBack() {
        this.isSupervisionDetail = false
        this.currentTask = null
      },
    },
  }
</script>

<style scoped>
  .supervision-result-manage {
    padding: 20px;
  }

  h2 {
    margin-bottom: 20px;
    font-size: 18px;
    color: #303133;
  }

  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #303133;
  }

  .demo-form-inline {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .description {
    margin-top: 15px;
    margin-bottom: 20px;
    padding: 10px;
    background-color: #fff7e6;
    border: 1px solid #ffe7ba;
    border-radius: 4px;
  }

  .supervision-detail {
    margin-top: 20px;
    padding: 15px;
    background-color: #fafafa;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .detail-content {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
  }

  .button-group {
    margin-top: 15px;
    text-align: center;
  }

  /* 子任务样式 */
  .el-table .sub-task-row {
    background-color: #fafafa !important;
  }

  /* 新报告标记样式 */
  .new-report-tag {
    display: inline-block;
    padding: 0 5px;
    margin-left: 5px;
    font-size: 12px;
    color: #fff;
    background-color: #ff4949;
    border-radius: 4px;
  }
</style>
