<template>
  <div class="task-supervision">
    <!-- 页面标题 -->
    <!-- <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-input
            v-model="searchForm.projectName"
            placeholder="请输入监审项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="generateTableData"
          >
            搜索
          </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-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :row-class-name="getRowClassName"
      default-expand-all
    >
      <el-table-column
        prop="serialNumber"
        label="序号"
        width="60"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.pid == 0">
            {{ scope.row.parentIndex }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="year"
        label="立项年度"
        width="100"
        align="center"
      />
      <el-table-column
        prop="projectName"
        label="成本监审项目名称"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.projectName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auditedUnitName"
        label="被监审单位"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.auditedUnitName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auditPeriod"
        label="监审期间"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <span :style="scope.row.style">{{ scope.row.auditPeriod }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="sourceType"
        label="立项来源"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ getDictName('projectProposal', scope.row.sourceType) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="auditType"
        label="监审形式"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ getDictName('auditType', scope.row.auditType) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="superviseStatus"
        label="状态"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <span
            v-if="!(scope.row.isSubTask || scope.row.pid != 0)"
            :style="scope.row.style"
          >
            {{ getSuperviseStatusName(scope.row.superviseStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="warning" label="预警" width="80" align="center">
        <template slot-scope="scope">
          <span :class="['warning-point', computeWarning(scope.row)]"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.isSubTask || scope.row.pid != 0">
            <el-button size="mini" type="text" @click="handleView(scope.row)">
              查看
            </el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              @click="handleDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button size="mini" type="text" @click="handleReport(scope.row)">
              督办报告
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 督办报告弹出框 -->
    <el-dialog
      title="督办报告"
      :visible.sync="isReport"
      width="30%"
      @close="handleCancel"
    >
      <el-form label-width="120px">
        <el-form-item label="报告内容：">
          <el-input
            v-model="reportForm.projectName"
            placeholder="请输入报告内容"
          />
        </el-form-item>
        <el-form-item label="督办材料：">
          <UploadComponent
            :upload-mode="'single'"
            :max-size="50 * 1024 * 1024"
            :allowed-types="['xlsx', 'xls', 'doc', 'docx', 'pdf']"
            :files-list="reportForm.uploadUrl"
            @removeFile="removeFile"
            @saveFiles="saveFiles"
          />
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button type="primary" @click="handleSubmit">确认</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- isDetail -->

    <el-dialog
      title="查看子任务"
      :visible.sync="isView"
      width="80%"
      @close="handleViewDialogClose"
    >
      <!-- todo -->
      详情内容
    </el-dialog>
  </div>
</template>

<script>
  import { getSupervisorList } from '@/api/superviseMattersManage'
  import { dictMixin } from '@/mixins/useDict'
  import UploadComponent from '@/components/costAudit/UploadComponent.vue'
  import { updateSuperviseTask } from '@/api/audit/supervise'

  export default {
    name: 'TaskSupervision',
    components: {
      UploadComponent,
    },
    mixins: [dictMixin],
    data() {
      return {
        dictData: {
          auditType: [], //监审形式
          projectProposal: [], //立项来源
        },
        loading: false,
        searchForm: {
          projectName: '',
          year: '',
        },
        projectList: [],
        tableData: [],
        reportForm: {
          content: '',
          uploadUrl: [],
        },
        fileList: [{ name: '督办说明.pdf', url: '' }],
        currentTask: null,
        activeTab: '0',
        isReport: false,
        isView: false,
        isDetail: false,
      }
    },
    mounted() {
      this.generateTableData()
    },
    methods: {
      handleReset() {
        this.searchForm = {
          projectName: '',
          year: '',
        }
        this.generateTableData()
      },
      generateTableData() {
        // 将主任务和子任务展平为表格数据
        getSupervisorList({
          projectName: this.searchForm.projectName,
          year: this.searchForm.year,
        }).then((res) => {
          this.tableData = res.value
          this.tableData = this.removeItemFromTree(this.tableData)
          let parentIndex = 1
          this.tableData.forEach((item, index) => {
            if (item.pid == 0) {
              item.parentIndex = parentIndex++
            }
          })
        })
      },
      removeItemFromTree(treeData) {
        // 边界条件检查
        if (!treeData || !Array.isArray(treeData)) {
          return []
        }
        // 创建新数组，避免修改原数据
        return treeData.map((item) => {
          // 创建当前节点的副本
          const newItem = { ...item }
          // 如果有hasChildren属性则删除
          if ('hasChildren' in newItem) {
            delete newItem.hasChildren
          }
          // 递归处理子节点 先检查children是否存在且为数组
          if (
            newItem.children &&
            Array.isArray(newItem.children) &&
            newItem.children.length > 0
          ) {
            newItem.children = this.removeItemFromTree(newItem.children)
          }
          return newItem
        })
      },
      getRowClassName({ row }) {
        if (row.isSubTask) {
          return 'sub-task-row'
        }
        return ''
      },
      computeWarning(row) {
        if (!row) return ''
        const ws = (row.warningStatus || '').toString().toLowerCase()
        if (ws === 'green') return 'green'
        if (ws === 'yellow') return 'yellow'
        if (ws === 'res' || ws === 'red') return 'red'

        const parse = (v) => (v ? new Date(v) : null)
        const now = new Date()
        const nodeDdl = parse(row.nodeDeadline)
        const procDdl = parse(row.processDeadline)
        if (nodeDdl && now <= nodeDdl) return 'green'
        if (nodeDdl && procDdl) {
          if (now > nodeDdl && now <= procDdl) return 'yellow'
          if (now > procDdl) return 'red'
        }
        if (!nodeDdl && procDdl) return now <= procDdl ? 'green' : 'red'
        return ''
      },
      getSuperviseStatusName(v) {
        const val = String(v)
        if (val === '0') return '在办'
        if (val === '1') return '办结'
        return v
      },
      handleView(row) {
        console.log('查看子任务:', row)
        this.isView = true
      },
      handleDetails(row) {
        this.isDetail = true
        console.log('查看详情:', row)
      },
      handleReport(row) {
        this.currentTask = row
        this.activeTab = '0'
        this.reportForm = { content: '', uploadUrl: [] }
        this.fileList = []
        this.isReport = true
      },
      // 与 UploadComponent 事件签名保持一致
      // saveFiles(files, props)
      saveFiles(files) {
        const list = Array.isArray(files) ? files : []
        this.reportForm.uploadUrl = list
        this.fileList = list
      },
      // removeFile(index, removedFile, files, props)
      removeFile(index, removedFile, files) {
        const list = Array.isArray(files) ? files : []
        this.reportForm.uploadUrl = list
        this.fileList = list
      },
      handleSubmit() {
        const reportContent = (
          (this.reportForm &&
            (this.reportForm.content || this.reportForm.projectName)) ||
          ''
        ).trim()
        const files = [
          ...(this.reportForm && Array.isArray(this.reportForm.uploadUrl)
            ? this.reportForm.uploadUrl
            : []),
          ...(Array.isArray(this.fileList) ? this.fileList : []),
        ]
          .map((f) =>
            typeof f === 'string'
              ? f
              : (f.response && f.response.value && f.response.value.savePath) ||
                f.savePath ||
                (f.response && f.response.data && f.response.data.savePath) ||
                ''
          )
          .filter(Boolean)
        console.log(files, 'files')
        const attachmentUrls = files.join(',')

        if (!reportContent) {
          this.$message.warning('请输入报告内容')
          return
        }

        const id =
          (this.currentTask &&
            (this.currentTask.superviseId || this.currentTask.ID)) ||
          ''
        if (!id) {
          this.$message.warning('缺少ID，无法提交督办报告')
          return
        }

        const loading = this.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)',
        })

        updateSuperviseTask({ id, reportContent, attachmentUrls })
          .then((res) => {
            if (res && Number(res.code) === 200) {
              this.$message.success('提交成功')
              this.isReport = false
              this.reportForm = { content: '', uploadUrl: [] }
              this.currentTask = null
              this.generateTableData()
            } else {
              this.$message.error((res && res.message) || '提交失败')
            }
          })
          .catch(() => {
            this.$message.error('提交失败')
          })
          .finally(() => {
            loading && loading.close && loading.close()
          })
      },
      handleCancel() {
        console.log('取消')
        this.isReport = false

        // 这里可以添加取消逻辑
      },
      handleDetailDialogClose() {
        this.isDetail = false
      },
      handleViewDialogClose() {
        this.isView = false
      },
    },
  }
</script>

<style scoped>
  .task-supervision {
    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-report {
    margin-top: 20px;
    padding: 15px;
    background-color: #fafafa;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

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

  .warning-dot {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    border: 2px solid;
  }

  .warning-dot.red {
    background-color: red;
    border-color: red;
  }

  .warning-dot.yellow {
    background-color: #ffcc00;
    border-color: #ffcc00;
  }

  .file-list-container {
    border: 1px dashed #d9d9d9;
    padding: 20px;
    text-align: center;
    min-height: 100px;
  }

  .file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 15px;
    margin-bottom: 8px;
    background-color: #fafafa;
    border-radius: 4px;
    text-align: left;
  }

  .upload-btn {
    margin-top: 10px;
  }

  .button-group {
    margin-top: 20px;
    text-align: right;
  }

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

  .el-table .sub-task-cell {
    padding-left: 40px !important;
  }

  /* 预警点样式，保持与任务进度页面一致 */
  .warning-point {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
  }
  .warning-point.red {
    background-color: #ff4949;
  }
  .warning-point.yellow {
    background-color: #e6a23c;
  }
  .warning-point.green {
    background-color: #67c23a;
  }
</style>
