<template>
  <div class="app-container">
    <el-card>
      <!-- 查询条件 -->
      <div class="filter-container">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable style="width: 200px" />
          </el-form-item>
          
          <el-form-item label="查询月份" prop="assessmentMonth">
            <el-date-picker v-model="queryParams.assessmentMonth" type="month" placeholder="请选择查询月份" 
              value-format="YYYY-MM" style="width: 200px" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="operation-container">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="assessmentList" border fit highlight-current-row style="width: 100%; margin-top: 20px;">
        <el-table-column type="index" label="序号" align="center" width="60" />
        
        <el-table-column label="员工姓名" prop="employeeName" align="center" min-width="120" />
        <el-table-column label="用工形式" prop="employmentType" align="center" min-width="120" />
        <el-table-column label="岗位" prop="position" align="center" min-width="120" />
        <el-table-column label="考核组" prop="assessmentGroup" align="center" min-width="120" />
        <el-table-column label="考核月份" prop="assessmentMonth" align="center" min-width="120" />
        <el-table-column label="总分" prop="totalScore" align="center" min-width="100" sortable />
        <el-table-column label="考核结果" prop="assessmentResult" align="center" min-width="120" />
        <el-table-column label="应用方式" prop="applicationMethod" align="center" min-width="120" />
        <el-table-column label="是否豁免" prop="isExempted" align="center" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isExempted ? 'success' : 'info'">
              {{ scope.row.isExempted ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" 
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 编辑/新增弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="80%" :close-on-click-modal="false">
      <el-form :model="formData" ref="formRef" :rules="rules" label-width="150px" class="form-container">
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="8">
            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="formData.employeeName" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用工形式" prop="employmentType">
              <el-select v-model="formData.employmentType" placeholder="请选择用工形式">
                <el-option v-for="item in employmentTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入岗位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考核组" prop="assessmentGroup">
              <el-input v-model="formData.assessmentGroup" placeholder="请输入考核组" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分管班组长" prop="teamLeader">
              <el-input v-model="formData.teamLeader" placeholder="请输入分管班组长" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分管主管" prop="supervisor">
              <el-input v-model="formData.supervisor" placeholder="请输入分管主管" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分管经理" prop="manager">
              <el-input v-model="formData.manager" placeholder="请输入分管经理" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考核月份" prop="assessmentMonth">
              <el-date-picker v-model="formData.assessmentMonth" type="month" placeholder="请选择考核月份" 
                value-format="YYYY-MM" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分管员工数量" prop="managedEmployeeCount">
              <el-input-number v-model="formData.managedEmployeeCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 红线指标 -->
        <el-divider content-position="left">红线指标</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红线指标触发次数" prop="redLineTriggerCount">
              <el-input-number v-model="formData.redLineTriggerCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红线指标依据" prop="redLineBasis">
              <el-input v-model="formData.redLineBasis" type="textarea" :rows="2" placeholder="请输入红线指标依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 核心指标 -->
        <el-divider content-position="left">核心指标</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="核心指标分值" prop="coreIndicatorScore">
              <el-input-number v-model="formData.coreIndicatorScore" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核心指标依据" prop="coreIndicatorBasis">
              <el-input v-model="formData.coreIndicatorBasis" type="textarea" :rows="2" placeholder="请输入核心指标依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他指标 -->
        <el-divider content-position="left">其他指标</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="其他指标分值" prop="otherIndicatorScore">
              <el-input-number v-model="formData.otherIndicatorScore" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他指标依据" prop="otherIndicatorBasis">
              <el-input v-model="formData.otherIndicatorBasis" type="textarea" :rows="2" placeholder="请输入其他指标依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 安全指标（含SOC/站品控检查扣分） -->
        <el-divider content-position="left">安全指标（含SOC/站品控检查扣分）</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全指标分值（含SOC）" prop="safetyIndicatorScoreWithSOC">
              <el-input-number v-model="formData.safetyIndicatorScoreWithSOC" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全指标依据（含SOC）" prop="safetyIndicatorBasisWithSOC">
              <el-input v-model="formData.safetyIndicatorBasisWithSOC" type="textarea" :rows="2" placeholder="请输入安全指标依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 安全指标（不含SOC/站品控检查扣分） -->
        <el-divider content-position="left">安全指标（不含SOC/站品控检查扣分）</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全指标分值（不含SOC）" prop="safetyIndicatorScoreWithoutSOC">
              <el-input-number v-model="formData.safetyIndicatorScoreWithoutSOC" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全指标依据（不含SOC）" prop="safetyIndicatorBasisWithoutSOC">
              <el-input v-model="formData.safetyIndicatorBasisWithoutSOC" type="textarea" :rows="2" placeholder="请输入安全指标依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 非安全指标 -->
        <el-divider content-position="left">非安全指标</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="非安全指标扣分" prop="nonSafetyIndicatorDeduction">
              <el-input-number v-model="formData.nonSafetyIndicatorDeduction" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="非安全指标扣分依据" prop="nonSafetyIndicatorBasis">
              <el-input v-model="formData.nonSafetyIndicatorBasis" type="textarea" :rows="2" placeholder="请输入非安全指标扣分依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 综合扣分 -->
        <el-divider content-position="left">综合扣分</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="非核心安全+核心扣分" prop="nonCoreSafetyCoreDeduction">
              <el-input-number v-model="formData.nonCoreSafetyCoreDeduction" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SOC/站品控检查涉及扣分" prop="socInspectionDeduction">
              <el-input-number v-model="formData.socInspectionDeduction" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="SOC/站品控检查扣分依据" prop="socInspectionBasis">
              <el-input v-model="formData.socInspectionBasis" type="textarea" :rows="2" placeholder="请输入SOC/站品控检查扣分依据" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 统计信息 -->
        <el-divider content-position="left">统计信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="扣分平均值" prop="averageDeduction">
              <el-input-number v-model="formData.averageDeduction" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number v-model="formData.totalScore" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖励（元）" prop="rewardAmount">
              <el-input-number v-model="formData.rewardAmount" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="扣罚（元）" prop="penaltyAmount">
              <el-input-number v-model="formData.penaltyAmount" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考核结果" prop="assessmentResult">
              <el-select v-model="formData.assessmentResult" placeholder="请选择考核结果">
                <el-option v-for="item in assessmentResultOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应用方式" prop="applicationMethod">
              <el-select v-model="formData.applicationMethod" placeholder="请选择应用方式">
                <el-option v-for="item in applicationMethodOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息 -->
        <el-divider content-position="left">备注信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="奖励明细" prop="rewardDetails">
              <el-input v-model="formData.rewardDetails" type="textarea" :rows="3" placeholder="请输入奖励明细" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="惩罚明细" prop="penaltyDetails">
              <el-input v-model="formData.penaltyDetails" type="textarea" :rows="3" placeholder="请输入惩罚明细" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考核结果备注" prop="assessmentResultRemark">
              <el-input v-model="formData.assessmentResultRemark" type="textarea" :rows="2" placeholder="请输入考核结果备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用方式备注" prop="applicationMethodRemark">
              <el-input v-model="formData.applicationMethodRemark" type="textarea" :rows="2" placeholder="请输入应用方式备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 豁免信息 -->
        <el-divider content-position="left">豁免信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否豁免" prop="isExempted">
              <el-switch v-model="formData.isExempted" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否豁免备注" prop="exemptionRemark">
              <el-input v-model="formData.exemptionRemark" type="textarea" :rows="2" placeholder="请输入豁免备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// API导入（需要根据实际API路径调整）
import { getNonCadreMonthlyAssessList, addNonCadreMonthlyAssess, updateNonCadreMonthlyAssess, deleteNonCadreMonthlyAssess } from '@/api/performance/nonCadreMonthlyAssess.js'

const { proxy } = getCurrentInstance()

// 响应式数据
const loading = ref(false)
const total = ref(0)
const queryFormRef = ref()
const formRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  employeeName: '',
  assessmentMonth: ''
})

