<template>
  <div class="user-score-container-wrapper">
    <div class="user-score-container">
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="content-header">
      <h1 class="page-title">月度工分汇总<span v-if="!isList" class="dept-name">-{{ monthScore.deptName }}</span></h1>
      <el-select v-if="!isList" style="width: 150px;" v-model="selectedMonth" placeholder="请选择月份" @change="handleMonthChange">
        <el-option
          v-for="item in monthOptions"
          :key="item.value"
          :value="item.value"
          :label="item.label">
          <span style="margin-left: 15px;">{{ item.label }}</span>
        </el-option>
      </el-select>
    </div>

    <!-- 场站列表 -->
    <el-card v-if="isList" class="card-form" shadow="hover">
      <div style="margin-bottom: 15px;">
        <el-row :gutter="20">
          <el-col :span="4">
            <div style="font-size: 15px;font-weight: bold;margin-bottom: 5px;">维保中心</div>
            <el-input
              v-model="queryParams.parentName"
              style="width: 100%;"
              placeholder="请输入维保中心"
              @keyup.enter="handleStatusChange"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <div style="font-size: 15px;font-weight: bold;margin-bottom: 5px;">场站</div>
            <el-input 
              v-model="queryParams.deptName"
              style="width: 100%;"
              placeholder="请输入场站"
              @keyup.enter="handleStatusChange"
              clearable
            />
          </el-col>
          <el-col :span="3">
            <div style="font-size: 15px;font-weight: bold;margin-bottom: 5px;">月份</div>
            <el-date-picker
              v-model="queryParams.monthPeriod"
              type="month"
              placeholder="请选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              style="width: 100%;"
              @change="handleStatusChange"
            />
          </el-col>
          <el-col :span="3">
            <div style="font-size: 15px;font-weight: bold;margin-bottom: 5px;">状态</div>
            <el-select 
              v-model="queryParams.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px;margin-right: 20px;"
              @change="handleStatusChange"
            >
              <el-option style="margin-left: 10px;" label="未提交" :value="0"></el-option>
              <el-option style="margin-left: 10px;" label="反馈待处理" :value="1"></el-option>
              <el-option style="margin-left: 10px;" label="待终审" :value="2"></el-option>
              <el-option style="margin-left: 10px;" label="完成" :value="3"></el-option>
            </el-select>
          </el-col>
          <!-- 添加的两个靠右按钮 -->
          <el-col :span="10" style="display: flex; justify-content: flex-end; align-items: flex-end;">
            <el-button style="padding: 5px 15px;" icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button style="padding: 5px 15px;" type="primary" icon="Search" @click="handleStatusChange">搜索</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="form-content">
        <el-table :data="departmentStats" style="width: 100%">
          <el-table-column prop="parentName" label="维保中心"></el-table-column>
          <el-table-column prop="deptName" label="场站"></el-table-column>
          <el-table-column prop="monthPeriod" label="汇总月份"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <span v-if="!row.status || row.status == null || row.status == 0" style="color: grey;">未提交</span>
              <span v-else-if="row.status == 1" style="color: orange;">反馈待处理</span>
              <span v-else-if="row.status == 2" style="color: blue;">待终审</span>
              <span v-else-if="row.status == 3" style="color: green;">完成</span>
              <span v-else>未知状态</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-tag type="primary" @click="handleReview(scope.row)" style="cursor: pointer;padding: 5px 10px;margin-right: 10px;">查看</el-tag>
              <el-tag v-hasPermi="['gxt:scoresummary:second']" v-if="scope.row.status==1" type="warning" @click="handleReview(scope.row)" style="cursor: pointer;padding: 5px 10px;margin-right: 10px;">处理反馈</el-tag>
              <el-tag v-hasPermi="['gxt:scoresummary:third']" v-if="scope.row.status==2" type="danger" @click="handleReview(scope.row)" style="cursor: pointer;padding: 5px 10px;">终审</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination style="margin-top: 20px;"
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>
    
    <!-- 第一个表单：本月维保工单统计 -->
    <el-card v-if="!isList" class="card-form" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">本月维保工单统计</span>
      </div>
      <div class="form-content">
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">计划维保台数</div>
              <el-input-number 
                v-model="maintenanceOrderStats.plannedCount" 
                :min="0"
                :readonly="!hasFirst()"
                controls-position="right" 
                class="full-width-input"
              ></el-input-number>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">实际维保台数</div>
              <el-input-number 
                v-model="maintenanceOrderStats.actualCount" 
                :min="0"
                :readonly="!hasFirst()"
                controls-position="right" 
                class="full-width-input"
              ></el-input-number>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">全组扣分</div>
              <el-input 
                v-model="maintenanceOrderStats.groupDeduction" 
                readonly
              ></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">
                <el-tooltip placement="top" effect="light">
                  <template #content>
                    <el-tag style="padding: 5px;" v-if="monthScore.coefficientScore.status==2" type="danger">取消扣分申请已拒绝</el-tag>
                    <el-tag style="padding: 5px;" v-else-if="monthScore.coefficientScore.status==1" type="success">取消扣分申请已通过</el-tag>
                    <el-tag style="padding: 5px;" v-else type="primary">全组扣分未处理</el-tag>
                  </template>
                  <span style="cursor: pointer;">说明<span v-if="isRemarksRequired" class="required-mark">*</span></span>
                </el-tooltip>
              </div>
              <el-input 
                v-model="maintenanceOrderStats.explainCode" 
                :readonly="!hasFirst()"
                maxlength="50"
                :class="{ 'required-field': isRemarksRequired }"
                placeholder="输入说明(限制50字以内)"
              ></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">维保工单系数</div>
              <el-input-number 
                v-model="maintenanceOrderStats.workOrderCoefficient" 
                :min="0.8"
                :max="1.2"
                :step="0.1"
                :controls="true"
                :readonly="!hasThird()"
                controls-position="right"
                class="full-width-input"
              ></el-input-number>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistic-item">
              <div class="statistic-label">维修工单系数</div>
              <el-input-number 
                v-model="maintenanceOrderStats.repairOrderCoefficient" 
                :min="0.5"
                :max="1.5"
                :step="0.1"
                :controls="true"
                :readonly="!hasThird()"
                controls-position="right"
                class="full-width-input"
              ></el-input-number>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 第二和第三个表单在同一行 -->
    <el-row v-if="!isList" :gutter="20">
      <!-- 第二个表单：非停设备统计 -->
      <el-col :span="12">
        <el-card class="card-form-left" shadow="hover">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">设备连续运行时长情况</span>
          </div>
          <div class="form-content" style="margin-top: 20px;">
            <!-- 非停设备统计表格 -->
            <el-table :data="runtimeList" style="width: 100%">
              <el-table-column prop="runtimeRange" label="运行天数"></el-table-column>
              <el-table-column label="风机数量">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.deviceCount" 
                    :min="0"
                    controls-position="right" 
                    readonly
                    class="full-width-input"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <!-- 第三个表单：维保机型类型统计 -->
      <el-col :span="12">
        <el-card class="card-form-right" shadow="hover">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">本月维保机型类型统计</span>
          </div>
          <div class="form-content" style="margin-top: 20px;">
            <!-- 维保机型类型统计表格 -->
            <el-table :data="fanInspectionScoreList" style="width: 100%">
              <el-table-column prop="model" label="机型"></el-table-column>
              <el-table-column prop="inspectionType" label="维保类型"></el-table-column>
              <el-table-column label="维保数量">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.deviceCount" 
                    :min="0" 
                    controls-position="right" 
                    readonly
                    class="full-width-input"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 第四个表单：维修工单详情 -->
    <el-card v-if="!isList" class="card-form" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">本月维修工单统计</span>
      </div>
      <div class="form-content" style="margin-top: 20px;">
        <!-- 维修工单详情表格 -->
        <el-table :data="repairOrderStatistics" style="width: 100%">
          <el-table-column prop="repairType" label="检修类型" width="400"></el-table-column>
          <el-table-column label="工单数量">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.orderCount" 
                :min="0" 
                controls-position="right" 
                readonly
                class="full-width-input"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 第五个表单：组员考核得分 -->
    <el-card v-if="!isList" class="card-form" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">组员考核得分</span>
      </div>
      <div class="form-content" style="margin-top: 20px;">
        <!-- 组员考核得分表格 -->
        <el-table :data="userScoreList" style="width: 100%">
          <el-table-column prop="nickName" label="组员姓名"></el-table-column>
          <el-table-column label="维保工分">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.maintenanceTotalScore" 
                controls-position="right" 
                readonly
                class="full-width-input"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="维修工分">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.repairTotalScore" 
                controls-position="right" 
                readonly
                class="full-width-input"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="总工分">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.finalScore" 
                controls-position="right" 
                readonly
                class="full-width-input"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-card v-if="!isList && !hasFirst()" class="card-form" shadow="hover">
      <div slot="header" class="clearfix">
        <el-tooltip placement="top" effect="light">
          <template #content>
            <el-tag style="padding: 5px;" v-if="monthScore.coefficientScore.status==2" type="danger">取消扣分申请已拒绝</el-tag>
            <el-tag style="padding: 5px;" v-else-if="monthScore.coefficientScore.status==1" type="success">取消扣分申请已通过</el-tag>
            <el-tag style="padding: 5px;" v-else type="primary">全组扣分未处理</el-tag>
          </template>
          <span style="font-weight: bold;margin-right: 20px;">评分更改说明</span>
        </el-tooltip>
      </div>
      <div class="form-content">
        <el-form style="margin-top: 20px;">
          <el-form-item>
            <el-input
              type="textarea"
              style="width: 100%"
              :rows="4"
              placeholder="请输入评分更改的详细说明"
              v-model="monthScore.feedbackContent"
              maxlength="200"
              readonly
              show-word-limit>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 底部按钮 -->
    <div v-if="!isList" class="button-group">
      <el-button v-hasPermi="['gxt:scoresummary:second','gxt:scoresummary:third']" @click="handleCancel">返回</el-button>
      <el-button v-if="hasFirst()" @click="handleFeedback">反馈</el-button>
      <el-button v-if="hasFirst()" @click="handleSubmit">提交评分</el-button>
      <el-button v-if="hasSecond()" @click="agreeFeedBack">取消全组扣分</el-button>
      <el-button v-if="hasSecond()" @click="againstFeedBack">拒绝取消扣分</el-button>
      <el-button v-if="hasThird()" @click="submitCoefficient">提交本月系数</el-button>
    </div>
  </div>
  </div>
  
  <!-- 评分反馈弹窗 -->
  <el-dialog
    class="force-center-dialog"
    title="评分反馈"
    v-model="feedbackDialogVisible"
    width="650px"
    :before-close="handleFeedbackDialogClose">
    <div class="header-divider"></div>
    <el-form label-position="top">
      <el-form-item label="评分更改说明">
        <el-input
          type="textarea"
          style="width: 100%"
          :rows="4"
          placeholder="请输入评分更改的详细说明（必填）"
          v-model="monthScore.feedbackContent"
          maxlength="200"
          show-word-limit>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="end-divider"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button class="button-ex" @click="handleFeedbackCancel">取消</el-button>
        <el-button v-if="hasFirst" class="button-ex" type="primary" @click="handleFeedbackSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { checkPermi } from '@/utils/permission'
