<template>
  <div class="task-progress-manage">
    <!-- 页面标题 -->
    <!-- <h2>成本监审任务进度跟踪</h2> -->
    <div v-if="activeView == 'list'">
      <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"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="监审项目名称：">
            <el-input
              v-model="searchForm.projectName"
              placeholder="请输入监审项目名称"
              clearable
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="iconfont-5039297 icon-chaxun"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="iconfont-5039297 icon-zhongzhi"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据表格 -->
      <cost-audit-table
        v-loading="loading"
        :table-data="tableData"
        :columns="tableColumns"
        :border="true"
        :row-class-name="getRowClassName"
        :show-pagination="true"
        :pagination="pagination"
        :table-props="{
          rowKey: 'id',
          treeProps: { children: 'children', hasChildren: 'hasChildren' },
          defaultExpandAll: true,
          showExpandColumn: false,
        }"
        @pagination-change="handlePaginationChange"
      >
        <template #projectName="{ row }">
          <span v-if="row.isSubTask" class="link-text" @click="handleView(row)">
            {{ row.projectName }}
          </span>
          <span v-else class="link-text" @click="handleViewTaskDetail(row)">
            {{ row.projectName }}
          </span>
        </template>
        <!-- 预警列自定义内容 -->
        <template #warning="{ row }">
          <span :class="['warning-point', computeWarning(row)]"></span>
        </template>

        <!-- 操作列自定义内容 -->
        <template #action="{ row }">
          <template v-if="row.isSubTask">
            <el-button
              size="mini"
              type="text"
              @click="handleMessage(row, 'chengben')"
            >
              查看
            </el-button>
            <el-button
              v-if="row.status != 400 && row.status != 300"
              size="mini"
              type="text"
              @click="handleUrgeReporting(row)"
            >
              催报
            </el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              @click="handleViewTaskDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="
                row.status != 400 &&
                row.status != 300 &&
                row.currentNode !== 'gd'
              "
              size="mini"
              type="text"
              @click="handlePause(row)"
            >
              中止
            </el-button>
            <el-button
              v-if="row.status == '300'"
              type="text"
              @click="handleHf(row)"
            >
              恢复
            </el-button>
            <el-button
              v-if="
                row.status != 400 &&
                row.status != 300 &&
                row.currentNode !== 'gd'
              "
              size="mini"
              type="text"
              @click="handleDelegate(row)"
            >
              催办
            </el-button>
            <el-button
              v-if="
                row.status != 400 &&
                row.status != 300 &&
                row.currentNode !== 'gd' &&
                row.warningStatus !== 'green'
              "
              size="mini"
              type="text"
              @click="handleUrge(row)"
            >
              督办
            </el-button>
            <!-- <el-button
              v-if="row.status != 400 && row.status != 300"
              size="mini"
              type="text"
              @click="handleToDo(row)"
            >
              代办
            </el-button> -->
          </template>
        </template>
        <template slot="empty">
          <Empty></Empty>
        </template>
      </cost-audit-table>
    </div>
    <!-- 详情内容 -->
    <!-- <div v-if="activeView == 'detail'" class="detail-content">
      <detail-tabs :task-data="taskData" :project="project" @detailClose="handleDetailClose"></detail-tabs>
    </div> -->

    <!-- 任务中止表单弹窗 -->
    <el-dialog
      title="任务中止"
      :visible.sync="showPauseForm"
      width="40%"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form ref="pauseForm" :model="pauseForm" label-width="100px">
          <el-form-item label="中止原因：">
            <el-input
              v-model="pauseForm.reason"
              type="textarea"
              rows="5"
              placeholder="请输入中止原因"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePauseFormSubmit">
          确定
        </el-button>
        <el-button @click="handlePauseFormCancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 任务督办弹窗 -->
    <el-dialog
      title="任务督办"
      :visible.sync="showUrgeForm"
      width="50%"
      :modal="true"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form ref="urgeForm" :model="urgeForm" label-width="140px">
          <el-form-item label="选择督办人员：">
            <el-select
              v-model="urgeForm.remindPerson"
              placeholder="请选择选择督办人员"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in urgeUserList"
                :key="index"
                :label="item.fullname"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择要求办结时间：">
            <el-date-picker
              v-model="urgeForm.requireTime"
              type="date"
              placeholder="请选择要求办结时间"
              style="width: 100%"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="督办要求：">
            <el-input
              v-model="urgeForm.content"
              type="textarea"
              rows="5"
              placeholder="请输入督办要求"
              style="width: 100%"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="发送方式：">
            <el-checkbox-group v-model="urgeForm.sendType">
              <el-checkbox label="站内消息">站内消息</el-checkbox>
              <el-checkbox label="短信通知">短信通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleUrgeCancel">取消</el-button>
        <el-button type="primary" @click="handleUrgeSubmit">发送</el-button>
      </div>
    </el-dialog>

    <!-- 任务催报弹窗 -->
    <el-dialog
      title="任务催报"
      :visible.sync="showUrgeReportingForm"
      width="50%"
      :modal="true"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form
          ref="urgeReportingFormRef"
          :model="urgeReportingForm"
          label-width="100px"
        >
          <el-form-item label="催办内容：">
            <el-input
              v-model="urgeReportingForm.content"
              type="textarea"
              rows="5"
              placeholder="请输入催办内容"
              style="width: 100%"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleUrgeReportingCancel">取消</el-button>
        <el-button type="primary" @click="handleUrgeReportingSubmit">
          发送
        </el-button>
      </div>
    </el-dialog>

    <!-- 任务催办弹窗 -->
    <el-dialog
      title="任务催办"
      :visible.sync="showDelegateForm"
      width="50%"
      :modal="true"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form ref="delegateForm" :model="delegateForm" label-width="100px">
          <el-form-item label="监审组人员：">
            <el-select
              v-model="delegateForm.userIds"
              multiple
              clearable
              placeholder="请选择监审组人员"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in delegateUserList"
                :key="index"
                :label="item.fullname"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="催办内容：">
            <el-input
              v-model="delegateForm.content"
              type="textarea"
              rows="5"
              placeholder="请输入催办内容"
              style="width: 100%"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="发送方式：">
            <el-checkbox-group v-model="delegateForm.sendType">
              <el-checkbox label="站内消息">站内消息</el-checkbox>
              <el-checkbox label="短信通知">短信通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDelegateCancel">取消</el-button>
        <el-button type="primary" @click="handleDelegateSubmit">发送</el-button>
      </div>
    </el-dialog>
    <!-- 任务详情弹窗（原组件暂保留，不再从列表入口打开） -->
    <task-detail
      ref="taskDetail"
      :visible.sync="taskDetailVisible"
      :is-view="isView"
    />

    <!-- 任务信息弹窗 -->
    <task-info ref="taskInfo" />

    <!-- 成本监审任务制定弹窗（封装自 tabs.vue，列表“详情/查看”入口使用） -->
    <task-customized-release-dialog
      :visible.sync="taskReleaseDialogVisible"
      :project="project"
      :is-view="true"
      @backToList="taskReleaseDialogVisible = false"
      @close="taskReleaseDialogVisible = false"
    />

    <!-- 成本监审信息弹窗 -->
    <cbjs-info
      :id="cbjsInfoData && cbjsInfoData.id"
      :selected-project="cbjsInfoData"
      :visible.sync="cbjsInfoVisible"
      :current-node="cbjsInfoData && cbjsInfoData.currentNode"
      :current-status="cbjsInfoData && cbjsInfoData.status"
    />
  </div>
