<template>
  <div class="ep-root">
    <!-- 顶部工具栏 -->
    <div class="ep-topbar">
      <div class="time-btns">
        <el-button size="small" :type="currentTime==='week'?'primary':'default'" @click="selectTime('week')">近一周</el-button>
        <el-button size="small" :type="currentTime==='month'?'primary':'default'" @click="selectTime('month')">近一月</el-button>
        <el-button size="small" :type="currentTime==='quarter'?'primary':'default'" @click="selectTime('quarter')">近三月</el-button>
        <el-button size="small" :type="currentTime==='year'?'primary':'default'" @click="selectTime('year')">近一年</el-button>
        <el-button size="small" :type="currentTime==='custom'?'primary':'default'" @click="selectTime('custom')">自定义时间范围</el-button>
        <el-date-picker
          v-if="currentTime==='custom'"
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始"
          end-placeholder="结束"
          size="small"
          style="margin-left:8px;width:240px"
          @change="loadPortrait"
        />
      </div>
      <el-autocomplete
        v-model="personName"
        :fetch-suggestions="queryUsers"
        placeholder="搜索员工/团队画像"
        size="small"
        style="width:220px"
        @select="handlePersonSelect"
        @clear="portrait=null"
        clearable
      >
        <template #suffix><el-icon><Search /></el-icon></template>
        <template #default="{ item }">
          <span>{{ item.nickName }}</span>
          <span v-if="item.deptName" style="font-size:12px;color:#999;margin-left:8px">{{ item.deptName }}</span>
        </template>
      </el-autocomplete>
    </div>

    <!-- 空状态 -->
    <div v-if="!portrait" class="ep-empty">
      <el-empty description="请在右上角搜索员工姓名以查看画像" />
    </div>

    <!-- 主内容 -->
    <div v-else v-loading="loading" class="ep-body">

      <!-- 左侧主区 -->
      <div class="ep-left">

        <!-- 第一行：基本信息卡 + 综合评价 -->
        <div class="row-flex gap">

          <!-- 基本信息 -->
          <div class="card basic-card">
            <div class="avatar-area">
              <img v-if="portrait.avatar" :src="portrait.avatar" class="avatar" alt="头像" />
              <div v-else class="avatar-fallback">{{ portrait.personName?.charAt(0) }}</div>
            </div>
            <div class="basic-detail">
              <div class="basic-name">
                <span class="lbl">姓名：</span>
                <span class="person-name">{{ portrait.personName }}</span>
              </div>
              <div class="basic-row">
                <span class="lbl">所属部门及队室：</span>
                <span class="val">{{ portrait.deptPath || '-' }}</span>
              </div>
              <div class="basic-row2">
                <span><span class="lbl">技能等级：</span><span class="val">{{ portrait.qualificationLevelText || '-' }}</span></span>
                <span><span class="lbl">学历：</span><span class="val">{{ portrait.schooling || '-' }}</span></span>
              </div>
              <div class="basic-row2" v-if="portrait.startWorkingDate">
                <span><span class="lbl">入职日期：</span><span class="val">{{ portrait.startWorkingDate }}</span></span>
                <span v-if="portrait.phonenumber"><span class="lbl">电话：</span><span class="val">{{ portrait.phonenumber }}</span></span>
              </div>
              <div class="tags-row">
                <span class="lbl">标签：</span>
                <el-tag size="small" type="primary" style="margin-right:6px" v-if="portrait.qualificationLevelText">{{ portrait.qualificationLevelText }}</el-tag>
                <el-tag size="small" type="warning" v-if="portrait.deptName">{{ portrait.deptName }}</el-tag>
              </div>
            </div>
          </div>

          <!-- 综合评价 -->
          <div class="card score-card">
            <div class="score-label">综合评价</div>
            <div class="score-num">{{ portrait.totalScore }}</div>
            <div class="score-level-tag">{{ scoreLevel }}</div>
          </div>
        </div>

        <!-- 第二行：工作履历+获奖 / 个人能力雷达 -->
        <div class="row-flex gap" style="flex:1;min-height:0">

          <!-- 工作履历 & 获奖记录 -->
          <div class="card left-mid-card">
            <div class="sec-title">● 工作履历</div>
            <div class="history-list">
              <div class="history-item" v-if="portrait.startWorkingDate">
                {{ portrait.startWorkingDate?.substring(0,7) }}入职
                <span v-if="portrait.workYears != null">｜司龄{{ portrait.workYears }}年</span>
                <span v-if="portrait.securityCheckYears != null">｜开机年限{{ portrait.securityCheckYears }}年</span>
                <span v-if="portrait.securityInspectionPosition">｜现任职{{ portrait.securityInspectionPosition }}</span>
              </div>
              <div v-if="!portrait.startWorkingDate" class="empty-text">暂无履历数据</div>
            </div>

            <div class="sec-title mt16">● 获奖记录</div>
            <table class="award-table" v-if="portrait.awards && portrait.awards.length">
              <thead>
                <tr>
                  <th>类型</th>
                  <th>内容</th>
                  <th>加分</th>
                  <th>日期</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(aw, i) in portrait.awards" :key="i" :class="i%2===0?'tr-a':'tr-b'">
                  <td>{{ aw.type }}</td>
                  <td>{{ aw.content }}</td>
                  <td class="td-score">+{{ aw.score }}</td>
                  <td>{{ aw.date }}</td>
                </tr>
              </tbody>
            </table>
            <div v-else class="empty-text mt8">暂无获奖记录</div>
          </div>

          <!-- 个人能力雷达 -->
          <div class="card radar-card">
            <div class="sec-title">● 个人能力</div>
            <div ref="abilityChart" class="chart-box"></div>
          </div>
        </div>

      </div>

      <!-- 右侧边栏 -->
      <div class="ep-right">

        <!-- 补充信息 -->
        <div class="card side-card">
          <div class="side-title">补充信息</div>
          <div class="supp-grid">
            <div class="supp-item">
              <span class="s-lbl">政治面貌</span>
              <span class="s-val">{{ portrait.politicalStatusText || '-' }}</span>
            </div>
            <div class="supp-item">
              <span class="s-lbl">性别</span>
              <span class="s-val">{{ portrait.sexText || '-' }}</span>
            </div>
            <div class="supp-item">
              <span class="s-lbl">司龄</span>
              <span class="s-val">{{ portrait.workYears != null ? portrait.workYears+'年' : '-' }}</span>
            </div>
            <div class="supp-item">
              <span class="s-lbl">开机年限</span>
              <span class="s-val">{{ portrait.securityCheckYears != null ? portrait.securityCheckYears+'年' : '-' }}</span>
            </div>
            <div class="supp-item">
              <span class="s-lbl">性格特征</span>
              <span class="s-val">{{ portrait.characterCharacteristics || '-' }}</span>
            </div>
            <div class="supp-item">
              <span class="s-lbl">工作风格</span>
              <span class="s-val">{{ portrait.workingStyle || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 业务岗位 -->
        <div class="card side-card">
          <div class="side-title">业务岗位</div>
          <div class="pos-list">
            <div class="pos-item" v-for="(p, i) in positionList" :key="i">{{ p }}</div>
            <div v-if="!positionList.length" class="empty-text">暂无岗位信息</div>
          </div>
        </div>

        <!-- 培训情况 -->
        <div class="card side-card">
          <div class="side-title">培训情况</div>
          <div v-if="portrait.theoryScore != null || portrait.imageScore != null">
            <div class="train-header">
              <span>季度</span><span>理论成绩</span><span>图像成绩</span>
            </div>
            <div class="train-row">
              <span>{{ portrait.examPeriod || '-' }}</span>
              <span :style="examScoreStyle(portrait.theoryScore)">
                {{ portrait.theoryScore != null ? portrait.theoryScore+'分' : '-' }}
              </span>
              <span :style="examScoreStyle(portrait.imageScore)">
                {{ portrait.imageScore != null ? portrait.imageScore+'分' : '-' }}
              </span>
            </div>
          </div>
          <div v-else class="empty-text">暂无考试记录</div>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Search } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { searchPortraitUsers, getEmployeePortrait } from '@/api/score/index'

defineOptions({ name: 'EmployeeProfile' })

const route = useRoute()
const currentTime = ref('year')
const dateRange = ref([])
const personName = ref('')
const portrait = ref(null)
const loading = ref(false)
const abilityChart = ref(null)
let chart = null

const formatDate = (d) => {
  const dt = new Date(d)
  return `${dt.getFullYear()}-${String(dt.getMonth()+1).padStart(2,'0')}-${String(dt.getDate()).padStart(2,'0')}`
}

const getTimeRange = () => {
  if (currentTime.value === 'custom') {
    if (dateRange.value?.length === 2) {
      return { beginTime: formatDate(dateRange.value[0]), endTime: formatDate(dateRange.value[1]) }
    }
    return {}
  }
  const end = new Date(), begin = new Date()
  if (currentTime.value === 'week') begin.setDate(end.getDate()-7)
  else if (currentTime.value === 'month') begin.setMonth(end.getMonth()-1)
  else if (currentTime.value === 'quarter') begin.setMonth(end.getMonth()-3)
  else begin.setFullYear(end.getFullYear()-1)
  return { beginTime: formatDate(begin), endTime: formatDate(end) }
}

const selectTime = (t) => {
  currentTime.value = t
  if (t !== 'custom') loadPortrait()
}

const queryUsers = async (query, cb) => {
  if (!query?.trim()) { cb([]); return }
  try {
    const res = await searchPortraitUsers(query.trim())
    cb((res.data || []).map(u => ({ ...u, value: u.nickName })))
  } catch (_) { cb([]) }
}

const handlePersonSelect = (item) => {
  personName.value = item.nickName
  loadPortrait()
}

const loadPortrait = async () => {
  if (!personName.value) return
  loading.value = true
  try {
    const res = await getEmployeePortrait({ personName: personName.value, ...getTimeRange() })
    portrait.value = res.data || null
  } catch (_) {
    portrait.value = null
  } finally {
    loading.value = false
  }
}

const scoreColor = computed(() => {
  const s = Number(portrait.value?.totalScore)
  if (s < 75) return 'color:#f56c6c'
  if (s > 85) return 'color:#67c23a'
  return 'color:#ff9900'
})

const scoreLevel = computed(() => {
  const s = Number(portrait.value?.totalScore)
  if (s < 75) return '较差'
  if (s > 85) return '优秀'
  return '良好'
})

const positionList = computed(() => {
  const pos = portrait.value?.securityInspectionPosition
  if (!pos) return []
  return pos.split(/[,，、/]/).map(s => s.trim()).filter(Boolean)
})

const examScoreStyle = (score) => {
  const s = Number(score)
  if (s >= 90) return 'color:#67c23a;font-weight:600'
  if (s < 60) return 'color:#f56c6c;font-weight:600'
  return 'color:#409eff'
}

const initChart = () => {
  if (!abilityChart.value || !portrait.value) return
  if (chart) { chart.dispose(); chart = null }
  chart = echarts.init(abilityChart.value)
  const dims = portrait.value.dimensions || []
  chart.setOption({
    radar: {
      indicator: dims.map(d => ({ name: d.name + '\n' + d.score, max: 100 })),
      center: ['50%', '52%'],
      radius: '65%',
      splitNumber: 4,
      name: { textStyle: { color: '#555', fontSize: 11 }, formatter: (v) => v },
      axisLine: { lineStyle: { color: '#c8dff5' } },
      splitLine: { lineStyle: { color: '#c8dff5' } },
      splitArea: { areaStyle: { color: ['rgba(64,158,255,0.03)', 'rgba(64,158,255,0.06)'] } }
    },
    series: [{
      type: 'radar',
      data: [{
        value: dims.map(d => Number(d.score)),
        name: '个人能力',
        areaStyle: { color: 'rgba(64,158,255,0.25)' },
        lineStyle: { color: '#409eff', width: 2 },
        itemStyle: { color: '#409eff' }
      }],
      symbol: 'circle',
      symbolSize: 5,
      label: {
        show: true,
        formatter: (p) => p.value,
        color: '#409eff',
        fontSize: 11
      }
    }],
    tooltip: { trigger: 'item' }
  })
}

watch(portrait, (val) => { if (val) nextTick(() => initChart()) })

const handleResize = () => { chart?.resize() }

onMounted(() => {
  window.addEventListener('resize', handleResize)
  const n = route.query.personName
  if (n) { personName.value = n; loadPortrait() }
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose(); chart = null
})
</script>

<style scoped lang="scss">
.ep-root {
  min-height: 100vh;
  background: #eef2fb;
  display: flex;
  flex-direction: column;
  padding: 12px;
  box-sizing: border-box;
  gap: 12px;
}

/* ── 顶部工具栏 ── */
.ep-topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 8px;
  padding: 10px 16px;
  box-shadow: 0 1px 6px rgba(0,0,0,0.07);
  flex-shrink: 0;
  gap: 12px;
  flex-wrap: wrap;

  .time-btns {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
  }
}

