<template>
  <el-dialog v-model="visible" title="添加联系人" width="800px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="办公电话" prop="officePhone">
            <el-input v-model="form.officePhone" placeholder="请输入办公电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办公电话1" prop="officePhoneTwo">
            <el-input v-model="form.officePhoneTwo" placeholder="请输入办公电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购角色" prop="roleId">
            <el-select v-model="form.roleId" placeholder="请选择采购角色" clearable filterable style="width: 100%" @change="handleRoleChange">
              <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio v-for="dict in sys_user_sex" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="主联系人" prop="isPrimary">
            <el-radio-group v-model="form.isPrimary">
              <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细地址" prop="addressDetail">
            <el-cascader v-model="codeArr" :options="regionData" placeholder="请选择" @change="handleChange" style="width: 100%"></el-cascader>
          </el-form-item>
          <el-form-item prop="addressDetail">
            <el-input v-model="form.addressDetail" type="textarea" :rows="3" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
      </el-row>
    </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 type { CustomerContactForm } from '@/api/customer/customerFile/customerContact/types';
import { listRole } from '@/api/system/role';
import type { RoleVO } from '@/api/system/role/types';
import { regionData } from 'element-china-area-data';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_platform_yes_no', 'sys_user_sex'));
interface Props {
  modelValue: boolean;
  editData?: CustomerContactForm;
}

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

const roleOptions = ref<any>([]);

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

const emit = defineEmits<Emits>();
const codeArr = ref([]);
const formRef = ref<any>(null);

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

const form = reactive<CustomerContactForm>({
  contactName: '',
  phone: '',
  officePhone: '',
  officePhoneTwo: '',
  gender: '0',
  roleId: undefined,
  roleName: '',
  deptId: undefined,
  email: '',
  isPrimary: '1',
  addressDetail: '',
  addressProvince: '',
  addressCity: '',
  addressCounty: '',
  provincialCityCounty: '',
  status: '0',
  remark: ''
});

const rules = {
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  roleId: [{ required: true, message: '请选择采购角色', trigger: 'change' }],
  addressDetail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
};

const handleRoleChange = (roleId: string | number) => {
  const role = roleOptions.value.find((r) => r.roleId === roleId);
  form.roleName = role?.roleName;
};

// 监听编辑数据
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
      // 回显地址选择器
      if (newVal.addressProvince && newVal.addressCity && newVal.addressCounty) {
        codeArr.value = [newVal.addressProvince, newVal.addressCity, newVal.addressCounty] as any;
      } else {
        codeArr.value = [];
      }
    }
  },
  { immediate: true, deep: true }
);

/** 处理区域选择变化 */
const handleChange = (val: string[]) => {
  // 保存编码
  form.addressProvince = val[0];
  form.addressCity = val[1];
  form.addressCounty = val[2];

  // 根据编码获取名称
  const names: string[] = [];
  if (val[0]) {
    const province = regionData.find((item: any) => item.value === val[0]);
    if (province) {
      names.push(province.label);

      if (val[1] && province.children) {
        const city = province.children.find((item: any) => item.value === val[1]);
        if (city) {
          names.push(city.label);

          if (val[2] && city.children) {
            const county = city.children.find((item: any) => item.value === val[2]);
            if (county) {
              names.push(county.label);
            }
          }
        }
      }
    }
  }

  // 将省市区名称用斜杠连接
  form.provincialCityCounty = names.join('/');
};

/** 加载角色列表 */
const loadRoleOptions = async () => {
  try {
    const res: any = await listRole({
      pageNum: 1,
      pageSize: 9999,
      roleName: '',
      roleKey: '',
      status: ''
    } as any);

    // roleOptions.value = res?.rows || res?.data?.rows || res?.data || [];
    roleOptions.value = [
      { roleId: 1, roleName: '管理角色' },
      { roleId: 2, roleName: '采购角色' },
      { roleId: 3, roleName: '查询角色' },
      { roleId: 4, roleName: '审核角色' }
    ];
  } catch (error) {
    console.error('加载角色列表失败:', error);
    roleOptions.value = [];
  }
};

// 确认
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();
    emit('confirm', { ...form });
    handleClose();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

onMounted(() => {
  loadRoleOptions();
});

// 关闭
const handleClose = () => {
  formRef.value?.resetFields();
  codeArr.value = [];
  Object.assign(form, {
    contactName: '',
    phone: '',
    officePhone: '',
    officePhoneTwo: '',
    gender: '0',
    roleId: undefined,
    isPrimary: '1',
    addressDetail: '',
    addressProvince: '',
    addressCity: '',
    addressCounty: '',
    provincialCityCounty: '',
    status: '0',
    remark: ''
  });
  emit('update:modelValue', false);
};
</script>
