<template>
  <div class="task-query-statistics">
    <!-- 页面标题 -->
    <!-- <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-cascader
              v-model="searchForm.areaCode"
              :options="districtTree"
              :props="districtTreeCascaderProps"
              :show-all-levels="false"
              clearable
              placeholder="请选择地区"
            ></el-cascader>
          </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-option label="审核中" value="审核中"></el-option>
              <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.projectName"
              placeholder="请输入监审项目名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="generateTableData"
            >
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计信息 -->
      <div class="statistics-info">
        <span>
          在办事项：
          <span class="pending-count">{{ pendingCount }}</span>
          件
        </span>
        <span>
          已结事项：
          <span class="completed-count">{{ completedCount }}</span>
          件
        </span>
      </div>

      <!-- 数据表格 -->
      <cost-audit-table
        v-loading="loading"
        :table-data="tableData"
        :columns="tableColumns"
        :border="true"
        :row-class-name="getRowClassName"
        :show-pagination="false"
        :table-props="{
          rowKey: 'id',
          treeProps: { children: 'children', hasChildren: 'hasChildren' },
          defaultExpandAll: true,
        }"
      >
        <!-- 操作列自定义模板 -->
        <template #operation="{ row }">
          <el-button size="mini" type="text" @click="handleView(row)">
            查看
          </el-button>
        </template>
      </cost-audit-table>
    </div>

    <!-- 详情内容 -->
    <div v-if="activeView == 'detail'" class="detail-content">
      <detail-tabs
        :project="project"
        :task-data="taskData"
        :is-view="true"
        @detailClose="handleDetailClose"
      ></detail-tabs>
    </div>
  </div>
</template>

<script>
  import { dictMixin, regionMixin } from '@/mixins/useDict'
  import detailTabs from '@/views/costAudit/projectInfo/auditTaskManage/taskProgressManage/detailTabs.vue'
  import { taskList } from '@/api/taskProgressManage'
  import { getAllUnitList } from '@/api/auditEntityManage'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import { getCostProjectDetail } from '@/api/taskCustomizedRelease.js'
  export default {
    components: {
      detailTabs,
      CostAuditTable,
    },
    mixins: [dictMixin, regionMixin],
    data() {
      return {
        dictData: {
          auditType: [], //监审形式
          projectProposal: [], //立项来源
        },
        activeView: 'list',
        loading: false,
        isView: true,
        searchForm: {
          year: '',
          areaCode: '',
          status: '全部',
          projectName: '',
        },
        tableData: [],
        // 统计数据
        statistics: {
          pending: 0,
          completed: 0,
        },
        project: {},
        taskData: {},
        unitList: [],
        // 表格列配置
        tableColumns: [
          {
            prop: 'serialNumber',
            label: '序号',
            width: 60,
            align: 'center',
            formatter: (row) => {
              return row.pid == 0 ? row.parentIndex : ''
            },
          },
          {
            prop: 'year',
            label: '立项年度',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return row.year || ''
            },
          },
          {
            prop: 'region',
            label: '立项地区',
            width: 100,
            align: 'center',
          },
          {
            prop: 'projectName',
            label: '成本监审项目名称',
            showOverflowTooltip: true,
          },
          {
            prop: 'auditedUnitId',
            label: '被监审单位',
            showOverflowTooltip: true,
            formatter: (row) => {
              return this.getUnitName(row.auditedUnitId)
            },
          },
          {
            prop: 'auditPeriod',
            label: '监审期间',
            width: 150,
            align: 'center',
          },
          {
            prop: 'sourceType',
            label: '立项来源',
            width: 120,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('projectProposal', row.sourceType)
            },
          },
          {
            prop: 'auditType',
            label: '监审形式',
            width: 120,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('auditType', row.auditType)
            },
          },
          {
            prop: 'status',
            label: '状态',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return this.getStatusName(row.status)
            },
          },
          {
            prop: 'operation',
            label: '操作',
            width: 80,
            align: 'center',
            slotName: 'operation',
          },
        ],
      }
    },
    computed: {
      pendingCount() {
        // 计算在办任务数量（非办结状态）
        return this.tableData.filter((item) => item.status !== 400).length
      },
      completedCount() {
        // 计算办结任务数量
        return this.tableData.filter((item) => item.status === 400).length
      },
    },
    mounted() {
      this.getAllUnitList()
      this.generateTableData()
    },
    methods: {
      handleReset() {
        this.searchForm = {
          year: '',
          areaCode: '',
          status: '',
          projectName: '',
        }
        this.generateTableData()
      },
      getAllUnitList() {
        getAllUnitList().then((res) => {
          this.unitList = res.value || []
        })
      },
      getUnitName(unitId) {
        // 直接处理unitId值
        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 : ''
        }
      },
      getStatusName(status) {
        // 100待提交、200审核中、400办结、300中止
        switch (status) {
          case '100':
            return '待提交'
          case '200':
            return '审核中'
          case '400':
            return '办结'
          case '300':
            return '中止'
          default:
            return status
        }
      },
      generateTableData() {
        this.loading = true
        taskList({
          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++
              }
            })
            this.loading = false
          })
          .catch(() => {
            this.loading = false
            this.$message.error('获取数据失败')
          })
      },
      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 ''
      },
      handleView(row) {
        this.taskData = row
        this.getProject()
        this.activeView = 'detail'
      },
      getProject() {
        getCostProjectDetail({
          id: this.taskData.projectId,
        })
          .then((res) => {
            this.project = {
              ...res.value,
            }
          })
          .catch(() => {
            this.project = this.taskData
          })
      },
      handleDetailClose() {
        this.activeView = 'list'
      },
      calculateStatistics() {
        // 计算在办和办结任务数量
        let pendingCount = 0
        let completedCount = 0

        this.tableData.forEach((item) => {
          if (item.status === '办结') {
            completedCount++
          } else {
            pendingCount++
          }
        })

        this.statistics = {
          pending: pendingCount,
          completed: completedCount,
        }
      },
    },
  }
</script>

<style scoped>
  .task-query-statistics {
    padding: 20px;
  }

  h2 {
    margin-bottom: 20px;
    font-size: 18px;
    color: #303133;
  }
  .demo-form-inline {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .statistics-info {
    text-align: right;
    margin-bottom: 20px;
  }

  .statistics-info span {
    margin-right: 30px;
  }

  .pending-count,
  .completed-count {
    font-weight: bold;
    color: #1890ff;
  }

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

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

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

  /* 响应式布局 */
  @media (max-width: 1200px) {
    .demo-form-inline {
      flex-direction: column;
      align-items: flex-start;
    }

    .demo-form-inline .el-form-item {
      margin-right: 0;
      margin-bottom: 15px;
    }
  }
</style>
