<template>
  <div class="cost-audit-management">
    <!-- 成本审核项目列表页面 -->
    <div v-if="activeView === 'list'" class="audit-list-container">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="监审项目名称"
          style="width: 300px; margin-right: 10px"
          clearable
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>

      <el-table
        v-loading="loading"
        class="mb10"
        :data="auditProjectList"
        style="width: 100%"
        border
        default-expand-all
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <!-- 只显示父节点的序号 -->
            <span v-if="scope.row.children">
              {{ getParentNodeIndex(scope.row) }}
            </span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="projectName"
          label="成本监审项目名称"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          prop="auditObject"
          label="监审对象"
          header-align="center"
          align="left"
        />
        <el-table-column
          prop="auditPeriod"
          label="监审期间"
          header-align="center"
          align="center"
          width="120"
        />
        <el-table-column
          prop="source"
          label="立项来源"
          header-align="center"
          align="center"
          width="100"
        />
        <el-table-column
          prop="form"
          label="监审形式"
          header-align="center"
          align="center"
          width="100"
        />
        <el-table-column
          prop="currentNodeName"
          label="状态"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <span v-if="!scope.row.isSubTask">
              {{ scope.row.currentNodeName }}
            </span>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSubTask" class="action-buttons">
              <el-button type="text" @click="handleTaskDetail(scope.row)">
                任务详情
              </el-button>
              <el-button
                v-if="scope.row.currentNode === 'sdsh'"
                type="text"
                @click="handleTaskProcess(scope.row)"
              >
                任务办理
              </el-button>
              <el-button type="text" @click="handleCheckRecord(scope.row)">
                备忘录
              </el-button>
            </span>
            <span v-if="scope.row.isSubTask" class="action-buttons">
              <el-button
                v-if="
                  scope.row.currentNode === 'ccls' &&
                  scope.row.status === '审核中'
                "
                type="text"
                @click="handleAuditReview(scope.row)"
              >
                资料初审
              </el-button>
              <el-button
                v-if="scope.row.currentNode === 'sdsh'"
                type="text"
                @click="handleCostAudit(scope.row)"
              >
                成本审核
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 成本监审任务详情页面 -->
    <div v-else-if="activeView === 'detail'" class="audit-detail-container">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>
          <a href="javascript:void(0)" @click="backToList">成本审核管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>成本监审任务详情</el-breadcrumb-item>
      </el-breadcrumb>
      <taskDetail
        ref="taskDetail"
        :workflow-list="workflowList"
        :form-data="formData"
        :material-data="materialData"
      />
    </div>

    <!-- 任务办理页面 -->
    <div v-else-if="activeView === 'process'" class="audit-process-container">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>
          <a href="javascript:void(0)" @click="backToList">成本审核管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>成本监审任务办理</el-breadcrumb-item>
      </el-breadcrumb>
      <taskProcess ref="taskProcess" />
    </div>
    <div v-else-if="activeView === 'auditReview'">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>
          <a href="javascript:void(0)" @click="backToList">成本审核管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>资料初审</el-breadcrumb-item>
      </el-breadcrumb>
      <auditReview
        :id="currentProject.id"
        :current-node="currentProject.currentNode"
        @handleBack="backToList"
      />
    </div>
    <div v-else-if="activeView === 'costAudit'">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>
          <a href="javascript:void(0)" @click="backToList">成本审核管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>成本审核</el-breadcrumb-item>
      </el-breadcrumb>
      <costAudit @handleBack="backToList" />
    </div>
  </div>
</template>

