<template>
  <div class="index4-container">
    <!-- 左侧表单，占据20%宽度 -->
    <div class="left-form">
      <el-card class="form-card floating-card">
        <div class="form-button">
            <el-button class="filter-button reset-button" @click="resetFilter">重置筛选</el-button>
        </div>
        <div class="form-button">
            <el-button class="filter-button apply-button" @click="handleQuery">应用筛选</el-button>
        </div>
        
        <!-- 时间筛选子标题 -->
        <div class="time-filter-title">时间筛选</div>
        
        <!-- 时间段选择按钮 -->
        <div class="period-buttons">
          <el-button 
            :class="['period-button', { 'active': selectedPeriod === '本月' }]"
            @click="selectPeriod('本月')"
          >本月</el-button>
          <el-button 
            :class="['period-button', { 'active': selectedPeriod === '上月' }]"
            @click="selectPeriod('上月')"
          >上月</el-button>
          <el-button 
            :class="['period-button', { 'active': selectedPeriod === '本季度' }]"
            @click="selectPeriod('本季度')"
          >本季度</el-button>
        </div>
        
        <!-- 日期选择控件 -->
        <div class="date-picker-container">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="年/月/日"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="年/月/日"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </div>
        
        <!-- 维度筛选 -->
        <div class="filter-card">
          <div class="flex justify-between items-center cursor-pointer" @click="toggleFilter('dimension')">
            <h2 class="text-lg font-semibold text-neutral-700 flex items-center">
              <i class="fa fa-filter blue-color" style="margin-right: 10px;"></i><span style="margin-top: 3px;">维度</span>
            </h2>
            <i class="fa fa-chevron-up text-neutral-400 transition-transform duration-300" :class="{'rotate-180': dimensionExpanded}" id="dimension-toggle"></i>
          </div>
          <!-- 多级筛选下拉框 -->
          <div class="filter-select">
            <el-cascader
              v-model="selectedFilterCombination"
              :options="filterOptions"
              :props="cascaderProps"
              placeholder="请选择筛选条件组合"
              clearable
              style="width: 100%;"
              @change="handleCascaderChange"
            ></el-cascader>
          </div>
          
          <!-- 设备选择树形下拉框 -->
          <div class="filter-select" style="margin-top: 15px;margin-bottom: 10px;">
            <el-popover
              placement="bottom-start"
              :width="250"
              trigger="click"
              popper-class="equipment-tree-popover"
            >
              <template #reference>
                <el-input 
                  readonly
                  :model-value="getDisplayLabel(selectedEquipmentNodes)"
                  placeholder="请选择设备"
                  style="width: 100%; cursor: pointer;"
                  clearable
                >
                  <template #suffix>
                    <i class="el-input__icon el-icon-arrow-down"></i>
                  </template>
                </el-input>
              </template>
              
              <div style="padding: 5px; border-bottom: 1px solid #eee; margin-bottom: 5px; display: flex; align-items: center;">
                <el-input 
                  v-model="equipmentKeyword" 
                  placeholder="请输入关键字" 
                  size="small"
                  style="width: 120px;"
                  @keyup.enter="filterEquipmentOptions"
                />
                <el-button 
                  type="primary" 
                  size="small"
                  style="width: 50px; margin-left: 5px;"
                  @click="filterEquipmentOptions"
                >
                  筛选
                </el-button>
                <el-button 
                  size="small"
                  style="width: 50px; margin-left: 5px;"
                  @click="resetEquipmentFilter"
                >
                  重置
                </el-button>
              </div>
              
              <el-tree
                ref="equipmentTree"
                :data="filteredEquipmentOptions || equipmentOptions"
                show-checkbox
                node-key="value"
                :props="equipmentTreeProps"
                :default-checked-keys="selectedEquipment"
                @check="handleEquipmentTreeCheck"
                style="max-height: 300px; overflow-y: auto;"
              />
            </el-popover>
          </div>
          <div id="dimension-content" class="filter-content" :class="{'hidden': !dimensionExpanded}">
            <!-- 地点纬度 - 树状选择 -->
            <!-- <div class="tree-select">
              <div class="tree-header" data-target="location-content" @click="toggleTree('location')">
                <span class="font-medium">归属地</span>
                <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.location}"></i>
              </div>
              <div id="location-content" class="tree-content" :class="{'show': treeExpanded.location}">
                <label v-if="checkCenter()" class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.location.center" label="中心" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.location.station" label="场站" />
                </label>
              </div>
            </div> -->
            
            <!-- 风机纬度 - 树状选择 -->
            <!-- <div class="tree-select">
              <div class="tree-header" data-target="fan-content" @click="toggleTree('fan')">
                <span class="font-medium">风机相关</span>
                <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.fan}"></i>
              </div>
              <div id="fan-content" class="tree-content" :class="{'show': treeExpanded.fan}">
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.fan.number" label="风机编号" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.fan.brand" label="品牌" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.fan.model" label="机型" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.fan.system" label="风机系统" disabled />
                </label>
              </div>
            </div> -->
            
            <!-- 类型维度 - 树状选择 -->
            <div class="tree-select">
              <div class="tree-header" data-target="type-content" @click="toggleTree('type')">
                <span class="font-medium">工单类型</span>
                <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.type}"></i>
              </div>
              <div id="type-content" class="tree-content" :class="{'show': treeExpanded.type}">
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.type.repair" label="维修" @change="handleWorkorderToggle" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.type.maintenance" label="维保" @change="handleWorkorderToggle"/>
                </label>
              </div>
            </div>
            
            <!-- 其他维度 - 树状选择 -->
            <div class="tree-select">
              <div class="tree-header" data-target="other-content" @click="toggleTree('other')">
                <span class="font-medium">其他</span>
                <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.other}"></i>
              </div>
              <div id="other-content" class="tree-content" :class="{'show': treeExpanded.other}">
                <label v-if="!(indicatorFilters.workorder.restartNum && !indicatorFilters.workorder.workorder)" class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.other.repairman" label="工作班成员" />
                </label>
                <label class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.other.manager" label="工作负责人" />
                </label>
                <label v-if="indicatorFilters.workorder.restartNum" class="checkbox-item ml-2">
                  <el-checkbox v-model="dimensionFilters.other.operator" label="复启操作人" />
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 指标筛选 -->
        <div class="filter-card flex-1">
          <div class="flex justify-between items-center cursor-pointer" @click="toggleFilter('indicator')">
            <h2 class="text-lg font-semibold text-neutral-700 flex items-center">
              <i class="fa fa-bar-chart blue-color" style="margin-right: 10px;"></i><span style="margin-top: 3px;">指标</span>
            </h2>
            <i class="fa fa-chevron-up text-neutral-400 transition-transform duration-300" :class="{'rotate-180': indicatorExpanded}" id="indicator-toggle"></i>
          </div>
          <div id="indicator-content" class="filter-content" :class="{'hidden': !indicatorExpanded}">
          
          <!-- 工单指标 - 树状选择 -->
          <div class="tree-select">
            <div class="tree-header" data-target="workorder-content" @click="toggleTree('workorder')">
              <span class="font-medium">工单</span>
              <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.workorder}"></i>
            </div>
            <div id="workorder-content" class="tree-content" :class="{'show': treeExpanded.workorder}">
              <label v-if="dimensionFilters.type.repair || dimensionFilters.type.maintenance" class="checkbox-item ml-2">
                <el-checkbox v-model="indicatorFilters.workorder.workorder" label="工单数量" @change="handleWorkorderSelect" />
              </label>
              <label v-if="!onlyWorkOrder" class="checkbox-item ml-2">
                <el-checkbox v-model="indicatorFilters.workorder.restartNum" label="复启数量" @change="handleWorkorderSelect" />
              </label>
            </div>
          </div>
          
          <!-- 工时指标 - 树状选择 -->
          <div class="tree-select">
            <div class="tree-header" data-target="workhour-content" @click="toggleTree('workhour')">
              <span class="font-medium">工时</span>
              <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.workhour}"></i>
            </div>
            <div id="workhour-content" class="tree-content" :class="{'show': treeExpanded.workhour}">
              <label class="checkbox-item ml-2">
                <el-checkbox v-model="indicatorFilters.workhour.enabled" label="工时统计" @change="handleWorkhourToggle" />
              </label>
              <div class="ml-4 mt-1 border-l-2 border-neutral-200 pl-2" style="margin-left: 20px;">
                <label v-if="!onlyWorkOrder" class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.xfsc" label="下发时长" @change="handleWorkhourSelect" />
                </label>
                <label v-if="!onlyWorkOrder" class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.xysc" label="接单时长" @change="handleWorkhourSelect" />
                </label>
                <label v-if="!onlyWorkOrder" class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.zbsc" label="准备时长" @change="handleWorkhourSelect" />
                </label>
                <label class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.clsc" label="作业时长" @change="handleWorkhourSelect" />
                </label>
                <label class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.qjbwsc" label="验收时长" @change="handleWorkhourSelect" />
                </label>
                <label class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.tjsc" label="停运时长" @change="handleWorkhourSelect" />
                </label>
                <label class="checkbox-item">
                  <el-checkbox v-model="indicatorFilters.workhour.items.gqsc" label="挂起时长" @change="handleWorkhourSelect" />
                </label>
              </div>
            </div>
          </div>
          
          <!-- 工分指标 - 树状选择 -->
          <div class="tree-select">
            <div class="tree-header" data-target="score-content" @click="toggleTree('score')">
              <span class="font-medium">工分</span>
              <i class="fa fa-chevron-left text-neutral-400 transition-transform duration-300" :class="{'rotate-90': treeExpanded.score}"></i>
            </div>
            <div id="score-content" class="tree-content" :class="{'show': treeExpanded.score}">
              <label class="checkbox-item ml-2">
                <el-checkbox v-model="indicatorFilters.score.enabled" label="工分统计" @change="handleScoreSelect" />
              </label>
            </div>
          </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 右侧内容，占据80%宽度 -->
    <div class="right-content">
      <!-- 第一行：4个图标，每个占据25%宽度 -->
      <div class="icons-row">
        <el-card class="floating-card icon-item" @click="toRoute(0)">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-red">
                <el-icon class="fa fa-exclamation-triangle text-danger"></el-icon>
                <!-- 角标位置调整到卡片右上角 -->
                <div v-if="homePageData.timeOutNum>0" class="badge">{{ homePageData.timeOutNum }}</div>
              </div>
            </div>
            <div class="icon-label">超时工单</div>
          </div>
        </el-card>
        <el-card class="floating-card icon-item" @click="toRoute(1)">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-blue">
                <el-icon class="fa fa-pencil text-primary blue-color"></el-icon>
                <!-- 角标位置调整到卡片右上角 -->
                <div v-if="homePageData.todoNum>0" class="badge">{{ homePageData.todoNum }}</div>
              </div>
            </div>
            <div class="icon-label">我的待办</div>
          </div>
        </el-card>
        <!-- 修改我处理的卡片的布局 -->
        <el-card class="floating-card icon-item" @click="toRoute(3)">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-red">
                <el-icon class="fa fa-check text-danger"></el-icon>
              </div>
            </div>
            <div class="icon-label">我处理的</div>
          </div>
        </el-card>
        <el-card class="floating-card icon-item-big">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-yellow">
                <el-icon class="fa fa-cogs deep-yellow-color"></el-icon>
              </div>
            </div>
            <div>
              <div class="card-header">
                <span class="card-title">维修工单总数</span>
              </div>
              <div class="card-content">
                <div class="data-value deep-yellow-color">{{ homePageData.repairOrderNum }}</div>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="floating-card icon-item-big">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-green">
                <el-icon class="fa fa-wrench green-color"></el-icon>
              </div>
            </div>
            <div>
              <div class="card-header">
                <span class="card-title">维保工单总数</span>
              </div>
              <div class="card-content">
                <div class="data-value green-color">{{ homePageData.workOrderNum }}</div>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="floating-card icon-item-big">
          <div class="todo-content">
            <div class="icon-wrapper">
              <div class="icon-circle bg-color-purple">
                <el-icon class="fa fa-repeat purple-color"></el-icon>
              </div>
            </div>
            <div>
              <div class="card-header">
                <span class="card-title">复启工单总数</span>
              </div>
              <div class="card-content">
                <div class="data-value purple-color">{{ homePageData.repairRestartOrderNum }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 第二行：4个表单，每个占据25%宽度
      <div class="forms-row">
        <div class="form-item">
          <el-card class="data-card floating-card">
            <div class="card-header">
              <span class="card-title">维保工单总数</span>
              <div class="card-icon bg-color-blue">
                <el-icon class="fa fa-search blue-color"></el-icon>
              </div>
            </div>
            <div class="card-content">
              <div class="data-value">{{ homePageData.workOrderNum }}</div>
              <div class="data-description" :style="{ color: getTextColor(homePageData.workOrderJsy) }">
                <i v-if="homePageData.workOrderJsy > 0" class="fa fa-arrow-up" style="margin-right: 4px;"></i>
                <i v-else-if="homePageData.workOrderJsy < 0" class="fa fa-arrow-down" style="margin-right: 4px;"></i>
                <i v-else class="fa fa-minus" style="margin-right: 4px;"></i>
                {{ homePageData.workOrderJsy }}% 较上月</div>
            </div>
          </el-card>
        </div>
        <div class="form-item">
          <el-card class="data-card floating-card">
            <div class="card-header">
              <span class="card-title">维修工单总数</span>
              <div class="card-icon bg-color-green">
                <el-icon class="fa fa-cog green-color"></el-icon>
              </div>
            </div>
            <div class="card-content">
              <div class="data-value">{{ homePageData.repairOrderNum }}</div>
              <div class="data-description" :style="{ color: getTextColor(homePageData.repairOrderJsy) }">
                <i v-if="homePageData.repairOrderJsy > 0" class="fa fa-arrow-up" style="margin-right: 4px;"></i>
                <i v-else-if="homePageData.repairOrderJsy < 0" class="fa fa-arrow-down" style="margin-right: 4px;"></i>
                <i v-else class="fa fa-minus" style="margin-right: 4px;"></i>
                {{ homePageData.repairOrderJsy }}% 较上月</div>
            </div>
          </el-card>
        </div>
        <div class="form-item">
          <el-card class="data-card floating-card">
            <div class="card-header">
              <span class="card-title">本月工时(小时)</span>
              <div class="card-icon bg-color-purple">
                <el-icon class="fa fa-clock-o purple-color"></el-icon>
              </div>
            </div>
            <div class="card-content">
              <div class="data-value">{{ formatWorkValue(homePageData.wbgs) }}</div>
              <div class="data-description" :style="{ color: getTextColor(homePageData.wbjsy) }">
                <i v-if="homePageData.wbjsy > 0" class="fa fa-arrow-up" style="margin-right: 4px;"></i>
                <i v-else-if="homePageData.wbjsy < 0" class="fa fa-arrow-down" style="margin-right: 4px;"></i>
                <i v-else class="fa fa-minus" style="margin-right: 4px;"></i>
                {{ homePageData.wbjsy }}% 较上月</div>
            </div>
          </el-card>
        </div>
        <div class="form-item">
          <el-card class="data-card floating-card">
            <div class="card-header">
              <span class="card-title">本月工分</span>
              <div class="card-icon bg-color-orange">
                <el-icon class="fa fa-refresh orange-color"></el-icon>
              </div>
            </div>
            <div class="card-content">
              <div class="data-value">{{ formatWorkValue(homePageData.score) }}</div>
              <div class="data-description" :style="{ color: getTextColor(homePageData.gfjsy) }">
                <i v-if="homePageData.gfjsy > 0" class="fa fa-arrow-up" style="margin-right: 4px;"></i>
                <i v-else-if="homePageData.gfjsy < 0" class="fa fa-arrow-down" style="margin-right: 4px;"></i>
                <i v-else class="fa fa-minus" style="margin-right: 4px;"></i>
                {{ homePageData.gfjsy }}% 较上月</div>
            </div>
          </el-card>
        </div>
      </div> -->

      <!-- 第三行：工单数据列表 -->
      <div class="list-row">
        <el-card class="list-card floating-card">
          <template #header>
            <div class="list-header">
              <i class="fa fa-table blue-color" style="margin-right: 10px;"></i>
              <span>工单数据列表</span>
              <div class="header-buttons">
                <el-input
                  v-model="queryParams.remark"
                  placeholder="搜索"
                  @keyup.enter="handleQuery"
                  style="width: 150px; margin-right: 10px;"
                  prefix-icon="search"
                  clearable
                />
                <el-button @click="handleExport">
                  <i class="fa fa-download" style="margin-right: 8px;"></i>导出</el-button>
              </div>
            </div>
          </template>
          <el-table :data="orderList" style="width: 100%">
            <el-table-column v-if="hasOrderCode()" prop="orderCode" label="工单编码" :style="{ width: changeWidth() * 2 + '%' }" header-align="center" align="center">
              <template #default="scope">
                <span style="color: #409EFF;" @click="handleWorkOrderClick(scope.row)">{{ scope.row.orderCode }}</span >
              </template>
            </el-table-column>
            <el-table-column v-if="queryParams.code" prop="code" label="风机编号" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.brand" prop="brand" label="品牌" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.model" prop="model" label="机型" :style="{ width: changeWidth() * 2 + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.system" prop="system" label="风机系统" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.center && checkCenter()" prop="center" label="中心" :style="{ width: changeWidth() * 2 + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.pcs" prop="pcs" label="场站" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.workOrder || queryParams.repairOrder" prop="orderType" label="工单类型" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.repairPerson" prop="repairPerson" label="工作班成员" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.chargePerson" prop="chargePerson" label="工作负责人" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.operator" prop="operator" label="复启操作人" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.workOrderNum==1" prop="workOrderNum" label="维保工单数" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.repairOrderNum==1" prop="repairOrderNum" label="维修工单数" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.restartNum==1" prop="restartNum" label="复启数量" :style="{ width: changeWidth() + '%' }" header-align="center" align="center"></el-table-column>
            <el-table-column v-if="queryParams.score==1" prop="score" label="工分" :style="{ width: changeWidth() + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.xfsc" prop="xfsc" label="下发时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.xysc" prop="xysc" label="接单时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.zbsc" prop="zbsc" label="准备时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.clsc" prop="clsc" label="作业时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.qjbwsc" prop="qjbwsc" label="验收时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.tjsc" prop="tjsc" label="停运时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
            <el-table-column v-if="queryParams.gqsc" prop="gqsc" label="挂起时长(h)" :style="{ width: changeWidth() * 1.5 + '%' }" header-align="center" align="center" :formatter="formatScore"></el-table-column>
          </el-table>
          <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="applyFilter"
            />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { getHomePageOrderListData } from '@/api/gxt/gxtOrder';
import { selectHomePageData } from '@/api/gxt/repairOrder';
import { listAllEquipment } from '@/api/gxt/equipment';
import { listMyTodo } from '@/api/gxt/orderMine';
import { encryptParams } from '@/utils/encrypt';
import { getConfigKey } from '@/api/system/config';

export default {
  name: 'Index4',
  data() {
    return {
      leftFormData: {
        field1: '',
        field2: '',
        field3: '',
        field4: ''
      },
      // 维度筛选数据
      dimensionFilters: {
        location: {
          center: true,
          station: true
        },
        fan: {
          number: false,
          brand: false,
          model: false,
          system: false
        },
        type: {
          repair: true,
          maintenance: true
        },
        other: {
          repairman: false,
          manager: false,
          operator: false
        }
      },
      // 指标筛选数据
      indicatorFilters: {
        workorder: {
          workorder: true,
          restartNum: false,
        },
        workhour: {
          enabled: false,
          items: {
            tjsc: false,
            xfsc : false,
            xysc: false,
            zbsc: false,
            clsc: false,
            qjbwsc: false,
            gqsc: false
          }
        },
        score: {
          enabled: false
        }
      },
      // 当前选中的指标类别，用于实现互斥选择
      selectedIndicatorCategory: null,
      // 展开收起状态
      dimensionExpanded: true,
      indicatorExpanded: true,
      treeExpanded: {
        location: true,
        fan: true,
        type: true,
        other: true,
        workorder: true,
        workhour: true,
        score: true
      },
      // 添加时间筛选相关数据
      selectedPeriod: '本月', // 选中的时间段（本月、上月、本季度）
      startDate: '', // 开始日期
      endDate: '', // 结束日期
      // 添加查询参数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        startTime: null,
        endTime: null,
        center: false,
        pcs: false,
        code: false,
        brand: false,
        model: false,
        system: false,
        repairOrder: false,
        workOrder: false,
        repairPerson: false,
        chargePerson: false,
        operator: false,
        repairOrderNum: null,
        workOrderNum: null,
        restartNum: null,
        tjsc: false,
        xfsc: false,
        xysc: false,
        zbsc: false,
        clsc: false,
        qjbwsc: false,
        gqsc: false,
        score: null,
        remark: null,
        devices: null,
        orderType: null,
      },
      orderList: [],
      // 添加首页统计数据
      homePageData: {
        workOrderNum: 120, // 维保工单总数
        workOrderJsy: 15,  // 维保工单较上月增长百分比
        repairOrderNum: 85, // 维修工单总数
        repairOrderJsy: 8,  // 维修工单较上月增长百分比
        repairRestartOrderNum: 5, // 维修工单复启数量
        wbgs: 168,         // 本月工时
        wbjsy: 12,         // 本月工时较上月增长百分比
        score: 92,         // 本月工分
        gfjsy: 5,           // 本月工分较上月增长百分比
        repairPending: 0,
        workPending: 0,
        pendingNum: 0,
        todoNum: 0,        // 我的待办数量
        hasCenter: null,
        timeOutNum: 0,
      },
      // 多级筛选数据
      selectedFilterCombination: [],
      cascaderProps: {
        checkStrictly: true,
        expandTrigger: 'hover',
        multiple: false
      },
      filterOptions: [
        {
          value: 'center',
          label: '中心',
          children: [
            {
              value: 'station',
              label: '场站',
              children: [
                {
                  value: 'brand',
                  label: '品牌',
                  children: [
                    {
                      value: 'model',
                      label: '机型'
                    }
                  ]
                }
              ]
            }
          ]
        },
        {
          value: 'brand',
          label: '品牌',
          children: [
            {
              value: 'center',
              label: '中心',
              children: [
                {
                  value: 'station',
                  label: '场站',
                  children: [
                    {
                      value: 'model',
                      label: '机型'
                    }
                  ]
                }
              ]
            },
            {
              value: 'area',
              label: '区域',
              children: [
                {
                  value: 'model',
                  label: '机型'
                }
              ]
            }
          ]
        },
        {
          value: 'model',
          label: '机型',
          children: [
            {
              value: 'brand',
              label: '品牌',
              children: [
                {
                  value: 'area',
                  label: '区域'
                }
              ]
            }
          ]
        }
      ],
      // 设备筛选数据
      selectedEquipment: [], // 存储选中的设备ID
      selectedEquipmentNodes: [], // 存储选中的设备节点信息
      equipmentOptions: [],
      equipmentTreeProps: {
        label: 'label',
        children: 'children',
        disabled: 'disabled'
      },
      equipmentKeyword: '',
      originalEquipmentOptions: null,
      filteredEquipmentOptions: null,
      // 定时器
      timer: null,
      onlyWorkOrder: false,
    }
  },
  created() {
    this.selectPeriod('本月');
    this.loadHomePageData(); // 首次加载首页统计数据
    this.loadEquipmentData(); // 加载设备数据
    this.applyFilter();
    
    // 设置定时器，每3秒执行一次loadHomePageData函数
    this.timer = setInterval(() => {
      this.loadHomePageData();
    }, 3000);
  },
  methods: {
    // 在组件销毁前清除定时器
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    handleCascaderChange(val) {
      console.log('选中的节点值：', val);
      
      // 重置所有维度筛选条件
      this.dimensionFilters.location.center = false;
      this.dimensionFilters.location.station = false;
      this.dimensionFilters.fan.brand = false;
      this.dimensionFilters.fan.model = false;
      
      // 如果没有选择任何值，直接返回
      if (!val || val.length === 0) {
        return;
      }
      
      // 遍历选中的值
      val.forEach(item => {
        if (item === 'center') {
          this.dimensionFilters.location.center = true;
        } else if (item === 'station') {
          this.dimensionFilters.location.station = true;
        } else if (item === 'area') {
          this.dimensionFilters.location.center = true;
          this.dimensionFilters.location.station = true;
        } else if (item === 'brand') {
          this.dimensionFilters.fan.brand = true;
        } else if (item === 'model') {
          this.dimensionFilters.fan.model = true;
        }
      });
      
      // 根据val的内容和顺序来构建设备级联选项
      this.buildEquipmentOptionsByVal(val);
    },

    // 根据val的内容和顺序来构建设备级联选项
    buildEquipmentOptionsByVal(val) {
      // 重置设备选项
      this.equipmentOptions = [];
      
      // 如果没有选择任何值，直接返回
      if (!val || val.length === 0) {
        return;
      }
      
      // 根据选择的维度动态构建设备级联选项
      // 获取所有设备数据
      listAllEquipment().then(response => {
        if (response.code === 200) {
          const equipmentList = response.rows;
          
          // 创建根级别的选项映射
          const rootOptions = {};
          
          // 根据val中的值来过滤和构建设备选项
          const filteredEquipment = equipmentList.filter(item => {
            // 检查是否符合选中的维度条件
            let match = true;
            
            if (val.includes('center') && !item.maintenanceCenter) match = false;
            if (val.includes('station') && !item.station) match = false;
            if (val.includes('brand') && !item.brand) match = false;
            if (val.includes('model') && !item.model) match = false;
            
            return match;
          });
          
          // 遍历过滤后的设备列表，根据val的顺序构建层级结构
          filteredEquipment.forEach((item, index) => {
            // 根据val的顺序构建值数组
            const values = [];
            let path = []; // 用于构建唯一键的路径
            
            val.forEach(level => {
              switch (level) {
                case 'center':
                  if (item.maintenanceCenter) {
                    path.push(`center-${item.maintenanceCenter}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.maintenanceCenter,
                      originalValue: item.maintenanceCenter
                    });
                  }
                  break;
                case 'station':
                  if (item.station) {
                    path.push(`station-${item.station}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.station,
                      originalValue: item.station
                    });
                  }
                  break;
                case 'brand':
                  if (item.brand) {
                    path.push(`brand-${item.brand}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.brand,
                      originalValue: item.brand
                    });
                  }
                  break;
                case 'model':
                  if (item.model) {
                    path.push(`model-${item.model}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.model,
                      originalValue: item.model
                    });
                  }
                  break;
                case 'area':
                  // area表示同时选择center和station两个层级
                  if (item.maintenanceCenter) {
                    path.push(`center-${item.maintenanceCenter}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.maintenanceCenter,
                      originalValue: item.maintenanceCenter
                    });
                  }
                  if (item.station) {
                    path.push(`station-${item.station}`);
                    values.push({ 
                      value: path.join('-'), 
                      label: item.station,
                      originalValue: item.station
                    });
                  }
                  break;
              }
            });
            
            // 添加风机编号作为最终层级
            // 显示为equipmentCode，但值为equipmentId
            if (item.equipmentCode && item.equipmentId) {
              path.push(`equipment-${item.equipmentId}-${index}`);
              values.push({ 
                value: path.join('-'),     // 使用唯一键
                label: item.equipmentCode, // 显示为equipmentCode
                originalValue: item.equipmentId, // 保存原始设备ID
                equipmentId: item.equipmentId   // 保存设备ID
              });
            }
            
            // 构建层级结构
            this.buildHierarchy(rootOptions, values);
          });
          
          // 在第一个选项中添加标记
          const convertedOptions = this.convertToCascaderOptions(rootOptions);
          if (convertedOptions.length > 0) {
            convertedOptions[0].isFirst = true;
          }
          
          // 将构建好的选项转换为级联选择器需要的格式
          this.equipmentOptions = convertedOptions;
        }
      }).catch(error => {
        console.error('加载设备数据失败:', error);
      });
    },
    
    // 根据值数组构建层级结构
    buildHierarchy(optionsMap, values) {
      if (!values || values.length === 0) return;
      
      let currentLevel = optionsMap;
      
      values.forEach((value, index) => {
        // 生成当前层级的唯一键
        const key = value.value;
        
        // 如果当前层级不存在，则创建
        if (!currentLevel[key]) {
          currentLevel[key] = {
            value: value.value,
            label: value.label,
            children: {},
            originalValue: value.originalValue, // 保存原始值
            equipmentId: value.equipmentId      // 保存设备ID（如果是设备节点）
          };
        }
        
        // 如果是最后一级，确保children是数组
        if (index === values.length - 1) {
          currentLevel[key].children = [];
        }
        
        // 移动到下一级
        currentLevel = currentLevel[key].children;
      });
    },
    
    // 将层级结构转换为级联选择器需要的格式
    convertToCascaderOptions(optionsMap) {
      const result = [];
      
      Object.values(optionsMap).forEach((item, index) => {
        const option = {
          value: item.value,
          label: item.label,
          originalValue: item.originalValue, // 保存原始值
          equipmentId: item.equipmentId      // 保存设备ID（如果是设备节点）
        };
        
        // 添加isFirst标记（仅第一个选项）
        if (index === 0 && item.isFirst) {
          option.isFirst = true;
        }
        
        // 如果有子级且不为空，递归转换
        if (item.children && Object.keys(item.children).length > 0) {
          option.children = this.convertToCascaderOptions(item.children);
        } else {
          // 如果是叶子节点，确保children是空数组
          option.children = [];
        }
        
        result.push(option);
      });
      
      return result;
    },
    
    // 加载设备数据并构建级联选择器选项
    async loadEquipmentData() {
      try {
        const response = await listAllEquipment();
        if (response.code === 200) {
          // �建设备级联选项
          this.buildEquipmentOptions(response.rows);
        }
      } catch (error) {
        console.error('加载设备数据失败:', error);
      }
    },

    // 构建设备级联选项
    buildEquipmentOptions(equipmentList) {
      // 初始化选项数组
      this.equipmentOptions = [];
      
      // 创建映射对象来存储不同层级的数据
      const centers = {};
      const stations = {};
      const brands = {};
      const models = {};
      
      // 遍历设备列表，构建层级结构
      equipmentList.forEach((item, index) => {
        const center = item.maintenanceCenter;
        const station = item.station;
        const brand = item.brand;
        const model = item.model;
        const equipmentCode = item.equipmentCode;
        const equipmentId = item.equipmentId; // 获取设备ID
        
        // 为每个层级生成唯一值，避免重复
        const centerKey = center ? `center-${center}` : null;
        const stationKey = center && station ? `station-${center}-${station}` : null;
        const brandKey = center && station && brand ? `brand-${center}-${station}-${brand}` : null;
        const modelKey = center && station && brand && model ? `model-${center}-${station}-${brand}-${model}` : null;
        
        // 维保中心层级
        if (center && !centers[centerKey]) {
          centers[centerKey] = {
            value: centerKey,
            label: center,
            children: [],
            originalValue: center // 保存原始值
          };
        }
        
        // 场站层级
        if (center && station && !stations[stationKey]) {
          stations[stationKey] = {
            value: stationKey,
            label: station,
            children: [],
            originalValue: station // 保存原始值
          };
          
          // 将场站添加到对应的维保中心下
          if (centers[centerKey] && !centers[centerKey].children.some(child => child.value === stationKey)) {
            centers[centerKey].children.push(stations[stationKey]);
          }
        }
        
        // 品牌层级
        if (center && station && brand && !brands[brandKey]) {
          brands[brandKey] = {
            value: brandKey,
            label: brand,
            children: [],
            originalValue: brand // 保存原始值
          };
          
          // 将品牌添加到对应的场站下
          if (stations[stationKey] && !stations[stationKey].children.some(child => child.value === brandKey)) {
            stations[stationKey].children.push(brands[brandKey]);
          }
        }
        
        // 机型层级
        if (center && station && brand && model && !models[modelKey]) {
          models[modelKey] = {
            value: modelKey,
            label: model,
            children: [],
            originalValue: model // 保存原始值
          };
          
          // 将机型添加到对应的品牌下
          if (brands[brandKey] && !brands[brandKey].children.some(child => child.value === modelKey)) {
            brands[brandKey].children.push(models[modelKey]);
          }
        }
        
        // 风机编号层级（最终层级）
        // 显示为equipmentCode，但值为equipmentId
        if (center && station && brand && model && equipmentCode && equipmentId) {
          // 为设备节点生成唯一值，结合所有层级信息和索引确保唯一性
          const equipmentKey = `equipment-${center}-${station}-${brand}-${model}-${equipmentId}-${index}`;
          
          const equipmentOption = {
            value: equipmentKey,        // 使用唯一键作为值
            label: equipmentCode,      // 显示为equipmentCode
            equipmentId: equipmentId,   // 保存设备ID
            originalValue: equipmentId  // 保存原始设备ID
          };
          
          // 将风机编号添加到对应的机型下
          if (models[modelKey] && !models[modelKey].children.some(child => child.value === equipmentKey)) {
            models[modelKey].children.push(equipmentOption);
          }
        }
      });
      
      // 将维保中心添加到设备选项中
      this.equipmentOptions = Object.values(centers);
    },

    // 获取显示标签，只显示第一个选中项，其余用省略号表示
    getDisplayLabel(nodes) {
      if (!nodes || nodes.length === 0) {
        return '';
      }
      
      // 如果只有一个选中项，直接显示
      if (nodes.length === 1) {
        return nodes[0].label;
      }
      
      // 如果有多个选中项，显示第一个项 + 省略号
      return nodes[0].label + '...';
    },

    resetFilter() {
      this.leftFormData.field1 = '';
      this.leftFormData.field2 = '';
      this.leftFormData.field3 = '';
      this.leftFormData.field4 = '';
      // 重置时间筛选
      this.startDate = '';
      this.endDate = '';
      this.selectedPeriod = '本月';
      this.selectPeriod('本月');
      // 重置维度筛选
      this.dimensionFilters = {
        location: {
          center: true,
          station: true
        },
        fan: {
          number: false,
          brand: false,
          model: false,
          system: false
        },
        type: {
          repair: true,
          maintenance: true
        },
        other: {
          repairman: false,
          manager: false,
          operator: false
        }
      };
      // 重置设备筛选
      this.selectedFilterCombination = [];
      this.selectedEquipment = [];
      this.selectedEquipmentNodes = [];
      this.queryParams.devices = null;
      this.equipmentKeyword = '';
      // 恢复原始选项
      if (this.originalEquipmentOptions) {
        this.equipmentOptions = JSON.parse(JSON.stringify(this.originalEquipmentOptions));
      }
      // 重置指标筛选
      this.indicatorFilters = {
        workorder: {
          workorder: true,
          restartNum: false,
        },
        workhour: {
          enabled: false,
          items: {
            tjsc: false,
            xfsc: false,
            xysc: false,
            zbsc: false,
            clsc: false,
            qjbwsc: false,
            gqsc: false
          }
        },
        score: {
          enabled: false
        }
      };
      // 重置选中的指标类别
      this.selectedIndicatorCategory = null;
      this.orderList = [];
      // 强制更新视图
      this.$forceUpdate();
      this.handleQuery();
    },
    hasOrderCode() {
      if (this.orderList.length>0) {
        for (let i=0;i<this.orderList.length;i++) {
          const orderI = this.orderList[i];
          if(!orderI.orderCode || orderI.orderCode == null || orderI.orderCode == '') {
            return false;
          }
        }
        return true;
      }
      return false;
    },
    changeWidth() {
      let num = 0;
      if (this.hasOrderCode()) {
        num += 2;
      }
      if (this.queryParams.code) {
        num += 1.5;
      }
      if (this.queryParams.brand) {
        num += 1;
      }
      if (this.queryParams.model) {
        num += 2;
      }
      if (this.queryParams.system) {
        num += 1;
      }
      if (this.queryParams.pcs) {
        num += 1.5;
      }
      if (this.queryParams.center && this.checkCenter()) {
        num += 2;
      }
      if (this.queryParams.workOrder || this.queryParams.repairOrder) {
        num += 1;
      }
      if (this.queryParams.repairPerson) {
        num += 1;
      }
      if (this.queryParams.chargePerson) {
        num += 1;
      }
      if (this.queryParams.operator) {
        num += 1;
      }
      if (this.queryParams.workOrderNum==1) {
        num += 1;
      }
      if (this.queryParams.repairOrderNum==1) {
        num += 1;
      }
      if (this.queryParams.restartNum==1) {
        num += 1;
      }
      if (this.queryParams.score==1) {
        num += 1;
      }
      if (this.queryParams.tjsc) {
        num += 1.5;
      }
      if (this.queryParams.xfsc) {
        num += 1.5;
      }
      if (this.queryParams.xysc) {
        num += 1.5;
      }
      if (this.queryParams.zbsc) {
        num += 1.5;
      }
      if (this.queryParams.clsc) {
        num += 1.5;
      }
      if (this.queryParams.qjbwsc) {
        num += 1.5;
      }
      if (this.queryParams.gqsc) {
        num += 1.5;
      }
      if(num==0) {
        return 0;
      }else{
        return Math.round(100/num);
      }
    },
    applyFilter() {
      if (this.startDate && this.endDate) {
        // 如果是选择的日期范围
        const start = new Date(this.startDate);
        start.setHours(0, 0, 0, 0);
        this.queryParams.startTime = this.formatDateTime(start);
        
        const end = new Date(this.endDate);
        end.setHours(23, 59, 59, 999);
        this.queryParams.endTime = this.formatDateTime(end);
      } else {
        // 其它情况设置为null
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }

      // 维度筛选
      this.queryParams.center = this.dimensionFilters.location.center;
      this.queryParams.pcs = this.dimensionFilters.location.station;
      this.queryParams.code = this.dimensionFilters.fan.number;
      if(this.queryParams.devices && this.queryParams.devices!=null && this.queryParams.devices!='') {
        this.queryParams.code = true;
      }else{
        this.queryParams.code = false;
      }
      this.queryParams.brand = this.dimensionFilters.fan.brand;
      this.queryParams.model = this.dimensionFilters.fan.model;
      this.queryParams.system = this.dimensionFilters.fan.system;
      this.queryParams.repairOrder = this.dimensionFilters.type.repair;
      this.queryParams.workOrder = this.dimensionFilters.type.maintenance;
      this.queryParams.repairPerson = this.dimensionFilters.other.repairman;
      this.queryParams.chargePerson = this.dimensionFilters.other.manager;

      // 指标筛选
      if (this.dimensionFilters.type.repair && this.indicatorFilters.workorder.workorder) {
        this.queryParams.repairOrderNum = 1;
      }else{
        this.queryParams.repairOrderNum = null;
      }
      if (this.dimensionFilters.type.maintenance && this.indicatorFilters.workorder.workorder) {
        this.queryParams.workOrderNum = 1;
      }else{
        this.queryParams.workOrderNum = null;
      }
      if (this.onlyWorkOrder) {
        this.queryParams.restartNum = null;
        this.queryParams.xfsc = null;
        this.queryParams.xysc = null;
        this.queryParams.zbsc = null;
      }else{
        this.queryParams.restartNum = this.indicatorFilters.workorder.restartNum ? 1 : null;
        this.queryParams.xfsc = this.indicatorFilters.workhour.items.xfsc;
        this.queryParams.xysc = this.indicatorFilters.workhour.items.xysc;
        this.queryParams.zbsc = this.indicatorFilters.workhour.items.zbsc;
      }
      if (this.queryParams.restartNum == 1) {
        this.queryParams.operator = this.dimensionFilters.other.operator;
      }else{
        this.queryParams.operator = null;
        this.dimensionFilters.other.operator = false;
      }
      this.queryParams.clsc = this.indicatorFilters.workhour.items.clsc;
      this.queryParams.qjbwsc = this.indicatorFilters.workhour.items.qjbwsc;
      this.queryParams.tjsc = this.indicatorFilters.workhour.items.tjsc;
      this.queryParams.gqsc = this.indicatorFilters.workhour.items.gqsc;
      if (this.indicatorFilters.score.enabled) {
        this.queryParams.score = 1;
      }else{
        this.queryParams.score = null;
      }
      if (this.indicatorFilters.workorder.restartNum && !this.indicatorFilters.workorder.workorder) {
        this.queryParams.repairPerson = null;
        this.dimensionFilters.other.repairman = false;
      }
      console.log(this.queryParams);
      
      getHomePageOrderListData(this.queryParams).then(response => {
        if (response.code === 200) {
          this.total = response.total;
          this.orderList = response.rows;
        }
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.applyFilter();
    },
    // 添加日期格式化方法
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 添加时间筛选相关方法
    selectPeriod(period) {
      this.selectedPeriod = period
      // 根据选择的时间段设置日期
      const now = new Date()
      switch (period) {
        case '本月':
          this.startDate = new Date(now.getFullYear(), now.getMonth(), 1)
          this.endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
          break
        case '上月':
          this.startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1)
          this.endDate = new Date(now.getFullYear(), now.getMonth(), 0)
          break
        case '本季度':
          const quarter = Math.floor(now.getMonth() / 3)
          this.startDate = new Date(now.getFullYear(), quarter * 3, 1)
          this.endDate = new Date(now.getFullYear(), (quarter + 1) * 3, 0)
          break
      }
    },
    // 维度筛选展开收起方法
    toggleFilter(type) {
      if (type === 'dimension') {
        this.dimensionExpanded = !this.dimensionExpanded;
      } else if (type === 'indicator') {
        this.indicatorExpanded = !this.indicatorExpanded;
      }
    },
    toggleTree(type) {
      this.treeExpanded[type] = !this.treeExpanded[type];
    },
    handleWorkorderToggle(val) {
      if (!this.dimensionFilters.type.repair && this.dimensionFilters.type.maintenance) {
        this.indicatorFilters.workhour.items.xfsc = false;
        this.indicatorFilters.workhour.items.xysc = false;
        this.indicatorFilters.workhour.items.zbsc = false;
        this.onlyWorkOrder = true;
      }else{
        this.onlyWorkOrder = false;
      }
    },
    handleWorkhourToggle(val) {
      // 当工时统计复选框状态改变时，同步更新所有子项的状态
      if (this.onlyWorkOrder) {
        this.indicatorFilters.workhour.items.xfsc = false;
        this.indicatorFilters.workhour.items.xysc = false;
        this.indicatorFilters.workhour.items.zbsc = false;
      }else{
        this.indicatorFilters.workhour.items.xfsc = val;
        this.indicatorFilters.workhour.items.xysc = val;
        this.indicatorFilters.workhour.items.zbsc = val;
      }
      this.indicatorFilters.workhour.items.tjsc = val;
      this.indicatorFilters.workhour.items.clsc = val;
      this.indicatorFilters.workhour.items.qjbwsc = val;
      this.indicatorFilters.workhour.items.gqsc = val;
      this.handleWorkhourSelect(val);
    },
    // 处理工单指标选择，实现互斥选择功能
    handleWorkorderSelect(val) {
      if (val) {
        // 如果选中了工单指标，则清空其他指标的选择
        this.clearOtherIndicators('workorder');
        this.selectedIndicatorCategory = 'workorder';
      } else if (this.selectedIndicatorCategory === 'workorder') {
        // 如果取消选中且当前选中的是工单指标，则清空选中类别
        this.selectedIndicatorCategory = null;
      }
    },
    // 处理工时指标选择，实现互斥选择功能
    handleWorkhourSelect(val) {
      if (val) {
        // 如果选中了工时指标，则清空其他指标的选择
        this.clearOtherIndicators('workhour');
        this.selectedIndicatorCategory = 'workhour';
      } else if (this.selectedIndicatorCategory === 'workhour') {
        // 如果取消选中且当前选中的是工时指标，则清空选中类别
        this.selectedIndicatorCategory = null;
      }
    },
    // 处理工分指标选择，实现互斥选择功能
    handleScoreSelect(val) {
      if (val) {
        // 如果选中了工分指标，则清空其他指标的选择
        this.clearOtherIndicators('score');
        this.selectedIndicatorCategory = 'score';
      } else if (this.selectedIndicatorCategory === 'score') {
        // 如果取消选中且当前选中的是工分指标，则清空选中类别
        this.selectedIndicatorCategory = null;
      }
    },
    // 清空除指定类别外的其他指标选择
    clearOtherIndicators(currentCategory) {
      if (currentCategory !== 'workorder') {
        this.indicatorFilters.workorder.workorder = false;
        this.indicatorFilters.workorder.restartNum = false;
      }
      if (currentCategory !== 'workhour') {
        this.indicatorFilters.workhour.enabled = false;
        // 同时清空工时子项
        Object.keys(this.indicatorFilters.workhour.items).forEach(key => {
          this.indicatorFilters.workhour.items[key] = false;
        });
      }
      if (currentCategory !== 'score') {
        this.indicatorFilters.score.enabled = false;
      }
    },
    formatScore(row, column, cellValue) {
      if (cellValue == null || cellValue === '') return '--'; // 处理空值
      return parseFloat(cellValue).toFixed(2); // 保留两位小数
    },
    // 格式化工时和工分显示，0显示为0，小数位超过两位时四舍五入
    formatWorkValue(value) {
      if (value == null || value === '') return '--'; // 处理空值
      const num = parseFloat(value);
      // 四舍五入保留两位小数
      const rounded = num.toFixed(2);
      // 去掉不必要的末尾0
      return parseFloat(rounded).toString();
    },
    handleExport() {
      this.download("gxt/order/exportHomePageOrderList", this.queryParams, `homePageOrderList_${new Date().getTime()}.xlsx`);
    },
    // 加载首页统计数据
    loadHomePageData() {
      selectHomePageData().then(response => {
        if (response.code === 200) {
          this.homePageData.workOrderNum = response.data.workOrderNum || 0;
          this.homePageData.workOrderJsy = response.data.workOrderJsy || 0;
          this.homePageData.repairOrderNum = response.data.repairOrderNum || 0;
          this.homePageData.repairOrderJsy = response.data.repairOrderJsy || 0;
          this.homePageData.repairRestartOrderNum = response.data.repairRestartOrderNum || 0;
          this.homePageData.wbgs = response.data.wbgs || 0;
          this.homePageData.wbjsy = response.data.wbjsy || 0;
          this.homePageData.score = response.data.score || 0;
          this.homePageData.gfjsy = response.data.gfjsy || 0;
          this.homePageData.repairPending = response.data.repairPending || 0;
          this.homePageData.workPending = 0;
          this.homePageData.pendingNum = this.homePageData.repairPending + this.homePageData.workPending;
          this.homePageData.hasCenter = response.data.hasCenter;
          this.homePageData.timeOutNum = response.data.timeOutNum;
        }
      });
      
      // 获取我的待办数量
      listMyTodo({ pageNum: 1, pageSize: 1 }).then(response => {
        if (response.code === 200) {
          this.homePageData.todoNum = response.total || 0;
        }
      });
    },
    getTextColor(jsy) {
      if(jsy>0) {
        return '#22c55e';
      }else if(jsy<0) {
        return '#ef4444';
      }else{
        return 'gray';
      }
    },
    toRoute(num) {
      if(num==0) {
        // 获取系统配置中的超时时间参数
        getConfigKey("gxt.order.timeout").then(response => {
          let timeoutValue = 30; // 默认值
          if (response && response.msg) {
            timeoutValue = parseInt(response.msg) || 30;
          }
          
          // 加密参数并传递到目标路由页面
          const params = {
            timeOutNum: timeoutValue,
            workOrderStatus: 'assigned'
          };
          const encryptedParams = encryptParams(params);
          this.$router.push({
            path: "/workOrder/repairOrder",
            query: {
              data: encryptedParams
            }
          });
        }).catch(() => {
          // 如果获取配置失败，使用默认值
          const params = {
            timeOutNum: 30,
            workOrderStatus: 'assigned'
          };
          const encryptedParams = encryptParams(params);
          this.$router.push({
            path: "/workOrder/repairOrder",
            query: {
              data: encryptedParams
            }
          });
        });
      }else if(num==1) {
        /*if(this.homePageData.repairPending>0 && this.homePageData.workPending==0) {
          const params = {
            userType: 'toBe'
          };
          const encryptedParams = encryptParams(params);
          this.$router.push({
            path: "/workOrder/repairOrder",
            query: {
              data: encryptedParams
            }
          });
        }else{
          this.$router.push("/workOrder/gxtOrder");
        }*/
        this.$router.push("/mine/orderMyTodo");
      }else if (num==2) {
        /*const params = {
          userType: 'toStart'
        };
        const encryptedParams = encryptParams(params);
        this.$router.push({
          path: "/workOrder/repairOrder",
          query: {
            data: encryptedParams
          }
        });*/
        this.$router.push("/mine/orderMyCreate");
      }else if (num==3) {
        /*const params = {
          userType: 'toHandle'
        };
        const encryptedParams = encryptParams(params);
        this.$router.push({
          path: "/workOrder/repairOrder",
          query: {
            data: encryptedParams
          }
        });*/
        this.$router.push("/mine/orderMyDone");
      }else{
        /*const params = {
          userType: 'toRelated'
        };
        const encryptedParams = encryptParams(params);
        this.$router.push({
          path: "/workOrder/repairOrder",
          query: {
            data: encryptedParams
          }
        });*/
        this.$router.push("/mine/orderMyRelate");
      }
    },
    checkCenter() {
      if (this.homePageData.hasCenter && this.homePageData.hasCenter=='yes') {
        return true;
      }
      return false;
    },
    filterEquipmentOptions() {
      // 根据关键字筛选设备选项
      if (!this.equipmentKeyword) {
        // 如果关键字为空，显示所有选项
        this.filteredEquipmentOptions = null;
        return;
      }
      
      // 保存原始选项
      if (!this.originalEquipmentOptions) {
        this.originalEquipmentOptions = JSON.parse(JSON.stringify(this.equipmentOptions));
      }
      
      // 根据关键字过滤选项
      this.filteredEquipmentOptions = this.filterOptionsByKeyword(this.originalEquipmentOptions, this.equipmentKeyword);
    },
    
    // 递归过滤选项
    filterOptionsByKeyword(options, keyword) {
      const filtered = [];
      
      options.forEach(option => {
        // 检查当前选项是否匹配关键字
        if (option.label.toLowerCase().includes(keyword.toLowerCase())) {
          // 如果匹配，直接添加整个选项（包括子项）
          filtered.push(option);
        } else if (option.children && option.children.length > 0) {
          // 如果当前选项不匹配，但有子项，递归过滤子项
          const filteredChildren = this.filterOptionsByKeyword(option.children, keyword);
          if (filteredChildren.length > 0) {
            // 如果子项中有匹配的，添加当前选项并更新子项
            const newOption = { 
              ...option, 
              children: filteredChildren 
            };
            filtered.push(newOption);
          }
        }
      });
      
      return filtered;
    },
    
    // 处理设备树形选择器选中变化
    handleEquipmentTreeCheck(data, checkedInfo) {
      // 保存选中的节点信息
      this.selectedEquipmentNodes = checkedInfo.checkedNodes;
      
      // 提取实际的设备ID用于selectedEquipment数组
      const actualEquipmentIds = checkedInfo.checkedNodes
        .filter(node => node.originalValue && (!node.children || node.children.length === 0)) // 只选择叶子节点（设备节点）
        .map(node => node.originalValue);
      
      // 更新selectedEquipment数组以保持与原逻辑兼容
      this.selectedEquipment = actualEquipmentIds;
      
      // 自动更新查询参数中的设备ID
      this.updateEquipmentQueryParams();
    },
    
    // 更新设备查询参数
    updateEquipmentQueryParams() {
      // 提取选中节点的实际设备ID（叶子节点）
      const selectedIds = this.selectedEquipmentNodes
        .filter(node => node.originalValue && (!node.children || node.children.length === 0)) // 只选择叶子节点（设备节点）
        .map(node => node.originalValue);
      
      // 将设备ID用逗号拼接成字符串存储到this.queryParams.devices
      this.queryParams.devices = selectedIds.length > 0 ? selectedIds.join(',') : null;
    },
    
    // 确认设备选择（保持向后兼容）
    confirmEquipmentSelection() {
      // 这个方法现在主要用于向后兼容，实际选择已经自动更新了
      this.updateEquipmentQueryParams();
    },
    
    resetEquipmentFilter() {
      // 重置设备筛选
      this.equipmentKeyword = '';
      this.filteredEquipmentOptions = null;
      this.selectedEquipment = [];
      this.selectedEquipmentNodes = []; // 同时重置选中的节点信息
      
      // 清空设备查询参数
      this.queryParams.devices = null;
      
      // 如果有设备树引用，清除选中状态
      if (this.$refs.equipmentTree) {
        this.$refs.equipmentTree.setCheckedKeys([]);
      }
    },
    handleWorkOrderClick(row) {
      // 记录来源路由和工单编码
      if (!row.orderCode) return;
      if (this.queryParams.score==1) {
        if (row.orderType=='维保工单') {
          sessionStorage.setItem('fromRoute', '/homePage/maintenance');
          sessionStorage.setItem('workOrderProjectNo', row.orderCode);
          // 跳转到工单评分页面
          this.$router.push({
            path: '/workScore/orderScore'
          });
        }else{
          // 记录来源路由和工单编码
          sessionStorage.setItem('fromRoute', '/homePage/repair');
          sessionStorage.setItem('workOrderProjectNo', row.orderCode);
          // 跳转到工单评分页面
          this.$router.push({
            path: '/workScore/orderScore'
          });
        }
      }else {
        if (row.orderType=='维保工单') {
          sessionStorage.setItem('fromRoute', '/workScore/monthScore');
          sessionStorage.setItem('workOrderProjectNo', row.orderCode);
          // 跳转到维保工单列表页面
          this.$router.push({
            path: '/workOrder/gxtOrder'
          });
        }else{
          // 记录来源路由和工单编码
          sessionStorage.setItem('fromRouteRepair', '/workScore/monthScore');
          sessionStorage.setItem('workOrderProjectNoRepair', row.orderCode);
          // 跳转到维保工单列表页面
          this.$router.push({
            path: '/workOrder/repairOrder'
          });
        }
      }
    }
  }
}
</script>

<style scoped>
.index4-container {
  display: flex;
  padding: 20px;
  min-height: calc(100vh - 84px);
  position: relative;
}

.left-form {
  width: 15%;
  box-sizing: border-box;
}

.right-content {
  width: 85%;
  display: flex;
  margin-left: 20px;
  flex-direction: column;
  gap: 20px;
}

.form-card {
  height: 100%;
}

.form-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.form-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 20px;
  width: 100%;
}

.form-button {
  text-align: center;
}

.filter-button {
  color: white;
  border: none;
  width: 100%;
  margin-bottom: 10px;
}

.filter-button:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.reset-button {
  background-color: #165dff;
}

.apply-button {
  background-color: #165dff;
}

/* 图标行样式 */
.icons-row {
  display: flex;
  justify-content: space-between;
}

.icon-item {
  width: 15%;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.icon-item-big {
  width: 17%;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.icon-item.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
  padding: 10px 0;
}

.icon-item-big.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
  padding: 10px 0;
}

.todo-content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin: 8px;
  gap: 10px;
}

.icon-content-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin: 8px;
  gap: 10px;
}

.icon-text-wrapper {
  text-align: left;
}

.icon-item:hover {
  transform: scale(1);
}

.icon-item-big:hover {
  transform: scale(1);
}

.icon-wrapper {
  position: relative;
}

.icon-circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  font-size: 18px;
  position: relative;
  margin: 10px;
}

.icon-size {
  width: 18px;
  height: 18px;
}

.blue-color {
  color: #165dff;
}

.green-color {
  color: #00b42a;
}

.purple-color {
  color: #a855f7;
}

.orange-color {
  color: #f97316;
}

.deep-yellow-color {
  color: #c98701;
}

.bg-color-blue {
  background-color: #dbeafe;
}

.bg-color-yellow {
  background-color: #fef9c3;
}

.bg-color-red {
  background-color: #fee2e2;
}

.bg-color-green {
  background-color: #dcfce7;
}

.bg-color-orange {
  background-color: #ffedd5;
}

.bg-color-purple {
  background-color: #f3e8ff;
}

.icon-label {
  font-size: 14px;
  color: #606266;
}

.badge {
  position: absolute;
  top: -3px;
  right: -3px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

/* 表单行样式 */
.forms-row {
  display: flex;
  justify-content: space-between;
}

.form-item {
  width: 24%; /* 留一些间距 */
}

.data-card {
  height: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3px;
}

.card-title {
  font-size: 14px;
}

.card-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.card-content {
  text-align: left;
  display: flex;
  align-items: center;
  gap: 10px;
}

.data-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
}

.data-description {
  font-size: 13px;
  color: #909399;
}

/* 列表行样式 */
.list-row {
  flex: 1;
}

.list-header {
  font-weight: bold;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 表头加粗 */
.el-table th {
  font-weight: bold !important;
}

/* 悬浮卡片通用样式 */
.floating-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.floating-card:hover {
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
}

/* 时间筛选标题样式 */
.time-filter-title {
  font-size: 16px;
  margin: 20px 0 10px 0;
  text-align: left;
  color: #303133;
}

/* 时间段按钮容器 */
.period-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

/* 时间段按钮样式 */
.period-button {
  flex: 1;
  padding: 5px;
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

/* 选中的时间段按钮样式 */
.period-button.active {
  background-color: #165dff;
  color: white;
  border-color: #165dff;
}

/* 日期选择器容器 */
.date-picker-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

/* 日期选择器 */
.date-picker {
  flex: 1;
}

/* 日期分隔符 */
.date-separator {
  margin: 0 3px;
  color: #606266;
}

/* 表单卡片调整 */
.form-card {
  height: auto;
}

/* 维度筛选样式 */
.filter-card {
  background: white;
  border-radius: 8px;
}

/* 修改复选框选中时的颜色 */
.el-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #165dff;
  border-color: #165dff;
}

.tree-select {
  margin-bottom: 0px;
}

.tree-header {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 3px 0;
  cursor: pointer;
  user-select: none;
}

.tree-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

.tree-content.show {
  max-height: 500px;
  transition: max-height 0.3s ease-in;
}

.checkbox-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-input {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.rotate-90 {
  transform: rotate(-90deg);
}

.rotate-180 {
  transform: rotate(180deg);
}

.hidden {
  display: none;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mt-1 {
  margin-top: 0.25rem;
}

.pl-2 {
  padding-left: 0.5rem;
}

.border-l-2 {
  border-left-width: 2px;
}

.border-neutral-200 {
  border-color: #e5e5e5;
}

.cursor-pointer {
  cursor: pointer;
}

.font-semibold {
  font-weight: 600;
}

.font-medium {
  font-weight: 100;
}

.text-lg {
  font-size: 1.125rem;
}

.text-neutral-700 {
  color: #404040;
}

.text-neutral-400 {
  color: #a3a3a3;
}

.transition-transform {
  transition: transform 0.3s ease;
}

.duration-300 {
  transition-duration: 300ms;
}

.flex-1 {
  flex: 1 1 0%;
}

/* 设备树形选择器弹出框样式 */
.equipment-tree-popover {
  padding: 0;
}

/* 设备树形选择器输入框样式 */
.filter-select :deep(.el-input.is-disabled .el-input__inner) {
  background-color: #fff;
  cursor: pointer;
}
</style>