<template>
  <el-dialog v-model="visible" title="分配技术顾问" width="600px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="技术顾问" prop="technicalAdviserId">
        <el-select v-model="form.technicalAdviserId" placeholder="请选择" clearable filterable class="w-full">
          <el-option v-for="item in comStaffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入技术顾问电话" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { listComStaff } from '@/api/company/comStaff';
import { ComStaffVO, ComStaffQuery } from '@/api/company/comStaff/types';
interface TechnicalAdviserForm {
  technicalAdviserId?: string | number;
  technicalAdviser?: string;
  contactPhone?: string;
}

interface Props {
  modelValue: boolean;
  editData?: TechnicalAdviserForm;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm', data: TechnicalAdviserForm): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  editData: undefined
});

const emit = defineEmits<Emits>();

const formRef = ref<any>(null);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const form = reactive<TechnicalAdviserForm>({
  technicalAdviserId: undefined,
  technicalAdviser: '',
  contactPhone: ''
});

// 技术顾问列表
const comStaffList = ref<ComStaffVO[]>([]);

// 初始化
onMounted(async () => {
  await loadComStaffList();
});

// 加载员工列表
const loadComStaffList = async () => {
  try {
    const query: any = { status: '0' };
    const res = await listComStaff(query);
    comStaffList.value = res.rows || [];
  } catch (error) {
    console.error('加载员工列表失败:', error);
  }
};

const rules = {
  technicalAdviserId: [{ required: true, message: '请选择技术顾问', trigger: 'change' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 监听编辑数据
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    }
  },
  { immediate: true, deep: true }
);

// 获取技术顾问名称
const getTechnicalAdviserName = (id: string | number | undefined) => {
  if (!id) return '';
  const adviser = comStaffList.value.find((item) => item.staffId === id);
  return adviser ? ` ${adviser.staffName}` : '';
};

// 确认
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();
    // 获取技术顾问名称
    form.technicalAdviser = getTechnicalAdviserName(form.technicalAdviserId);
    emit('confirm', { ...form });
    handleClose();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 关闭
const handleClose = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    technicalAdviserId: undefined,
    technicalAdviser: '',
    contactPhone: ''
  });
  emit('update:modelValue', false);
};
</script>

<style scoped lang="scss">
.w-full {
  width: 100%;
}
</style>
