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

    <!-- 主要内容区域 -->
    <div class="content-wrapper">
      <!-- 工分复核模块 -->
      <div class="module-container">
        <div class="module-header">
          <h2 class="module-subtitle">工分复核列表</h2>
        </div>
        
        <div class="tab-content active">
          <div class="table-responsive">
            <el-table :data="scoreReviewList" class="data-table" v-loading="loading" :row-class-name="tableRowClassName">
              <el-table-column prop="userName" label="被评人" header-align="center" align="center" />
              <el-table-column prop="monthPeriod" label="月份" header-align="center" align="center" />
              <el-table-column prop="maintenanceTotalScore" label="维保工单分" header-align="center" align="center" />
              <el-table-column prop="repairTotalScore" label="维修工单分" header-align="center" align="center" />
              <el-table-column prop="createTime" label="评分时间" header-align="center" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="nickName" label="评分人" header-align="center" align="center" />
              <el-table-column prop="finalScore" label="总分" header-align="center" align="center">
                <template #default="scope">
                  <span :class="scope.row.finalScore >= 0 ? 'text-success' : 'text-danger'">
                    {{ scope.row.finalScore >= 0 ? '+' : '' }}{{ scope.row.finalScore }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center">
                <template #default="scope">
                  <div class="table-actions">
                    <button class="btn btn-primary view-detail-btn" @click="openDetail(scope.row)">
                      <el-icon><View /></el-icon> 查看详情
                    </button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handlePagination"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="评分详情" width="600px" append-to-body>
      <div class="modal-body">
        <el-form :model="detailForm" label-width="100px">
          <el-form-item label="被评人：">
            <span>{{ detailForm.userName }}</span>
          </el-form-item>
          <el-form-item label="月份：">
            <span>{{ detailForm.monthPeriod }}</span>
          </el-form-item>
          <el-form-item label="维保工单分：">
            <span>{{ detailForm.maintenanceTotalScore }}</span>
          </el-form-item>
          <el-form-item label="维修工单分：">
            <span>{{ detailForm.repairTotalScore }}</span>
          </el-form-item>
          <el-form-item label="评分时间：">
            <span>{{ parseTime(detailForm.createTime) }}</span>
          </el-form-item>
          <el-form-item label="评分人：">
            <span>{{ detailForm.nickName }}</span>
          </el-form-item>
          <el-form-item label="分数：">
            <span :class="detailForm.finalScore >= 0 ? 'text-success' : 'text-danger'">
              {{ detailForm.finalScore >= 0 ? '+' : '' }}{{ detailForm.finalScore }}
            </span>
          </el-form-item>
          
          <div class="fh">
            <el-form-item label="复核意见：">
              <el-input 
                v-model="detailForm.reviewOpinion" 
                type="textarea" 
                :rows="4" 
                :readonly="detailForm.secondCheckStatus !== null && detailForm.secondCheckStatus !== undefined && detailForm.secondCheckStatus !== ''"
                :placeholder="detailForm.secondCheckStatus !== null && detailForm.secondCheckStatus !== undefined && detailForm.secondCheckStatus !== '' ? detailForm.secondCheckStatus : '请输入复核意见'"
                />
            </el-form-item>
            <el-form-item label="最终得分：">
              <el-input-number 
                v-model="detailForm.finalScoreAfterReview" 
                placeholder="请输入得分（可正负）" 
                :min="-10" 
                :max="10"
                :readonly="detailForm.secondCheckStatus !== null && detailForm.secondCheckStatus !== undefined && detailForm.secondCheckStatus !== ''"
                controls-position="right"
                />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 90px;" v-if="(hasEditPermission || hasFirstCheckPermission) && (detailForm.firstCheckStatus === null || detailForm.firstCheckStatus === undefined || detailForm.firstCheckStatus === '')" type="primary" @click="submitFirstCheck">
            <el-icon><Check /></el-icon> 一级校核
          </el-button>
          <el-button style="width: 90px;" v-if="(hasEditPermission || hasSecondCheckPermission) && (detailForm.firstCheckStatus !== null && detailForm.firstCheckStatus !== undefined && detailForm.firstCheckStatus !== '') && (detailForm.secondCheckStatus === null || detailForm.secondCheckStatus === undefined || detailForm.secondCheckStatus === '')" type="success" @click="submitSecondCheck">
            <el-icon><Check /></el-icon> 二级校核
          </el-button>
          <el-button style="width: 50px;" @click="closeDetail">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserScoreReview">
import { View, Refresh, Check } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, computed } from 'vue'
import useUserStore from '@/store/modules/user'
import { listUserScore, updateUserScore } from '@/api/gxt/userScore'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/ruoyi'