// 表单数据
const formData = reactive({
  // 基本信息
  employeeName: '',
  employmentType: '',
  position: '',
  assessmentGroup: '',
  teamLeader: '',
  supervisor: '',
  manager: '',
  assessmentMonth: '',
  managedEmployeeCount: 0,
  
  // 红线指标
  redLineTriggerCount: 0,
  redLineBasis: '',
  
  // 核心指标
  coreIndicatorScore: 0,
  coreIndicatorBasis: '',
  
  // 其他指标
  otherIndicatorScore: 0,
  otherIndicatorBasis: '',
  
  // 安全指标（含SOC）
  safetyIndicatorScoreWithSOC: 0,
  safetyIndicatorBasisWithSOC: '',
  
  // 安全指标（不含SOC）
  safetyIndicatorScoreWithoutSOC: 0,
  safetyIndicatorBasisWithoutSOC: '',
  
  // 非安全指标
  nonSafetyIndicatorDeduction: 0,
  nonSafetyIndicatorBasis: '',
  
  // 综合扣分
  nonCoreSafetyCoreDeduction: 0,
  socInspectionDeduction: 0,
  socInspectionBasis: '',
  
  // 统计信息
  averageDeduction: 0,
  totalScore: 0,
  rewardAmount: 0,
  penaltyAmount: 0,
  assessmentResult: '',
  applicationMethod: '',
  
  // 备注信息
  rewardDetails: '',
  penaltyDetails: '',
  assessmentResultRemark: '',
  applicationMethodRemark: '',
  
  // 豁免信息
  isExempted: false,
  exemptionRemark: ''
})

