<template>
  <div>
    <!-- 搜索工作栏 -->
    <el-form :model="searchForm" inline label-width="0">
      <el-form-item>
        <el-date-picker
          v-model="searchForm.period"
          type="month"
          format="YYYY-MM"
          value-format="YYYY-MM"
          :clearable="false"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="getList" v-hasPermi="['kpi:score:search']"> 搜索</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="employeeId" @tab-click="getList">
      <el-tab-pane
        v-for="item in employeeOptions"
        :key="item.examinedUser"
        :name="item.examinedUser"
      >
        <template #label>
          <span>{{ item.examinedUserName }}</span>
          <el-badge :is-dot="item.notExaminedCount > 0" type="danger" />
        </template>
        <div class="mb-10px">
          <el-tag v-if="periodSaved == 1" type="danger">
            当前周期已封存，不可修改当月绩效考核
          </el-tag>
          <el-tag v-else type="warning">
            当前周期未封存，可选择修改当月绩效考核，两秒内不操作将自动保存考核结果
          </el-tag>
        </div>

        <el-table
          v-loading="loading"
          :data="list"
          border
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column prop="examineTarget" label="考核指标" width="180" />
          <el-table-column prop="typeName" label="分值模式" width="90" />
          <el-table-column prop="weight" label="权重%" width="90" />
          <el-table-column label="考核内容">
            <template #default="{ row }">
              <div v-dompurify-html="row.examineContent"></div>
            </template>
          </el-table-column>
          <el-table-column label="考核规则" prop="examineRule">
            <template #default="{ row }">
              <div v-dompurify-html="row.examineRule"></div>
            </template>
          </el-table-column>
          <el-table-column label="评分上限" prop="examineScore" width="90" />
          <el-table-column label="考核评分" width="120">
            <template #default="{ row }">
              <div v-if="periodSaved == 1">{{ row.score }}</div>
              <el-input-number
                v-else
                v-model="row.score"
                :min="0"
                :max="row.examineScore"
                :step="1"
                :controls="false"
                size="small"
                style="width: 100%"
                @input="handleSave(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="评分备注" width="200">
            <template #default="{ row }">
              <div v-if="periodSaved == 1">{{ row.remark }}</div>
              <el-input
                v-else
                v-model="row.remark"
                type="textarea"
                :rows="3"
                size="small"
                style="width: 100%"
                @input="handleSave(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="加权得分" prop="weightSocre" width="90" />
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="{ row }">
              <el-button style="padding: 0" type="danger" text @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="KpiScore">
import { formatDate } from '@/utils/formatTime'
import * as KpiApi from '@/api/kpi/score.js'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const searchForm = ref({
  period: undefined
})

const periodSaved = ref(0)

const employeeOptions = ref([])
const employeeId = ref('')

onMounted(() => {
  // 默认取上个月
  const today = new Date()
  searchForm.value.period = formatDate(
    new Date(today.getFullYear(), today.getMonth() - 1),
    'YYYY-MM'
  )

  getList()
})

async function getList() {
  try {
    KpiApi.getKpiPeriodStatus({ period: searchForm.value.period }).then((data) => {
      periodSaved.value = data.status
    })
    // 获取当前要考核的人员
    const arr = await KpiApi.getKpiEmployees(searchForm.value)
    employeeOptions.value = arr || []
    if (employeeOptions.value.length > 0) {
      if (!employeeId.value) {
        employeeId.value = employeeOptions.value[0].examinedUser
      }
    } else {
      message.error('当月无待考核员工！！！')
      return
    }
    list.value =
      employeeOptions.value.find((it) => it.examinedUser == employeeId.value)
        ?.examineScoreRespVOList || []
  } finally {
    loading.value = false
  }
}

let timer = ref(null)
const lastId = ref('')
function handleSave(row) {
  try {
    lastId.value == row.id && clearTimeout(timer.value)
    timer.value = setTimeout(async () => {
      lastId.value = row.id
      // message.success('正在保存数据，请稍后')
      await KpiApi.saveKpiScore({
        id: row.id,
        score: row.score,
        remark: row.remark
      })
      message.success('修改成功！')
      getList()
    }, 2000)
  } catch (err) {
    console.log(err)
  }
}

async function handleDelete(row) {
  try {
    // 删除的二次确认
    await message.delConfirm(
      `删除后，该员工于${searchForm.value.period}将不再考核此项，是否确认删除？`
    )
    // 发起删除
    await KpiApi.deleteKpiItem({ id: row.id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

function getSummaries({ columns, data }) {
  let sums = []
  columns.forEach((column, index) => {
    if (index == 0) {
      sums[index] = '考核总分'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      if (column.property == 'weightSocre') {
        const employee = employeeOptions.value.find((it) => it.examinedUser == employeeId.value)
        sums[index] = employee.scoreTotal + '分'
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}
</script>

<style lang="scss" scoped></style>
