<template>
  <Dialog :title="title" v-model="show" width="800px">
    <el-form v-loading="formLoading" :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="考核指标" prop="examineTarget">
            <el-input v-model="form.examineTarget" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="form.effectiveDate"
              type="date"
              :disabled="!!form.id"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="模式" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio
                v-for="(item, index) in prop.kpiModeOoptions"
                :key="index"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="权重" prop="weight">
            <el-input-number v-model="form.weight" :min="0" :step="1" :controls="false" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="评分上限" prop="examineScore">
            <el-input-number v-model="form.examineScore" :min="0" :step="1" :controls="false" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="考核内容" prop="examineContent">
            <Editor
              v-model:modelValue="form.examineContent"
              height="150px"
              :toolbarConfig="{
                toolbarKeys: []
              }"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="考核规则" prop="examineRule">
            <Editor
              v-model:modelValue="form.examineRule"
              height="150px"
              :toolbarConfig="{ toolbarKeys: [] }"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="考核员工" prop="examinedUserIdList">
            <div>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选
              </el-checkbox>
              <el-checkbox-group v-model="form.examinedUserIdList" @change="handleCheckedChange">
                <el-checkbox
                  v-for="item in employeeOptions"
                  :key="item.id"
                  :disabled="item.status == 1"
                  :label="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" :disabled="formLoading" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogAppraise">
import * as KpiApi from '@/api/kpi/index.js'

const prop = defineProps({
  kpiModeOoptions: {
    type: Array,
    default: () => []
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const show = ref(false)
const title = ref('')
const formType = ref('create')

const form = ref({})
const formLoading = ref(false)
const rules = ref({
  examineTarget: { required: true, message: '标题不可为空', trigger: 'blur' },
  effectiveDate: { required: true, message: '生效日期不可为空', trigger: 'blur,change' },
  examineContent: { required: true, message: '标题不可为空', trigger: 'blur' },
  examineRule: { required: true, message: '标题不可为空', trigger: 'blur' }
})

async function open(type, val) {
  show.value = true
  title.value = type == 'update' ? '修改考核项' : '新增考核项'
  formType.value = type
  resetForm()
  if (val) {
    formLoading.value = true
    try {
      form.value = await KpiApi.getKpiDetail(val)
    } finally {
      formLoading.value = false
    }
  }
  getOptions()
}

function getOptions() {
  KpiApi.getKpiEmployees().then((data) => {
    employeeOptions.value = data
    if (formType.value == 'update') {
      handleCheckedChange(form.value.examinedUserIdList)
    } else {
      handleCheckAllChange(true)
      checkAll.value = true
    }
  })
}

function resetForm() {
  form.value = {
    examineTarget: '',
    type: '3',
    weight: 0,
    examineContent: ``,
    examineRule: ``,
    examineScore: 5,
    examinedUserIdList: []
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const formRef = ref()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await KpiApi.createKpi(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await KpiApi.updateKpi(form.value)
      message.success(t('common.updateSuccess'))
    }
    show.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const checkAll = ref(false)
const isIndeterminate = ref(false)
const employeeOptions = ref([])

function handleCheckAllChange(val) {
  form.value.examinedUserIdList = val ? employeeOptions.value.map((it) => it.id) : []
  isIndeterminate.value = false
}

function handleCheckedChange(value) {
  const checkedCount = value.length
  checkAll.value = checkedCount === employeeOptions.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < employeeOptions.value.length
}
</script>

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