</template>

<script>
  import { taskList } from '@/api/taskProgressManage'
  import { dictMixin } from '@/mixins/useDict'
  import { getAllUnitList } from '@/api/auditEntityManage'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import { getUserList, getTaskUserList } from '@/api/uc'
  import { getCostProjectDetail } from '@/api/taskCustomizedRelease.js'
  import { doProcessBtn } from '@/api/dataPreliminaryReview'
  import TaskDetail from '@/components/task/taskDetail.vue'
  import TaskCustomizedReleaseDialog from '@/components/task/TaskCustomizedReleaseDialog.vue'
  import { createSuperviseTask } from '@/api/audit/supervise'
  import cbjsInfo from '@/components/task/cbjsInfo.vue'
  import taskInfo from '@/components/task/taskInfo.vue'
  export default {
    components: {
      CostAuditTable,
      TaskDetail,
      TaskCustomizedReleaseDialog,
      cbjsInfo,
      taskInfo,
    },
    mixins: [dictMixin],
    data() {
      return {
        // 弹窗相关
        cbjsInfoData: null, // 存储当前选中的成本监审信息
        cbjsInfoVisible: false, // 控制成本监审信息弹窗的显示/隐藏

        dictData: {
          auditType: [], //监审形式
          projectProposal: [], //立项来源
        },
        activeView: 'list',
        loading: false,
        isView: true,
        searchForm: {
          year: '',
          projectName: '',
        },
        taskData: {},
        project: {},
        tableData: [],
        // 分页
        pagination: {
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 50, 100],
          total: 0,
        },
        // 表格列配置
        tableColumns: [
          {
            prop: 'serialNumber',
            label: '序号',
            width: 80,
            align: 'center',
            formatter: (row) => {
              return row.pid == 0 ? row.parentIndex : ''
            },
          },
          {
            prop: 'year',
            label: '立项年度',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return row.year || ''
            },
            renderHeader: ({ column, $index }) => {
              return <span>{column.label}</span>
            },
            slotName: 'expand',
          },
          {
            prop: 'projectName',
            label: '成本监审项目名称',
            align: 'left',
            headerAlign: 'center',
            showOverflowTooltip: true,
            slotName: 'projectName',
          },
          {
            prop: 'auditedUnitId',
            label: '被监审单位',
            align: 'left',
            headerAlign: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              // 优先使用后端返回的名称，兼容多个名称逗号分隔
              if (row && row.auditedUnitName) return row.auditedUnitName
              return this.getUnitName(row.auditedUnitId)
            },
          },
          {
            prop: 'auditPeriod',
            label: '监审期间',
            width: 150,
            align: 'center',
          },
          {
            prop: 'sourceType',
            label: '立项来源',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return this.getDictName(
                'projectProposal',
                row && row.sourceType !== undefined && row.sourceType !== null
                  ? String(row.sourceType)
                  : ''
              )
            },
          },
          {
            prop: 'auditType',
            label: '监审形式',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return this.getDictName(
                'auditType',
                row && row.auditType !== undefined && row.auditType !== null
                  ? String(row.auditType)
                  : ''
              )
            },
          },
          {
            prop: 'status',
            label: '状态',
            width: 150,
            align: 'center',
            formatter: (row) => {
              const left = row.currentNodeName || ''
              const right = row.statusName || this.getStatusName(row.status)
              // 当 currentNode 是 'gd' 时，只显示 currentNodeName，不显示 -statusName
              if (row.currentNode === 'gd') {
                return left || right
              }
              return left ? `${left}-${right}` : right
            },
          },
          {
            prop: 'warning',
            label: '预警',
            width: 80,
            align: 'center',
            slotName: 'warning',
          },
          {
            prop: 'action',
            label: '操作',
            width: 240,
            align: 'center',
            slotName: 'action',
          },
        ],
        // 弹窗状态
        showPauseConfirm: false,
        showPauseForm: false,
        showUrgeForm: false,
        showDelegateForm: false,
        showUrgeReportingForm: false,
        // 当前选中的任务
        currentTask: null,
        // 表单数据
        pauseForm: {
          reason: '',
        },
        urgeForm: {
          remindPerson: '',
          requireTime: '',
          content: '',
          // sendType: '站内消息',
        },
        delegateForm: {
          userIds: [],
          content: '',
          // sendType: '站内消息',
        },
        urgeReportingForm: {
          content: '',
        },
        unitList: [],
        // 弹窗人员列表（按接口 getUserList(projectId,type) 动态加载）
        delegateUserList: [], // 催办弹窗：监审组人员（type=0）
        urgeUserList: [], // 督办弹窗：督办人员（type=1）
        // 任务详情弹窗
        taskDetailVisible: false,
        // 成本监审任务制定弹窗
        taskReleaseDialogVisible: false,
      }
    },
    mounted() {
      this.getAllUnitList()
      this.generateTableData()
    },
    methods: {
      async fetchUrgeUserList() {
        try {
          const res = await getTaskUserList({ code: 'dbfzr' })
          return (res && res.value) || []
        } catch (e) {
          return []
        }
      },
      async fetchUserListByProjectId({ projectId, type }) {
        if (!projectId) return []
        try {
          const res = await getUserList({ projectId, type })
          return (res && res.value) || []
        } catch (e) {
          return []
        }
      },

      getStatusName(status) {
        // 100待提交、200审核中、400办结、300中止
        switch (status) {
          case '100':
            return '待提交'
          case '200':
            return '审核中'
          case '400':
            return '办结'
          case '300':
            return '中止'
          default:
            return ''
        }
      },
      getAllUnitList() {
        getAllUnitList().then((res) => {
          this.unitList = res.value || []
        })
      },
      getUnitName(unitId) {
        // 直接处理unitId值，而不是row对象
        if (unitId && typeof unitId === 'string' && unitId.includes(',')) {
          // 如果包含逗号，分割成数组并查找对应的unitName
          const unitIds = unitId.split(',')
          return unitIds
            .map((id) => {
              const unit = this.unitList.find((item) => item.unitId == id)
              return unit ? unit.unitName : ''
            })
            .filter((name) => name) // 过滤空值
            .join(',')
        } else {
          // 单个unitId的情况
          const unit = this.unitList.find((item) => item.unitId == unitId)
          return unit ? unit.unitName : ''
        }
      },
      computeWarning(row) {
        // 优先使用后端返回的 warningStatus：green/yellow/res(red)
        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'

        // 兼容无 warningStatus 时按截止期计算
        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 ''
      },
      generateTableData() {
        this.loading = true
        taskList({
          projectName: this.searchForm.projectName,
          year: this.searchForm.year,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
        })
          .then((res) => {
            // console.log(res,'表格')
            // 兼容分页与非分页返回
            const records = res?.value?.records || res?.value || []
            const total =
              Number(res?.value?.total) ||
              Number(res?.total) ||
              (Array.isArray(records) ? records.length : 0)
            // 统一将 childTasks 规范化为 children，并补齐 pid / isSubTask
            const normalized = this.normalizeChildren(
              Array.isArray(records) ? records : []
            )
            this.tableData = normalized
            this.pagination.total = Number(total) || 0
            // 同步后端分页信息（如有）
            if (Number.isFinite(Number(res?.value?.current))) {
              this.pagination.currentPage = Number(res.value.current)
            }
            if (Number.isFinite(Number(res?.value?.size))) {
              this.pagination.pageSize = Number(res.value.size)
            }
            // 移除不需要的属性
            this.tableData = this.removeItemFromTree(this.tableData)
            let parentIndex = 1
            this.tableData.forEach((item) => {
              if (item.pid == 0) {
                item.parentIndex = parentIndex++
              }
            })
            this.loading = false
          })
          .catch(() => {
            this.loading = false
            this.$message.error('获取数据失败')
          })
      },
      handlePaginationChange({ currentPage, pageSize }) {
        this.pagination.currentPage = currentPage
        this.pagination.pageSize = pageSize
        this.generateTableData()
      },
      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
        })
      },
      normalizeChildren(list, parentId = 0) {
        if (!Array.isArray(list)) return []
        return list.map((node) => {
          const copied = { ...node }
          const rawChildren = Array.isArray(node.children)
            ? node.children
            : Array.isArray(node.childTasks)
            ? node.childTasks
            : []
          // 设置父子关系与子任务标识
          copied.pid =
            node.pid !== undefined && node.pid !== null ? node.pid : parentId
          // 注意：后端可能返回字符串 '0'，需要统一判断
          const pidStr = copied.pid != null ? String(copied.pid) : '0'
          copied.isSubTask = pidStr !== '0'
          // 递归规范化子节点
          const children = this.normalizeChildren(rawChildren, node.id)
          delete copied.childTasks
          copied.children = children
          return copied
        })
      },
      handleReset() {
        this.searchForm = {
          projectName: '',
          year: '',
        }
        this.pagination.currentPage = 1
        this.generateTableData()
      },
      handleSearch() {
        this.pagination.currentPage = 1
        this.generateTableData()
      },

      getRowClassName({ row }) {
        if (row.isSubTask) {
          return 'sub-task-row'
        }
        return ''
      },
      // handleView(row) {
      //   // 子任务查看：统一走任务制定弹窗（只读）
      //   this.openTaskReleaseDialog(row)
      // },
      // 任务中止相关方法
      handlePause(row) {
        this.currentTask = row
        this.$confirm(
          '如您选择中止操作，该任务将停止办理，是否中止？',
          '中止确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            this.showPauseForm = true
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
      },
      handlePauseCancel() {
        this.showPauseConfirm = false
        this.currentTask = null
      },
      handlePauseConfirm() {
        this.showPauseConfirm = false
        this.showPauseForm = true
      },
      handlePauseFormCancel() {
        this.showPauseForm = false
        this.pauseForm.reason = ''
      },
      handlePauseFormSubmit() {
        if (!this.currentTask) return
        const params = {
          taskId: this.currentTask.id,
          key: 2,
          status: 300,
          processNodeKey: this.currentTask.currentNode,
          content: this.pauseForm.reason,
        }
        doProcessBtn(params)
          .then((res) => {
            if (res && Number(res.code) === 200) {
              this.$message.success('任务已中止')
              this.showPauseForm = false
              this.pauseForm.reason = ''
              this.currentTask = null
              this.generateTableData()
            } else {
              this.$message.error(res?.message || '操作失败')
            }
          })
          .catch(() => {
            this.$message.error('操作失败')
          })
      },
      // 恢复任务
      async handleHf(row) {
        if (!row || !row.id) {
          this.$message.error('缺少任务ID')
          return
        }

        // 弹出确认对话框
        this.$confirm('确定要恢复此任务吗？', '恢复任务', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            try {
              const params = {
                taskId: row.id,
                key: 2,
                status: 200,
                processNodeKey: row.currentNode,
              }

              const response = await doProcessBtn(params)

              if (response && response.code === 200) {
                this.$message.success('恢复任务成功')
                // 刷新列表
                this.generateTableData()
              } else {
                this.$message.error(response?.message || '恢复任务失败')
              }
            } catch (error) {
              // this.$message.error('恢复任务失败')
              console.error('恢复任务失败:', error)
            }
          })
          .catch(() => {
            // 用户取消操作
            this.$message.info('已取消恢复任务')
          })
      },
      // 任务督办相关方法
      async handleUrge(row) {
        console.log('任务督办:', row)
        this.currentTask = row
        this.urgeForm = {
          remindPerson: '',
          requireTime: '',
          content: '',
          // sendType: [],
        }

        // 督办人员下拉：走 getTaskUserList，参数 code='dbfzr'
        this.urgeUserList = await this.fetchUrgeUserList()

        this.showUrgeForm = true
      },
      handleUrgeCancel() {
        this.showUrgeForm = false
        this.urgeForm = {
          remindPerson: '',
          requireTime: '',
          content: '',
          // sendType: [],
        }
        this.urgeUserList = []
      },
      handleUrgeSubmit() {
        if (!this.currentTask) return
        const projectId =
          this.currentTask.projectId || this.currentTask.projectID || ''
        const supervisorId = this.urgeForm.remindPerson
        const requireTime = this.urgeForm.requireTime
        const requireContent = (this.urgeForm.content || '').trim()
        if (!projectId) {
          this.$message.warning('缺少项目ID，无法发送督办')
          return
        }
        if (!supervisorId) {
          this.$message.warning('请选择督办人员')
          return
        }
        if (!requireContent) {
          this.$message.warning('请输入督办要求')
          return
        }
        const loading = this.$loading({
          lock: true,
          text: '发送中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0,0,0,0.3)',
        })
        createSuperviseTask({
          projectId,
          supervisorId,
          requireContent,
          requireTime,
        })
          .then((res) => {
            if (res && Number(res.code) === 200) {
              this.$message.success('督办信息已发送')
              this.showUrgeForm = false
              this.urgeForm = { remindPerson: '', content: '', requireTime: '' }
              this.currentTask = null
              this.generateTableData()
            } else {
              this.$message.error(res?.message || '发送失败')
            }
          })
          .catch(() => {
            this.$message.error('发送失败')
          })
          .finally(() => {
            loading && loading.close && loading.close()
          })
      },
      // 任务代办相关方法
      async handleDelegate(row) {
        console.log('任务代办:', row)
        this.currentTask = row
        this.showDelegateForm = true
        this.delegateForm = {
          userIds: [],
          content: '',
        }

        const projectId = row?.projectId || row?.projectID || row?.id || ''
        this.delegateUserList = await this.fetchUserListByProjectId({
          projectId,
          type: 0,
        })
      },
      handleDelegateCancel() {
        this.showDelegateForm = false
        this.delegateForm = {
          userIds: [],
          content: '',
          // sendType: '站内消息',
        }
        this.delegateUserList = []
      },
      handleDelegateSubmit() {
        if (!this.currentTask) return
        if (
          !Array.isArray(this.delegateForm.userIds) ||
          this.delegateForm.userIds.length === 0
        ) {
          this.$message.warning('请选择监审组人员')
          return
        }
        const params = {
          taskId: this.currentTask.id,
          key: 5,
          status: this.currentTask.status,
          processNodeKey: this.currentTask.currentNode,
          content: this.delegateForm.content,
          userIds: this.delegateForm.userIds.join(','),
        }
        doProcessBtn(params)
          .then((res) => {
            if (res && Number(res.code) === 200) {
              this.$message.success('催办信息已发送')
              this.showDelegateForm = false
              this.delegateForm = { userIds: [], content: '' }
              this.currentTask = null
              this.generateTableData()
            } else {
              this.$message.error(res?.message || '操作失败')
            }
          })
          .catch(() => {
            this.$message.error('操作失败')
          })
      },

      // 任务详情相关方法
      handleViewTaskDetail(row) {
        // 主任务详情：打开成本监审任务制定弹窗（只读）
        this.openTaskReleaseDialog(row)
      },
      handleView(row) {
        this.$refs.taskDetail.open(row, 'chengben')
      },
      // 打开成本监审任务制定弹窗（从进度列表“详情/查看”入口）
      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
          })
      },
      getProject() {
        getCostProjectDetail({
          id: this.taskData.projectId,
        })
          .then((res) => {
            this.project = {
              ...res.value,
            }
          })
          .catch(() => {
            this.project = this.taskData
          })
      },
      handleDetailClose() {
        this.activeView = 'list'
        this.taskData = null
      },
      // 代办
      handleToDo(row) {
        console.log('代办', row)
      },
      // 催报
      handleUrgeReporting(row) {
        this.currentTask = row
        this.urgeReportingForm = {
          content: '',
        }
        this.showUrgeReportingForm = true
      },
      handleUrgeReportingCancel() {
        this.showUrgeReportingForm = false
        this.urgeReportingForm = { content: '' }
        this.currentTask = null
      },
      handleUrgeReportingSubmit() {
        if (!this.currentTask) return

        // 不再由弹窗选择被监审单位：默认取当前行的 auditedUnitId
        const auditedUnitIds = this.currentTask.auditedUnitId
          ? String(this.currentTask.auditedUnitId)
          : ''

        const params = {
          taskId: this.currentTask.id,
          key: 10,
          status: this.currentTask.status,
          processNodeKey: this.currentTask.currentNode,
          content: this.urgeReportingForm.content,
          auditedUnitIds,
        }
        doProcessBtn(params)
          .then((res) => {
            if (res && Number(res.code) === 200) {
              this.$message.success('催报信息已发送')
              this.showUrgeReportingForm = false
              this.urgeReportingForm = { content: '' }
              this.currentTask = null
              this.generateTableData()
            } else {
              this.$message.error(res?.message || '操作失败')
            }
          })
          .catch(() => {
            this.$message.error('操作失败')
          })
      },
      // 查看 - 修改为打开cbjsInfo弹窗
      handleMessage(row, type) {
        if (type === 'chengben') {
          this.cbjsInfoData = { ...row, taskId: row.id }

          console.log(this.cbjsInfoData, '数据')
          this.cbjsInfoVisible = true
        } else if (this.$refs.taskInfo) {
          this.$refs.taskInfo.open(row, type)
        } else {
          console.warn('taskInfo 组件未找到，请确保已正确导入和注册')
          // 如果 taskInfo 组件不存在，尝试使用其他方式处理
          this.$message.warning('功能暂不可用，请联系管理员')
        }
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';

  .task-progress-manage {
    padding: 20px;
  }

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

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

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

  .description p {
    margin: 5px 0;
    line-height: 1.6;
  }

  /* 子任务样式 */
  .el-table .sub-task-row {
    background-color: #fafafa !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;
  }

  .back-button-container {
    margin-bottom: 20px;
  }

  .process-tab {
    padding: 20px;
  }

  .process-time-form {
    display: flex;
    align-items: center;
  }
</style>