<script>
  import taskDetail from './taskDetail.vue'
  import taskProcess from './taskProcess.vue'
  import auditReview from './auditReview.vue'
  import costAudit from './costAudit.vue'
  import taskMixins from './taskMixins.js'
  // 成本监审任务列表API
  import { getReviewTaskList } from '@/api/audit/auditIndex'
  export default {
    name: 'CostAuditManagement',
    components: {
      taskDetail,
      taskProcess,
      auditReview,
      costAudit,
    },
    mixins: [taskMixins],
    data() {
      return {
        // 分页相关
        currentPage: 1,
        pageSize: 10,
        total: 0,
        // 视图控制
        activeView: 'list', // list: 列表, detail: 详情, process: 办理
        // 搜索相关
        searchQuery: '',
        // 列表数据
        auditProjectList: [],
        // workflowList: [],
        notificationsList: [],
        templatesList: [],
        // 加载状态
        loading: false,
        // 当前选中的项目
        currentProject: null,
      }
    },

    created() {
      this.loadAuditProjectList()
    },

    methods: {
      // 获取父节点的连续序号
      getParentNodeIndex(row) {
        // 过滤出所有父节点
        const parentNodes = this.auditProjectList.filter(
          (item) => item.children && item.children.length > 0
        )
        // 找到当前行在父节点数组中的索引
        const index = parentNodes.findIndex((item) => item.id === row.id)
        // 返回序号（索引+1）
        return index + 1
      },
      // 加载审核项目列表
      async loadAuditProjectList() {
        try {
          this.loading = true
          // 调用API获取数据
          const params = {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            projectName: this.searchQuery,
          }
          const response = await getReviewTaskList(params)

          // 根据API返回格式处理数据
          if (response.state && response.value) {
            // 获取记录列表
            const records = response.value.records || []
            // 转换数据格式，将childTasks转换为children以适应表格组件
            this.auditProjectList = records.map((record) => {
              return {
                id: record.id,
                projectName: record.projectName,
                auditObject: record.auditedUnitName,
                auditPeriod: record.auditPeriod,
                source: this.getSourceTypeText(record.sourceType),
                form: this.getAuditTypeText(record.auditType),
                status: this.getStatusText(record.status),
                isSubTask: record.pid !== '0',
                currentNodeName: record.currentNodeName,
                currentNode: record.currentNode,
                children: record.childTasks
                  ? record.childTasks.map((child) => ({
                      id: child.id,
                      projectName: child.projectName,
                      auditObject: child.auditedUnitName,
                      auditPeriod: record.auditPeriod, // 子任务可能使用父任务的审核期间
                      source: '',
                      form: '',
                      currentNode: child.currentNode,
                      status: child.status,
                      isSubTask: true,
                    }))
                  : [],
              }
            })
            // 设置总数
            this.total = response.value.total || 0
          } else {
            this.auditProjectList = []
            this.total = 0
            this.$message.warning('未获取到审核项目数据')
          }
        } catch (error) {
          this.$message.error('加载审核项目列表失败')
          console.error('加载审核项目列表失败:', error)
        } finally {
          this.loading = false
        }
      },

      // 获取来源类型文本
      getSourceTypeText(type) {
        const typeMap = {
          1: '年度计划内',
          2: '年度计划外',
          // 可根据实际需求补充其他类型
        }
        return typeMap[type] || type
      },

      // 获取审核类型文本
      getAuditTypeText(type) {
        const typeMap = {
          1: '定期监审',
          2: '定调价监审',
          // 可根据实际需求补充其他类型
        }
        return typeMap[type] || type
      },

      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          ccls: '资料初审',
          200: '审核通过',
          clcs: '审核中', // 添加clcs状态映射为审核中
          // 可根据实际需求补充其他状态
        }
        return statusMap[status] || status
      },

      // 搜索
      handleSearch() {
        // 搜索逻辑
        this.loadAuditProjectList()
      },

      // 任务详情
      handleTaskDetail(project) {
        this.currentProject = project
        this.activeView = 'detail'
        this.loadAuditProjectDetail(project.id)
        this.loadWorkflowList(project.id)
        this.loadNotificationsList(project.id)
      },

      // 任务办理
      handleTaskProcess(project) {
        this.currentProject = project
        this.activeView = 'process'
        this.loadTemplatesList()

        // 初始化集体审议表单中的项目信息
        if (project) {
          this.meetingForm.projectName = project.projectName
          this.meetingForm.auditUnit = project.auditObject
        }
      },
      handleAuditReview(project) {
        this.currentProject = project
        this.activeView = 'auditReview'
      },

      // 查记录
      handleCheckRecord(project) {
        // memoManage
        this.$router.push({
          name: 'memoManage',
          // params: { projectId: project.id }
        })
      },

      // 查看
      handleView(project) {
        this.currentProject = project
        this.activeView = 'detail'
        this.loadAuditProjectDetail(project.id)
        this.loadWorkflowList(project.id)
        this.loadNotificationsList(project.id)
      },

      // 成本审核
      handleCostAudit(project) {
        this.currentProject = project
        this.activeView = 'costAudit'
        this.loadAuditProjectDetail(project.id)
        this.loadWorkflowList(project.id)
        this.loadNotificationsList(project.id)
      },

      // 返回列表
      backToList() {
        this.activeView = 'list'
        // 刷新列表数据
        this.loadAuditProjectList()
      },

      // 返回详情
      backToDetail() {
        this.activeView = 'detail'
      },

      // 加载审核项目详情
      async loadAuditProjectDetail(id) {
        try {
          // 这里应该调用API获取数据，现在使用模拟数据
          this.basicForm = {
            projectName: '太原市电网输配电成本监审',
            costAuditTable: '电网企业成本监审表',
            region: 'shanxi',
            auditObject: '太原市热电厂、****热电厂、****公司',
            year: '2023',
            source: 'plan',
            form: 'price',
            startYear: '2023',
            endYear: '2024',
            isNew: '否',
            isDynamic: '否',
            basis: '太原市发改委关于开展2023年电网输配电成本监审的通知',
            attachments: [
              {
                name: '太原市发改委关于开展2023年电网输配电成本监审的通知.pct',
              },
              { name: '其他附件.pdf' },
            ],
          }
        } catch (error) {
          this.$message.error('加载审核项目详情失败')
          console.error('加载审核项目详情失败:', error)
        }
      },

      // 加载工作流程列表
      async loadWorkflowList(id) {
        try {
          // 这里应该调用API获取数据，现在使用模拟数据
          this.workflowList = [
            {
              id: '1',
              stepName: '提交材料',
              nodeType: '外部环节',
              handler: '张**、李**',
              opinions: '已提交相关材料',
              deadline: '2025-5-4',
              startTime: '2025-4-18 14:20',
              endTime: '2025-4-18 15:30',
            },
            {
              id: '2',
              stepName: '资料初审',
              nodeType: '内部环节',
              handler: '王**',
              opinions: '资料齐全，同意进入下一环节',
              deadline: '2025-5-4',
              startTime: '2025-5-4 10:10',
              endTime: '2025-5-4 16:30',
            },
            {
              id: '3',
              stepName: '实地审核',
              nodeType: '内部环节',
              handler: '张**',
              opinions: '正在审核中',
              deadline: '2025-5-6',
              startTime: '2025-5-6 09:00',
              endTime: '2025-5-6 18:30',
            },
            // 其他环节...
            {
              id: '8',
              stepName: '办结',
              nodeType: '内部环节',
              handler: '李**',
              opinions: '',
              deadline: '2025-5-30',
              startTime: '',
              endTime: '',
            },
          ]
        } catch (error) {
          this.$message.error('加载工作流程列表失败')
          console.error('加载工作流程列表失败:', error)
        }
      },

      // 加载消息通知列表
      async loadNotificationsList(id) {
        try {
          // 这里应该调用API获取数据，现在使用模拟数据
          this.notificationsList = [
            {
              id: '1',
              title: '材料收到通知',
              source: '山西省发改委-张**',
              target: 'A单位',
              content: '2025年收到你单位报送的材料...',
              sendTime: '2025-5-11 16:40',
            },
            {
              id: '2',
              title: '环节办理通知',
              source: '山西省发改委-张**',
              target: 'B单位',
              content: '2025年收到你单位报送的材料...',
              sendTime: '2025-5-12 16:56',
            },
            // 其他通知...
            {
              id: '9',
              title: '',
              source: '',
              target: '',
              content: '',
              sendTime: '2025-5-30 16:55',
            },
          ]
        } catch (error) {
          this.$message.error('加载消息通知列表失败')
          console.error('加载消息通知列表失败:', error)
        }
      },

      // 加载模板列表
      async loadTemplatesList() {
        try {
          // 这里应该调用API获取数据，现在使用模拟数据
          this.templatesList = [
            { id: '1', name: '成本监审通知书' },
            { id: '2', name: '成本监审工作方案' },
            { id: '3', name: '成本监审资料报送要求' },
            { id: '4', name: '成本监审意见告知书' },
            { id: '5', name: '成本监审结论告知书' },
            { id: '6', name: '成本监审报告' },
            { id: '7', name: '成本监审报告(送审稿)' },
            { id: '8', name: '成本监审结论告知书(适用返还)' },
            { id: '9', name: '成本监审结论告知书(适用返还)-送审稿' },
          ]
          this.selectedTemplate = '1'
        } catch (error) {
          this.$message.error('加载模板列表失败')
          console.error('加载模板列表失败:', error)
        }
      },

      // 分页处理
      handleSizeChange(size) {
        this.pageSize = size
        this.loadAuditProjectList()
      },

      handleCurrentChange(current) {
        this.currentPage = current
        this.loadAuditProjectList()
      },
    },
  }