// 数据定义
const selectedMonth = ref(null)
const monthOptions = ref([])
const scoreReviewList = ref([])
const detailDialogVisible = ref(false)
const loading = ref(true)
const total = ref(0)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  monthPeriod: undefined,
  status: undefined
})

const detailForm = reactive({
  userName: '',
  id: '',
  monthPeriod: '',
  maintenanceTotalScore: 0,
  repairTotalScore: 0,
  createTime: '',
  createBy: '',
  finalScore: 0,
  reviewOpinion: '',
  finalScoreAfterReview: 0,
  firstCheckStatus: '',
  secondCheckStatus: '' // 添加二级校核状态字段
})

// 计算属性
const hasEditPermission = computed(() => {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*"
  const requiredPermission = "gxt:userscorereview:edit"
  
  return permissions.some(permission => {
    return all_permission === permission || permission === requiredPermission
  })
})

// 一级校核权限
const hasFirstCheckPermission = computed(() => {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*"
  const requiredPermission = "gxt:userscorereview:first"
  
  return permissions.some(permission => {
    return all_permission === permission || permission === requiredPermission
  })
})

// 二级校核权限
const hasSecondCheckPermission = computed(() => {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*"
  const requiredPermission = "gxt:userscorereview:second"
  
  return permissions.some(permission => {
    return all_permission === permission || permission === requiredPermission
  })
})

const isReadOnly = computed(() => {
  return !hasEditPermission.value
})

// 表格行的类名处理函数
function tableRowClassName({ row, rowIndex }) {
  return 'table-row-hover'
}

