<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="请选择地区"
              @change="handleAreaChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select
              v-model="searchForm.currentNode"
              placeholder="请选择状态"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="材料初审" value="clcs"></el-option>
              <el-option label="实地审核" value="sdsh"></el-option>
              <el-option label="意见告知" value="yjgz"></el-option>
              <el-option label="意见反馈" value="yjfk"></el-option>
              <el-option label="集体审议" value="jtsy"></el-option>
              <el-option label="出具报告" value="cjbg"></el-option>
              <el-option label="归档" value="gd"></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">{{ statistics.pendingCount }}</span>
          件
        </span>
        <span>
          已结事项：
          <span class="completed-count">{{ statistics.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>
      <!-- 分页 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="total"
        style="margin-top: 20px; text-align: right"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </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 CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import { getTaskListStatistics, getItemsCount } from '@/api/home'

  export default {
    components: {
      detailTabs,
      CostAuditTable,
    },
    mixins: [dictMixin, regionMixin],
    data() {
      return {
        dictData: {
          auditType: [], //监审形式
          projectProposal: [], //立项来源
        },
        activeView: 'list',
        loading: false,
        isView: true,
        searchForm: {
          year: '',
          areaCode: null,
          currentNode: null,
          projectName: '',
        },
        tableData: [],
        // 分页相关
        pageNum: 1,
        pageSize: 10,
        total: 0,
        // 统计数据
        statistics: {
          pendingCount: 0,
          completedCount: 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: 'areaName',
            label: '立项地区',
            width: 100,
            align: 'center',
          },
          {
            prop: 'projectName',
            label: '成本监审项目名称',
            showOverflowTooltip: true,
          },
          {
            prop: 'auditedUnitName',
            label: '被监审单位',
            showOverflowTooltip: true,
          },
          {
            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: 'currentNodeName',
            label: '状态',
            width: 100,
            align: 'center',
          },
          {
            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.getTaskList()
      this.getItemsCount()
    },
    methods: {
      getItemsCount() {
        return getItemsCount().then((res) => {
          this.statistics = res.value
        })
      },
      getTaskList() {
        return getTaskListStatistics({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          year: this.searchForm.year,
          areaCode: this.searchForm.areaCode,
          currentNode: this.searchForm.currentNode,
          projectName: this.searchForm.projectName,
        }).then((res) => {
          if (res.state && res.value) {
            // 获取记录列表
            const records = res.value.records || []
            // 转换数据格式，将childTasks转换为children以適应表格组件
            this.tableData = records.map((record, index) => {
              return {
                id: record.id,
                projectName: record.projectName,
                auditedUnitName: record.auditedUnitName,
                auditPeriod: record.auditPeriod,
                source: this.getSourceTypeText(record.sourceType),
                form: this.getAuditTypeText(record.auditType),
                status: record.status,
                statusName: record.statusName,
                isSubTask: record.pid !== '0' && record.pid !== 0,
                currentNodeName: record.currentNodeName,
                currentNode: record.currentNode,
                projectId: record.projectId,
                auditedUnitId: record.auditedUnitId,
                parentIndex: index + 1, // 母计数作为parentIndex
                year: record.year,
                sourceType: record.sourceType,
                auditType: record.auditType,
                isGd: record.isGd,
                areaName: record.areaName,
                warningStatus: record.warningStatus,
                children:
                  record.childTasks && record.childTasks.length > 0
                    ? record.childTasks.map((child) => ({
                        id: child.id,
                        projectName: child.projectName,
                        auditedUnitName: child.auditedUnitName,
                        auditPeriod: child.auditPeriod || record.auditPeriod,
                        source: child.sourceType
                          ? this.getSourceTypeText(child.sourceType)
                          : '',
                        form: child.auditType
                          ? this.getAuditTypeText(child.auditType)
                          : '',
                        currentNode: child.currentNode,
                        status: child.status,
                        statusName: child.statusName,
                        isSubTask: true,
                        currentNodeName: child.statusName,
                        projectId: child.projectId,
                        auditedUnitId: child.auditedUnitId,
                        taskId: child.id,
                        catalogId: child.catalogId,
                        year: child.year,
                        sourceType: child.sourceType,
                        auditType: child.auditType,
                        isGd: child.isGd,
                        warningStatus: child.warningStatus,
                      }))
                    : [],
              }
            })
            // 设置总数
            this.total = res.value.total || records.length
          } else {
            this.tableData = []
            this.total = 0
          }
        })
      },
      // 获取来源类型文本
      getSourceTypeText(type) {
        const typeMap = {
          1: '年度计划内',
          2: '年度计划外',
        }
        return typeMap[type] || type
      },
      // 获取审核类型文本
      getAuditTypeText(type) {
        const typeMap = {
          1: '定期监审',
          2: '定调价监审',
        }
        return typeMap[type] || type
      },
      handleReset() {
        this.searchForm = {
          year: '',
          areaCode: null,
          currentNode: null,
          projectName: '',
        }
        this.pageNum = 1
        this.getTaskList()
      },
      generateTableData() {
        // 查询时重置为第一页
        this.pageNum = 1
        this.getTaskList()
      },
      getRowClassName({ row }) {
        if (row.isSubTask) {
          return 'sub-task-row'
        }
        return ''
      },
      handleView(row) {
        this.taskData = row
        this.getProject()
        this.activeView = 'detail'
      },
      handleDetailClose() {
        this.activeView = 'list'
      },
      // 分页处理
      handleSizeChange(size) {
        this.pageSize = size
        this.pageNum = 1
        this.getTaskList()
      },
      handleCurrentChange(current) {
        this.pageNum = current
        this.getTaskList()
      },
      // 地区选择处理 - 只按上佊中最后一级值
      handleAreaChange(value) {
        if (Array.isArray(value) && value.length > 0) {
          // 只保留最后一级的值
          this.searchForm.areaCode = value[value.length - 1]
        } else {
          // 清空时设为null
          this.searchForm.areaCode = null
        }
      },
    },
  }
</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>