</script>

<style scoped>
  .cost-audit-management {
    padding: 20px;
  }

  /* 列表页面样式 */
  .search-section {
    margin-bottom: 20px;
  }

  .action-buttons {
    font-size: 12px;
  }

  .action-buttons a {
    color: #409eff;
    text-decoration: none;
  }

  .separator {
    margin: 0 5px;
    color: #999;
  }

  .note-section {
    margin-top: 20px;
  }

  .note-text {
    color: #f56c6c;
    font-size: 12px;
    margin: 5px 0;
  }

  /* 详情页面样式 */
  .audit-detail-container {
    margin-top: 20px;
  }

  .detail-form {
    margin-top: 20px;
  }

  .tab-content {
    padding: 20px;
    background-color: #f9f9f9;
    min-height: 200px;
  }

  /* 办理页面样式 */
  .audit-process-container {
    margin-top: 20px;
  }

  .process-actions {
    margin-bottom: 20px;
  }

  .process-actions .el-button {
    margin-right: 10px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .process-steps {
      flex-direction: column;
    }

    .step-line {
      width: 2px;
      height: 20px;
      margin: 5px 0;
    }

    .documents-layout {
      flex-direction: column;
    }

    .documents-type-list {
      width: 100%;
      margin-right: 0;
      margin-bottom: 20px;
    }

    .meeting-form .el-row {
      flex-direction: column;
    }

    .meeting-form .el-col {
      width: 100%;
    }
  }
</style>