import { getScoreSummary, getSummaryMonths, submitMonthScore, getMonthScoreList } from '@/api/gxt/userScore'
import { useDict } from '@/utils/dict'
import { el } from 'element-plus/es/locales.mjs';

export default {
  name: 'ScoreSummary',
  data() {
    return {
      isList: true,
      isInfo:false,
      monthScore: {
        status: 0,
        deptId: 0,
        feedbackContent: '' // 添加feedbackContent属性
      },
      selectedMonth: null, // 默认选中的月份
      monthOptions: [], // 月份选项
      statusFilter: null, // 状态筛选
      // 新增的部门统计数据
      departmentStats: [],
      // 字典数据
      gxtInspectionType: [], // 维保类型字典
      gxtMaintenanceType: [], // 维保类型字典
      // 本月维保工单统计数据
      maintenanceOrderStats: {
        plannedCount: 0,
        actualCount: 0,
        groupDeduction: 0,
        explainCode: '',
        workOrderCoefficient: 1,
        repairOrderCoefficient: 1
      },
      // 非停设备统计数据
      runtimeList: [],
      // 维保机型类型统计数据
      fanInspectionScoreList: [],
      // 维修工单详情数据
      repairOrderStatistics: [],
      // 组员考核得分数据
      userScoreList: [],
      // 评分反馈弹窗相关数据
      feedbackDialogVisible: false,
      total:0,
      queryParams: {
        status: null,
        statusList: null,
        pageNum: 1,
        pageSize: 10,
        deptName: null,
        parentName: null,
        monthPeriod: null
      }
    }
  },
  created() {
    this.initMonthOptions(0,null);
    this.initDict();
  },
  computed: {
    // 计算说明输入框是否必填
    isRemarksRequired() {
      // 当实际维保台数小于计划维保台数时，说明输入框为必填
      const planned = parseInt(this.maintenanceOrderStats.plannedCount) || 0;
      const actual = parseInt(this.maintenanceOrderStats.actualCount) || 0;
      return actual < planned;
    }
  },
  watch: {
    // 监听路由变化，当路由参数发生变化时重新加载数据
    '$route'() {
      // 如果是从其他页面返回到当前页面，重新加载数据
      if(this.$route.name=='ScoreSummary') {
        this.handleStatusChange();
      }
    },
    // 监听 plannedCount 或 actualCount 的变化
    'maintenanceOrderStats.plannedCount': 'calculateDeduction',
    'maintenanceOrderStats.actualCount': 'calculateDeduction'
  },
  methods: {
    // 判断选择的月份是否小于当前月份
    isMonthLessThanCurrent(month) {
      if (!month) return false;
      const selectedDate = new Date(month + '-01');
      const currentDate = new Date();
      // 设置为当月的第一天，便于比较
      currentDate.setDate(1);
      currentDate.setHours(0, 0, 0, 0);
      return selectedDate < currentDate;
    },
    hasFirst() {
      return this.monthScore.status === 0 && checkPermi(['gxt:scoresummary:first']) && this.isMonthLessThanCurrent(this.selectedMonth);
    },
    hasSecond() {
      return this.monthScore.status === 1 && checkPermi(['gxt:scoresummary:second']) && this.isMonthLessThanCurrent(this.selectedMonth);
    },
    hasThird() {
      return this.monthScore.status === 2 && checkPermi(['gxt:scoresummary:third']) && this.isMonthLessThanCurrent(this.selectedMonth);
    },
    calculateDeduction() {
      const { plannedCount, actualCount } = this.maintenanceOrderStats;
      // 当计划值大于实际值时，计算差值；否则清空
      if (plannedCount > actualCount) {
        this.maintenanceOrderStats.groupDeduction = plannedCount - actualCount;
      } else {
        this.maintenanceOrderStats.groupDeduction = 0; // 或设为 0
      }
    },
    handlePagination() {
      this.fetchScoreSummaryData(this.selectedMonth, this.monthScore.deptId);
    },
    handleReview(row) {
      const rtType = this.isInfo ? 1 : 0;
      getScoreSummary(row.monthPeriod, rtType, row.deptId).then(response => {
        if (response.code === 200 && response.monthScore) {
          // 使用router.push方法替代tab.openPage避免页面切换问题
          this.$router.push({ path: '/gxt/userScore/info/' + response.monthScore.id });
        }
      });
    },
    // 根据inspectionTypeId获取inspectionType标签
    getInspectionTypeLabel(inspectionTypeId) {
      if (!inspectionTypeId) return '';
      
      const dictItem = this.gxtInspectionType.find(item => item.value === inspectionTypeId.toString());
      return dictItem ? dictItem.label : '';
    },
    getMaintenanceTypeLabel(maintenanceTypeId) {
      if (!maintenanceTypeId) return '';
      
      const dictItem = this.gxtMaintenanceType.find(item => item.value === maintenanceTypeId.toString());
      return dictItem ? dictItem.label : '';
    },
    
    // 初始化字典数据
    initDict() {
      const { gxt_inspection_type, gxt_maintenance_type } = useDict("gxt_inspection_type", "gxt_maintenance_type")
      this.gxtInspectionType = gxt_inspection_type || []
      this.gxtMaintenanceType = gxt_maintenance_type || []
      if(!checkPermi(['gxt:scoresummary:second']) && !checkPermi(['gxt:scoresummary:third'])) {
        this.isList = false;
      }
    },
    // 初始化月份选项
    initMonthOptions(param,monthParam) {
      // 从后端接口获取月份选项数据
      getSummaryMonths(param).then(response => {
        if (response.code === 200) {
          this.monthOptions = response.dictList || [];
          
          // 如果有月份选项数据，设置默认选中第一个
          if (this.monthOptions.length > 0) {
            if(monthParam && monthParam!=null) {
              this.selectedMonth = monthParam;
            }else{
              this.selectedMonth = this.monthOptions[0].value;
            }
            // 获取默认月份的数据
            this.fetchScoreSummaryData(this.selectedMonth,param);
          }
        } else {
          console.error('获取月份选项数据失败:', response.msg);
          // 如果获取失败，使用原有的默认逻辑
          this.initDefaultMonthOptions();
        }
      }).catch(error => {
        console.error('获取月份选项数据异常:', error);
        // 如果获取异常，使用原有的默认逻辑
        this.initDefaultMonthOptions();
      });
    },

    getLastMonth() {
      const date = new Date();
      date.setMonth(date.getMonth() - 1); // 设置为上一个月
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要 +1
      return `${year}-${month}`;
    },
    
    // 获取月度工分汇总数据
    fetchScoreSummaryData(monthPeriod,deptParam) {
      this.feedbackDialogVisible = false;
      if(this.isList) {
        this.selectedMonth = this.getLastMonth();
        getMonthScoreList(this.queryParams).then(response => {
          if (response.code === 200) {
            this.departmentStats = response.rows;
            this.total = response.total;
          }else{
            this.departmentStats = [];
          }
        }).catch(error => {
          console.error('获取月度工分列表数据异常:', error);
          this.departmentStats = [];
        });
        return;
      }
      // 根据权限设置rtType参数
      const rtType = this.isInfo ? 1 : 0;
      
      getScoreSummary(monthPeriod, rtType, deptParam).then(response => {
        if (response.code === 200 && response.monthScore) {
          const monthScoreGet = response.monthScore;
          this.monthScore = monthScoreGet;
          if(this.monthScore.status==4) {
            this.$message.warning('当前用户所属部门非场站，无法生成月度工分汇总数据！');
          }
          // console.log(monthScoreGet);
          
          // 设置本月维保工单统计数据
          if (monthScoreGet.coefficientScore) {
            this.maintenanceOrderStats = monthScoreGet.coefficientScore;
          }
          
          // 设置非停设备统计数据
          if (monthScoreGet.monthRuntimes) {
            this.runtimeList = monthScoreGet.monthRuntimes;
          }
          
          // 设置维保机型类型统计数据
          if (monthScoreGet.monthFanInspections) {
            this.fanInspectionScoreList = monthScoreGet.monthFanInspections.map(item => {
              return {
                model: item.model,
                inspectionType: this.getInspectionTypeLabel(item.inspectionTypeId), // 从字典中获取
                deviceCount: item.deviceCount || 0
              };
            });
          }
          
          // 设置维修工单详情数据
          if (monthScoreGet.monthRepairProjects) {
            this.repairOrderStatistics = monthScoreGet.monthRepairProjects.map(item => {
              return {
                repairType: this.getMaintenanceTypeLabel(item.maintenanceType),
                orderCount: item.orderCount || 0
              };
            });
          }
          
          // 设置组员考核得分数据
          if (monthScoreGet.userScores) {
            console.log(monthScoreGet.userScores);
            this.userScoreList = monthScoreGet.userScores;
          }
          this.checkPermissions();
        } else {
          console.error('获取月度工分汇总数据失败:', response.msg);
        }
      }).catch(error => {
        console.error('获取月度工分汇总数据异常:', error);
      });
    },
    
    // 处理月份变化
    handleMonthChange(value) {
      // console.log('选择的月份:', value);
      // 获取选择月份的数据
      this.fetchScoreSummaryData(value,this.monthScore.deptId);
    },
    
    // 处理取消按钮点击事件
    handleCancel() {
      // console.log('返回按钮被点击')
      this.isList = true;
      this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      // 在这里添加取消操作的逻辑
    },
    
    // 处理反馈按钮点击事件
    handleFeedback() {
      // console.log('反馈按钮被点击')
      // 只有当isFirst为true时才显示弹窗
      const planned = parseInt(this.maintenanceOrderStats.plannedCount) || 0;
      const actual = parseInt(this.maintenanceOrderStats.actualCount) || 0;
      if(actual < planned && this.maintenanceOrderStats.explainCode=='') {
        this.$message.warning('请输入全组扣分说明');
        return;
      }
      this.feedbackDialogVisible = true;
    },
    
    // 处理提交评分按钮点击事件
    handleSubmit() {
      // console.log('提交评分按钮被点击')
      if(this.monthScore.status != 0) {
        this.$message.warning('请勿重复提交评分！');
        return;
      }
      // 在这里添加提交评分操作的逻辑
      this.monthScore.previousStatus = this.monthScore.status;
      this.monthScore.status = 2;
      this.monthScore.coefficientScore = this.maintenanceOrderStats;
      submitMonthScore(this.monthScore).then(response => {
        if (response.code === 200) {
          this.$message.success('评分提交成功！');
          this.checkPermissions();
        } else {
          this.$message.error(response.msg)
          this.monthScore.status = this.monthScore.previousStatus;
        }
        this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      }).catch(error => {
        console.error('评分提交失败:', error)
        this.$message.error('评分提交失败，请查看控制台错误信息')
        this.monthScore.status = this.monthScore.previousStatus;
      })
    },

    agreeFeedBack() {
      // console.log('通过反馈按钮被点击')
      if(this.monthScore.status != 1) {
        this.$message.warning('反馈已审核，请勿重复操作！');
        return;
      }
      // 在这里添加提交评分操作的逻辑
      this.monthScore.previousStatus = this.monthScore.status;
      this.monthScore.status = 2;
      this.maintenanceOrderStats.status = 1;
      this.monthScore.coefficientScore = this.maintenanceOrderStats;
      submitMonthScore(this.monthScore).then(response => {
        if (response.code === 200) {
          this.$message.success('取消全组扣分成功！');
          this.checkPermissions();
        } else {
          this.$message.error(response.msg)
          this.monthScore.status = this.monthScore.previousStatus;
        }
        this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      }).catch(error => {
        console.error('审核提交失败:', error)
        this.$message.error('审核提交失败，请查看控制台错误信息')
        this.monthScore.status = this.monthScore.previousStatus;
      })
    },

    againstFeedBack() {
      // console.log('不通过反馈按钮被点击')
      if(this.monthScore.status != 1) {
        this.$message.warning('反馈已审核，请勿重复操作！');
        return;
      }
      // 在这里添加提交评分操作的逻辑
      this.monthScore.previousStatus = this.monthScore.status;
      this.monthScore.status = 2;
      this.maintenanceOrderStats.status = 2;
      this.monthScore.coefficientScore = this.maintenanceOrderStats;
      submitMonthScore(this.monthScore).then(response => {
        if (response.code === 200) {
          this.$message.success('审核提交成功！');
          this.checkPermissions();
        } else {
          this.$message.error(response.msg)
          this.monthScore.status = this.monthScore.previousStatus;
        }
        this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      }).catch(error => {
        console.error('审核提交失败:', error)
        this.$message.error('审核提交失败，请查看控制台错误信息')
        this.monthScore.status = this.monthScore.previousStatus;
      })
    },

    submitCoefficient() {
      // console.log('主任提交本月系数按钮被点击')
      if(this.monthScore.status != 2) {
        this.$message.warning('系数已提交，请勿重复操作！');
        return;
      }
      // 在这里添加提交评分操作的逻辑
      this.monthScore.previousStatus = this.monthScore.status;
      this.monthScore.status = 3;
      this.monthScore.coefficientScore = this.maintenanceOrderStats;
      submitMonthScore(this.monthScore).then(response => {
        if (response.code === 200) {
          this.$message.success('系数提交成功！');
          this.checkPermissions();
        } else {
          this.$message.error(response.msg)
          this.monthScore.status = this.monthScore.previousStatus;
        }
        this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      }).catch(error => {
        console.error('系数提交失败:', error)
        this.$message.error('系数提交失败，请查看控制台错误信息')
        this.monthScore.status = this.monthScore.previousStatus;
      })
    },
    
    // 初始化默认月份选项（原有逻辑）
    initDefaultMonthOptions() {
      const now = new Date();
      // 获取上个月
      const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      
      // 生成最近6个月的选项（包括本月）
      this.monthOptions = [];
      for (let i = 0; i < 6; i++) {
        const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const value = `${year}-${month}`;
        const label = `${year}年${month}月`;
        
        this.monthOptions.push({
          value: value,
          label: label
        });
      }
      
      // 设置默认选中为上个月
      const defaultYear = lastMonth.getFullYear();
      const defaultMonth = String(lastMonth.getMonth() + 1).padStart(2, '0');
      this.selectedMonth = `${defaultYear}-${defaultMonth}`;
      
      // 获取默认月份的数据
      this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
    },
    
    // 检查权限
    checkPermissions() {
      this.isInfo = checkPermi(['gxt:scoresummary:first']) || checkPermi(['gxt:scoresummary:second']) || checkPermi(['gxt:scoresummary:third']);
    },
    
    // 处理反馈弹窗关闭
    handleFeedbackDialogClose(done) {
      // 清空反馈内容
      this.monthScore.feedbackContent = '';
      done();
    },
    
    // 处理反馈弹窗取消按钮
    handleFeedbackCancel() {
      this.feedbackDialogVisible = false;
      // 清空反馈内容
      this.monthScore.feedbackContent = '';
    },
    resetQuery() {
      this.queryParams = {
        status: null,
        statusList: null,
        pageNum: 1,
        pageSize: 10,
        deptName: null,
        parentName: null,
        monthPeriod: null
      };
      this.handleStatusChange();
    },
    
    // 处理反馈弹窗提交按钮
    handleFeedbackSubmit() {
      if(this.monthScore.status != 0) {
        this.$message.warning('请勿重复提交反馈！');
        return;
      }
      // 添加验证逻辑，确保用户输入了反馈内容
      if (!this.monthScore.feedbackContent || this.monthScore.feedbackContent.trim() === '') {
        this.$message.warning('请输入评分更改说明');
        return;
      }
      // console.log('提交反馈:', this.monthScore.feedbackContent);
      this.monthScore.previousStatus = this.monthScore.status;
      this.monthScore.status = 1;
      this.monthScore.coefficientScore = this.maintenanceOrderStats;
      submitMonthScore(this.monthScore).then(response => {
        if (response.code === 200) {
          this.$message.success('反馈提交成功！');
          this.checkPermissions();
        } else {
          this.$message.error(response.msg)
          this.monthScore.status = this.monthScore.previousStatus;
        }
        this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      }).catch(error => {
        console.error('反馈提交失败:', error)
        this.$message.error('反馈提交失败，请查看控制台错误信息')
        this.monthScore.status = this.monthScore.previousStatus;
      })
      // 提交后关闭弹窗
      this.feedbackDialogVisible = false;
    },
    
    // 处理状态筛选变化
    handleStatusChange(value) {
      console.log('状态筛选变化:', this.queryParams);
      this.queryParams.pageNum = 1;
      this.fetchScoreSummaryData(this.selectedMonth,this.monthScore.deptId);
      // 在这里可以添加根据状态筛选数据的逻辑
      // 例如：重新加载部门统计数据或其他相关操作
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Inter', sans-serif;
}

.user-score-container-wrapper {
  position: relative;
  height: 100%;
}

.user-score-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 页面头部样式 */
.content-header {
  padding: 1.2rem 2rem;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: #2d3748;
  margin: 0;
}

.dept-name {
  font-size: 1.4rem;
  font-weight: 600;
  color: #2d3748;
  font-style: normal;
}

.card-form {
  border-radius: 10px; /* 统一圆角半径 */
  margin-top: 20px;
  margin-bottom: 0px;
  margin-left: 20px;
  margin-right: 20px;
}

.card-form-left {
  border-radius: 10px; /* 统一圆角半径 */
  margin-top: 20px;
  margin-bottom: 0px;
  margin-left: 20px;
  margin-right: 0px;
}

.card-form-right {
  border-radius: 10px; /* 统一圆角半径 */
  margin-top: 20px;
  margin-bottom: 0px;
  margin-left: 0px;
  margin-right: 20px;
}

.button-group {
  display: flex;
  justify-content: right;
  gap: 10px;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 10px;
}

.button-group .el-button {
  background-color: #165dff; /* 蓝色背景 */
  color: white;             /* 白色文字 */
  border: none;             /* 去掉默认边框 */
  border-radius: 4px;       /* 圆角（可调整） */
  padding: 10px 15px;            /* 内边距 */
  cursor: pointer;          /* 鼠标悬停时显示手型 */
  font-size: 14px;          /* 可选：调整字体大小 */
}

/* 可选：悬停效果 */
.button-group .el-button:hover {
  opacity: 0.9;             /* 悬停时略微变透明 */
  /* 或者用更深蓝色：background-color: #1450d9; */
}

/* 统计项样式 */
.statistic-item {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ccc; /* 宽度 | 样式 | 颜色 */
}

.statistic-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

/* 输入框样式 - 占据100%宽度并左对齐数字 */
.full-width-input {
  width: 100% !important;
}

:deep(.full-width-input .el-input__inner) {
  text-align: left !important;
}

/* 数字输入框字体变大 */
.large-number-input {
  font-size: 16px !important;
}

:deep(.large-number-input .el-input__inner) {
  font-size: 16px !important;
  text-align: left !important;
}

/* 更高的输入框以适配大字体 */
.taller-input {
  height: 30px !important;
}

:deep(.taller-input .el-input__inner) {
  height: 40px !important;
  line-height: 40px !important;
}


:deep(.taller-input .el-input__suffix) {
  height: 40px !important;
  line-height: 40px !important;
}

:deep(.taller-input .el-input-number__decrease) {
  height: calc(100% - 2px) !important;
  line-height: calc(40px / 2) !important;
}

:deep(.taller-input .el-input-number__increase) {
  height: calc(100% - 2px) !important;
  line-height: calc(40px / 2) !important;
}

/* 必填项标记样式 */
.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

/* 必填项输入框样式 */
.required-field :deep(.el-input__inner) {
  border-color: #f56c6c !important;
}
/* 使用 :deep() 穿透 scoped 样式 */
:deep(.force-center-dialog) {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  font-weight: bold;
}

.header-divider {
  height: 0.1px;
  background-color: #ddd; /* Element Plus 默认灰色 */
  margin-bottom: 12px;
}

.end-divider {
  height: 0.1px;
  background-color: #ddd; /* Element Plus 默认灰色 */
  margin-top: 12px;
}

.button-ex {
  padding: 10px 15px;            /* 内边距 */
}
</style>