// 方法定义
function generateMonthOptions() {
  const now = new Date()
  const options = []
  
  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}月`
    
    options.push({
      value: value,
      label: label
    })
  }
  
  monthOptions.value = options
  selectedMonth.value = options[0] // 默认选择本月
  queryParams.monthPeriod = selectedMonth.value.value
  loadScoreReviewData()
}

function handleMonthChange() {
  console.log('月份选择变化:', selectedMonth.value.label)
  queryParams.monthPeriod = selectedMonth.value.value
  queryParams.pageNum = 1
  loadScoreReviewData()
}

function handlePagination(data) {
  queryParams.pageNum = data.page
  queryParams.pageSize = data.limit
  loadScoreReviewData()
}

function loadScoreReviewData() {
  loading.value = true
  listUserScore(queryParams).then(response => {
    scoreReviewList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('获取工分复核数据失败:', error)
    loading.value = false
  })
}

function openDetail(row) {
  // 填充详情表单数据
  detailForm.userName = row.userName
  detailForm.id = row.id
  detailForm.monthPeriod = row.monthPeriod
  detailForm.maintenanceTotalScore = row.maintenanceTotalScore
  detailForm.repairTotalScore = row.repairTotalScore
  detailForm.createTime = row.createTime
  detailForm.createBy = row.createBy
  detailForm.nickName = row.nickName
  detailForm.finalScore = row.finalScore
  detailForm.reviewOpinion = ''
  detailForm.finalScoreAfterReview = row.finalScore
  detailForm.firstCheckStatus = row.firstCheckStatus
  detailForm.secondCheckStatus = row.secondCheckStatus // 添加二级校核状态字段
  
  detailDialogVisible.value = true
}

function closeDetail() {
  detailDialogVisible.value = false
}

function submitFirstCheck() {
  if (!detailForm.reviewOpinion) {
    alert('请输入复核意见')
    return
  }
  
  if (detailForm.finalScoreAfterReview === null || detailForm.finalScoreAfterReview === undefined) {
    alert('请输入最终得分')
    return
  }
  
  // 检查是否有编辑权限，如果没有则不提交
  if (!hasFirstCheckPermission.value) {
    alert('您没有权限进行一级校核操作')
    return
  }
  
  // 构造要提交的数据
  const submitData = {
    id: detailForm.id,
    firstCheckStatus: detailForm.reviewOpinion,
    finalScore: detailForm.finalScoreAfterReview,
    firstChecker: useUserStore().id, // 记录一级校核人
    firstCheckTime: new Date() // 记录一级校核时间
  }
  
  // 调用API提交数据
  updateUserScore(submitData).then(response => {
    if (response.code === 200) {
      closeDetail()
      loadScoreReviewData() // 重新加载数据
      alert('一级校核提交成功！')
    } else {
      alert('提交失败: ' + response.msg)
    }
  }).catch(error => {
    console.error('提交一级校核失败:', error)
    alert('提交失败，请稍后重试')
  })
}

function submitSecondCheck() {
  if (!detailForm.reviewOpinion) {
    alert('请输入复核意见')
    return
  }
  
  if (detailForm.finalScoreAfterReview === null || detailForm.finalScoreAfterReview === undefined) {
    alert('请输入最终得分')
    return
  }
  
  // 检查是否有编辑权限，如果没有则不提交
  if (!hasSecondCheckPermission.value) {
    alert('您没有权限进行二级校核操作')
    return
  }
  
  // 构造要提交的数据
  const submitData = {
    id: detailForm.id,
    secondCheckStatus: detailForm.reviewOpinion,
    finalScore: detailForm.finalScoreAfterReview,
    secondChecker: useUserStore().id, // 记录二级校核人
    secondCheckTime: new Date() // 记录二级校核时间
  }
  
  // 调用API提交数据
  updateUserScore(submitData).then(response => {
    if (response.code === 200) {
      closeDetail()
      loadScoreReviewData() // 重新加载数据
      alert('二级校核提交成功！')
    } else {
      alert('提交失败: ' + response.msg)
    }
  }).catch(error => {
    console.error('提交二级校核失败:', error)
    alert('提交失败，请稍后重试')
  })
}

// 生命周期钩子
onMounted(() => {
  generateMonthOptions()
})
</script>

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

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

/* 页面头部样式 */
.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;
}

.content-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
  width: auto;
}

/* 内容区域样式 */
.content-wrapper {
  flex: 1;
  padding: 1.5rem 2rem;
  overflow-y: auto;
}

.module-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  overflow: hidden;
}

.module-header {
  padding: 1.2rem 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.module-subtitle {
  font-size: 1.1rem;
  font-weight: 500;
  color: #2d3748;
}

.tab-content {
  padding: 1.5rem;
}

/* 表格样式 */
.data-table {
  width: 100%;
  font-size: 0.9rem;
}

.table-responsive {
  margin-bottom: 1.5rem;
}

/* 表格行悬浮效果 */
:deep(.table-row-hover:hover) {
  background-color: #f5f7fa !important;
  transition: background-color 0.3s ease;
}

/* 按钮样式 */
.btn {
  padding: 0.4rem 0.8rem;
  border-radius: 6px;
  border: none;
  font-size: 0.85rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
}

.btn-primary {
  background-color: #4299e1;
  color: #fff;
}

.btn-primary:hover {
  background-color: #3182ce;
}

.btn-warning {
  background-color: #f6ad55;
  color: #fff;
}

.btn-warning:hover {
  background-color: #ed8936;
}

/* 表格操作按钮容器 */
.table-actions {
  display: flex;
  gap: 0.5rem;
}

/* 弹窗样式 */
.modal-body {
  padding: 1.5rem;
}

.fh {
  padding: 20px;
  border-top: 1px solid #e2e8f0;
  margin-top: 15px;
}

/* 文本颜色样式 */
.text-success {
  color: #48bb78;
}

.text-danger {
  color: #f56565;
}

/* Element UI 组件样式调整 */
:deep(.el-table) {
  font-size: 0.9rem;
}

:deep(.el-table th) {
  background-color: #f7fafc;
  color: #4a5568;
  font-weight: 600;
  text-align: center !important;
}

:deep(.el-table th, .el-table td) {
  padding: 0.9rem 1.2rem;
  text-align: center;
}

:deep(.el-table td) {
  text-align: center;
}

:deep(.el-input__inner) {
  padding: 0.6rem 0.8rem;
}

/* Element UI 图标样式调整 */
.el-icon {
  width: 1em;
  height: 1em;
  vertical-align: middle;
}
</style>