<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="责任人" prop="personName">
        <el-input v-model="queryParams.personName" placeholder="请输入责任人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="队室/班组" prop="teamName">
        <el-input v-model="queryParams.teamName" placeholder="请输入队室/班组" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="维度" prop="dimensionId">
        <el-select v-model="queryParams.dimensionId" placeholder="全部维度" clearable style="width:150px">
          <el-option v-for="d in dimensionOptions" :key="d.id" :label="d.name" :value="d.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="全部来源" clearable style="width:120px">
          <el-option label="手动录入" value="1" />
          <el-option label="台账同步" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件时间">
        <el-date-picker v-model="dateRange" type="daterange" value-format="YYYY-MM-DD"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable />
      </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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['score:event:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['score:event:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['score:event:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['score:event:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload :show-file-list="false" accept=".xlsx,.xls" :auto-upload="false" :on-change="handleImportFile">
          <el-button type="info" plain icon="Upload" v-hasPermi="['score:event:import']">导入</el-button>
        </el-upload>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="事件时间" align="center" prop="eventTime" width="120">
        <template #default="{ row }">{{ parseTime(row.eventTime, '{y}-{m}-{d}') }}</template>
      </el-table-column>
      <el-table-column label="维度" align="center" prop="dimensionName" width="110" />
      <el-table-column label="二级指标" align="center" prop="level2Name" show-overflow-tooltip />
      <el-table-column label="三级指标" align="center" prop="level3Name" show-overflow-tooltip />
      <el-table-column label="责任人" align="center" prop="personName" width="80" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="班组" align="center" prop="teamName" />
      <el-table-column label="基础分值" align="center" prop="scoreValue" width="90">
        <template #default="{ row }">
          <span :style="{ color: row.scoreValue > 0 ? '#67c23a' : row.scoreValue < 0 ? '#f56c6c' : '' }">
            {{ row.scoreValue > 0 ? '+' : '' }}{{ row.scoreValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="叠加分" align="center" prop="cascadeScore" width="80">
        <template #default="{ row }">
          <span v-if="row.cascadeScore" :style="{ color: row.cascadeScore > 0 ? '#67c23a' : '#f56c6c' }">
            {{ row.cascadeScore > 0 ? '+' : '' }}{{ row.cascadeScore }}
          </span>
          <span v-else style="color:#c0c4cc">-</span>
        </template>
      </el-table-column>
      <el-table-column label="总分值" align="center" prop="totalScore" width="90">
        <template #default="{ row }">
          <strong :style="{ color: row.totalScore > 0 ? '#67c23a' : row.totalScore < 0 ? '#f56c6c' : '' }">
            {{ row.totalScore > 0 ? '+' : '' }}{{ row.totalScore }}
          </strong>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" width="90">
        <template #default="{ row }">
          <el-tag :type="row.sourceType === '1' ? 'primary' : 'warning'" size="small">
            {{ row.sourceType === '1' ? '手动录入' : '台账同步' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="事件描述" align="center" prop="eventDesc" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="120">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['score:event:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['score:event:remove']">删除</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-dialog :title="dialogTitle" v-model="dialogVisible" width="680px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="维度" prop="dimensionId">
              <el-select v-model="form.dimensionId" placeholder="请选择维度" style="width:100%" @change="onDimensionChange">
                <el-option v-for="d in dimensionOptions" :key="d.id" :label="d.name" :value="d.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级指标" prop="level2Name">
              <el-select v-model="form.level2Name" placeholder="请选择" style="width:100%" clearable @change="onLevel2Change">
                <el-option v-for="n in level2Options" :key="n" :label="n" :value="n" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="三级指标" prop="level3Name">
              <el-select v-model="form.level3Name" placeholder="请选择" style="width:100%" clearable @change="onLevel3Change">
                <el-option v-for="n in level3Options" :key="n" :label="n" :value="n" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="四级指标">
              <el-select v-model="form.level4Name" placeholder="请选择" style="width:100%" clearable>
                <el-option v-for="n in level4Options" :key="n" :label="n" :value="n" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件时间" prop="eventTime">
              <el-date-picker v-model="form.eventTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择事件时间" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置">
              <el-input v-model="form.location" placeholder="区域/通道" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人" prop="personName">
              <el-input v-model="form.personName" placeholder="请输入责任人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="队室/班组">
              <el-input v-model="form.teamName" placeholder="请输入队室/班组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小组">
              <el-input v-model="form.groupName" placeholder="请输入小组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础分值" prop="scoreValue">
              <el-input-number v-model="form.scoreValue" :precision="2" style="width:100%"
                               placeholder="正数=加分 负数=扣分" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="叠加分值">
              <el-input-number v-model="form.cascadeScore" :precision="2" style="width:100%"
                               placeholder="叠加后果产生的分值" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="事件描述" prop="eventDesc">
              <el-input v-model="form.eventDesc" type="textarea" :rows="3" placeholder="请输入事件描述" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listScoreEvent, addScoreEvent, updateScoreEvent, delScoreEvent,
  exportScoreEvent, importScoreEvent
} from '@/api/score/index'
import { allDimension, treeIndicator } from '@/api/score/index'
import { parseTime } from '@/utils/ruoyi'

defineOptions({ name: 'ScoreEvent' })

const loading = ref(false), list = ref([]), total = ref(0), showSearch = ref(true)
const dateRange = ref([]), queryRef = ref(null), formRef = ref(null)
const dialogVisible = ref(false), dialogTitle = ref('')
const single = ref(true), multiple = ref(true), ids = ref([])
const dimensionOptions = ref([])
const indicatorTree = ref([])  // 当前维度的指标树（扁平+嵌套）
const level2Options = ref([])
const level3Options = ref([])
const level4Options = ref([])

const queryParams = reactive({ pageNum: 1, pageSize: 10, personName: '', deptName: '', teamName: '', dimensionId: null, sourceType: '' })
const form = reactive({ id: null, dimensionId: null, dimensionName: '', indicatorId: null, level2Name: '', level3Name: '', level4Name: '', eventTime: '', location: '', personName: '', deptName: '', teamName: '', groupName: '', scoreValue: 0, cascadeScore: 0, eventDesc: '', remark: '' })
const rules = {
  dimensionId: [{ required: true, message: '请选择维度', trigger: 'change' }],
  personName: [{ required: true, message: '请输入责任人', trigger: 'blur' }],
  eventTime: [{ required: true, message: '请选择事件时间', trigger: 'change' }],
  scoreValue: [{ required: true, message: '请输入分值', trigger: 'blur' }]
}

async function loadDimensions() {
  const r = await allDimension()
  dimensionOptions.value = r.data || []
}

function getList() {
  loading.value = true
  const p = { ...queryParams }
  if (dateRange.value?.length === 2) { p['params[beginTime]'] = dateRange.value[0]; p['params[endTime]'] = dateRange.value[1] }
  listScoreEvent(p).then(r => { list.value = r.rows; total.value = r.total }).finally(() => loading.value = false)
}

function handleQuery() { queryParams.pageNum = 1; getList() }
function resetQuery() { dateRange.value = []; queryRef.value?.resetFields(); handleQuery() }
function handleSelectionChange(sel) { ids.value = sel.map(s => s.id); single.value = sel.length !== 1; multiple.value = !sel.length }

function resetForm() {
  Object.assign(form, { id: null, dimensionId: null, dimensionName: '', indicatorId: null, level2Name: '', level3Name: '', level4Name: '', eventTime: '', location: '', personName: '', deptName: '', teamName: '', groupName: '', scoreValue: 0, cascadeScore: 0, eventDesc: '', remark: '' })
  level2Options.value = []; level3Options.value = []; level4Options.value = []
}

function handleAdd() { resetForm(); dialogTitle.value = '新增配分事项'; dialogVisible.value = true }
function handleUpdate(row) {
  resetForm()
  const record = row?.id ? row : list.value.find(r => r.id === ids.value[0])
  if (record) {
    Object.assign(form, record)
    if (record.dimensionId) onDimensionChange(record.dimensionId, true)
  }
  dialogTitle.value = '修改配分事项'; dialogVisible.value = true
}

async function onDimensionChange(dimId, preserveSelection) {
  const dim = dimensionOptions.value.find(d => d.id === dimId)
  if (dim) form.dimensionName = dim.name
  const r = await treeIndicator(dimId)
  indicatorTree.value = r.data || []
  level2Options.value = indicatorTree.value.map(n => n.name)
  if (!preserveSelection) { form.level2Name = ''; form.level3Name = ''; form.level4Name = '' }
  level3Options.value = []; level4Options.value = []
  if (preserveSelection && form.level2Name) onLevel2Change(form.level2Name, true)
}

function onLevel2Change(val, preserveSelection) {
  const node = indicatorTree.value.find(n => n.name === val)
  level3Options.value = node ? (node.children || []).map(n => n.name) : []
  if (!preserveSelection) { form.level3Name = ''; form.level4Name = '' }
  level4Options.value = []
  if (preserveSelection && form.level3Name) onLevel3Change(form.level3Name, true)
}

function onLevel3Change(val, preserveSelection) {
  const level2Node = indicatorTree.value.find(n => n.name === form.level2Name)
  const node = level2Node ? (level2Node.children || []).find(n => n.name === val) : null
  level4Options.value = node ? (node.children || []).map(n => n.name) : []
  if (!preserveSelection) form.level4Name = ''
}

async function submitForm() {
  await formRef.value.validate()
  if (form.id) { await updateScoreEvent(form); ElMessage.success('修改成功') }
  else { await addScoreEvent(form); ElMessage.success('新增成功') }
  dialogVisible.value = false; getList()
}

function handleDelete(row) {
  const delIds = row?.id ? [row.id] : ids.value
  ElMessageBox.confirm('确认删除选中的配分事项？', '提示', { type: 'warning' }).then(() => {
    delScoreEvent(delIds.join(',')).then(() => { ElMessage.success('删除成功'); getList() })
  })
}

function handleExport() {
  const p = { ...queryParams }
  if (dateRange.value?.length === 2) { p['params[beginTime]'] = dateRange.value[0]; p['params[endTime]'] = dateRange.value[1] }
  exportScoreEvent(p)
}

async function handleImportFile(file) {
  try {
    const r = await importScoreEvent(file.raw)
    ElMessage.success(r.msg || '导入成功')
    getList()
  } catch (e) {
    ElMessage.error('导入失败')
  }
}

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