<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ContestItem } from '../types'
import { getContestUnbindExpertList, getExpert } from '../api'
import { useMapStore } from '@/stores/map'

const emit = defineEmits<{
  (e: 'add', data: any): void
  (e: 'update:modelValue', visible: boolean): void
}>()
// 角色列表
const roleList = useMapStore().getMapValuesByKey('expert_role')

const detail = $ref(inject('detail') as ContestItem)

let list = $ref<any>([])
function fetchList() {
  getContestUnbindExpertList({ competition_id: detail.id }).then(res => {
    list = res.data.list || []
  })
}
let info = $ref<any>()
function fetchInfo(id: string) {
  if (id) {
    getExpert({ id }).then(res => {
      info = res.data.detail
    })
  } else {
    info = undefined
  }
}
onMounted(() => {
  fetchList()
})

const formRef = $ref<FormInstance>()
const form = reactive({
  role: '',
  id: ''
})
const rules = ref<FormRules>({
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  id: [{ required: true, message: '请选择专家', trigger: 'change' }]
})

// 添加
function handleSubmit() {
  formRef?.validate().then(() => {
    emit('add', Object.assign(info, { info: { role: form.role, id: '0' }, expert_id: form.id, id: '0' }))
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog title="添加专家" width="500px" @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="right" label-width="100px" label-suffix=":">
      <el-form-item label="赛项名称">{{ detail.name }}</el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="form.role" style="width: 100%">
          <el-option v-for="item in roleList" :key="item.id" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专家" prop="id">
        <el-select v-model="form.id" @change="fetchInfo" style="width: 100%">
          <el-option v-for="item in list" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <template v-if="info">
        <el-form-item label="联系电话">{{ info.mobile }}</el-form-item>
        <el-form-item label="所在单位">{{ info.company }}</el-form-item>
        <el-form-item label="职务">{{ info.position.label }}</el-form-item>
      </template>
    </el-form>
    <el-row justify="center">
      <el-button type="primary" round auto-insert-space @click="handleSubmit">添加</el-button>
      <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>