// 弹窗配置
const dialog = reactive({
  visible: false,
  title: ''
})

// 数据列表
const assessmentList = ref([])

// 选项配置
const employmentTypeOptions = [
  { label: '正式员工', value: 'formal' },
  { label: '合同工', value: 'contract' },
  { label: '临时工', value: 'temporary' },
  { label: '实习生', value: 'intern' }
]

const assessmentResultOptions = [
  { label: '优秀', value: 'excellent' },
  { label: '良好', value: 'good' },
  { label: '合格', value: 'qualified' },
  { label: '不合格', value: 'unqualified' }
]

const applicationMethodOptions = [
  { label: '直接应用', value: 'direct' },
  { label: '加权计算', value: 'weighted' },
  { label: '特殊处理', value: 'special' }
]

// 表单验证规则
const rules = {
  employeeName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  employmentType: [{ required: true, message: '用工形式不能为空', trigger: 'change' }],
  position: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
  assessmentGroup: [{ required: true, message: '考核组不能为空', trigger: 'blur' }],
  assessmentMonth: [{ required: true, message: '考核月份不能为空', trigger: 'change' }]
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getNonCadreMonthlyAssessList(queryParams)
    assessmentList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNum = 1
  getList()
}

// 新增
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增非干部月度考核'
  
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (typeof formData[key] === 'number') {
      formData[key] = 0
    } else if (typeof formData[key] === 'boolean') {
      formData[key] = false
    } else {
      formData[key] = ''
    }
  })
}

// 编辑
const handleEdit = (row) => {
  dialog.visible = true
  dialog.title = '编辑非干部月度考核'
  
  // 填充表单数据
  Object.keys(formData).forEach(key => {
    if (row[key] !== undefined) {
      formData[key] = row[key]
    }
  })
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该考核记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteNonCadreMonthlyAssess(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return
  
  try {
    if (dialog.title === '新增非干部月度考核') {
      await addNonCadreMonthlyAssess(formData)
      ElMessage.success('新增成功')
    } else {
      await updateNonCadreMonthlyAssess(formData)
      ElMessage.success('更新成功')
    }
    
    dialog.visible = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 导出
const handleExport = async () => {
  try {
    // 导出逻辑（需要根据实际API实现）
    ElMessage.success('导出功能开发中')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="less" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-container {
  margin-bottom: 20px;
}

.form-container {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.el-divider {
  margin: 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>