/* ── 空状态 ── */
.ep-empty {
  background: #fff;
  border-radius: 8px;
  padding: 60px;
  text-align: center;
}

/* ── 主体两栏 ── */
.ep-body {
  display: flex;
  gap: 12px;
  flex: 1;
  min-height: 0;
}

.ep-left {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ep-right {
  width: 230px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* ── 通用卡片 ── */
.card {
  background: #fff;
  border-radius: 8px;
  padding: 14px 16px;
  box-shadow: 0 1px 6px rgba(0,0,0,0.07);
}

.row-flex {
  display: flex;
}
.gap { gap: 12px; }

/* ── 基本信息卡 ── */
.basic-card {
  flex: 1;
  display: flex;
  gap: 16px;
  align-items: flex-start;
  background: repeating-linear-gradient(
    45deg,
    #daeeff 0px, #daeeff 2px,
    #eef7ff 2px, #eef7ff 14px
  );

  .avatar-area {
    flex-shrink: 0;
    .avatar {
      width: 90px;
      height: 90px;
      border-radius: 50%;
      border: 3px solid #409eff;
      object-fit: cover;
    }
    .avatar-fallback {
      width: 90px;
      height: 90px;
      border-radius: 50%;
      background: linear-gradient(135deg, #409eff, #79bbff);
      border: 3px solid #409eff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32px;
      font-weight: bold;
      color: #fff;
    }
  }

  .basic-detail {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 7px;
  }

  .basic-name {
    display: flex;
    align-items: center;
    .person-name {
      font-size: 48px;
      font-weight: normal;
      color: rgba(31, 135, 232, 1);
      font-family: 'YSBiaoTiHei-bold', 'YouSheBiaoTiHei', 'PingFang SC', 'Microsoft YaHei', sans-serif;
      line-height: 68px;
    }
  }

  .basic-row {
    font-size: 13px;
  }

  .basic-row2 {
    display: flex;
    gap: 24px;
    font-size: 13px;
  }

  .tags-row {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
  }

  .lbl { color: #888; }
  .val { color: #333; font-weight: 500; }
}

/* ── 综合评价卡 ── */
.score-card {
  width: 150px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(160deg, #f7b89c, #f4a088);
  border: none;

  .score-label {
    font-size: 14px;
    font-weight: 600;
    color: #fff;
    margin-bottom: 8px;
    text-shadow: 0 1px 2px rgba(0,0,0,0.15);
  }

  .score-num {
    font-size: 52px;
    font-weight: bold;
    line-height: 1;
    color: #fff;
    text-shadow: 0 2px 6px rgba(0,0,0,0.15);
  }

  .score-level-tag {
    margin-top: 8px;
    font-size: 14px;
    font-weight: 600;
    color: #fff;
    background: rgba(255,255,255,0.25);
    padding: 2px 12px;
    border-radius: 10px;
  }
}

/* ── 工作履历 + 获奖 ── */
.left-mid-card {
  width: 260px;
  flex-shrink: 0;
  overflow-y: auto;
  background: #e8f5ff;

  .sec-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  .mt16 { margin-top: 16px; }
  .mt8  { margin-top: 8px; }

  .history-list {
    .history-item {
      font-size: 12px;
      color: #555;
      background: #f0f7ff;
      border-radius: 4px;
      padding: 6px 10px;
      margin-bottom: 6px;
      line-height: 1.6;
    }
  }
}

.award-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;

  th {
    background: #fde8e6;
    color: #555;
    padding: 6px 6px;
    text-align: center;
    font-weight: 500;
  }

  td {
    padding: 6px 6px;
    text-align: center;
    color: #555;
  }

  .tr-a td { background: #fff8f7; }
  .tr-b td { background: #fff; }
  .td-score { color: #67c23a; font-weight: 600; }
}

/* ── 雷达图卡 ── */
.radar-card {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;

  .sec-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
    flex-shrink: 0;
  }

  .chart-box {
    flex: 1;
    min-height: 260px;
  }
}

/* ── 右侧侧栏卡片 ── */
.side-card {
  .side-title {
    font-size: 13px;
    font-weight: 600;
    color: #fff;
    background: #409eff;
    margin: -14px -16px 12px;
    padding: 7px 16px;
    border-radius: 8px 8px 0 0;
  }
}

/* 补充信息 */
.supp-grid {
  display: flex;
  flex-direction: column;
  gap: 0;

  .supp-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 0;
    border-bottom: 1px dashed #dce9f5;
    font-size: 12px;

    &:last-child { border-bottom: none; }

    .s-lbl { color: #666; }
    .s-val {
      color: #2c6baf;
      font-weight: 500;
      background: #d6eaf8;
      padding: 2px 10px;
      border-radius: 4px;
      min-width: 56px;
      text-align: center;
    }
  }
}

/* 业务岗位 */
.pos-list {
  display: flex;
  flex-direction: column;
  gap: 6px;

  .pos-item {
    background: #c8e6f8;
    color: #1a6aaa;
    border-radius: 4px;
    padding: 7px 10px;
    font-size: 12px;
    text-align: center;
    font-weight: 500;
  }
}

/* 培训情况 */
.train-header, .train-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  font-size: 12px;
  text-align: center;
  gap: 4px;
}

.train-header {
  color: #888;
  margin-bottom: 6px;
  padding-bottom: 4px;
  border-bottom: 1px solid #dce9f5;
}

.train-row {
  color: #2c6baf;
  font-weight: 600;

  span {
    background: #d6eaf8;
    border-radius: 4px;
    padding: 4px 4px;
  }
}

/* 通用 */
.empty-text { color: #bbb; font-size: 12px; text-align: center; padding: 8px 0; }
</style>
