<template>
  <el-drawer
    v-model="visible"
    title="新增联系人"
    size="80%"
    @close="handleClose"
    destroy-on-close
    class="custom-drawer"
  >
    <div class="drawer-content">
      <el-form ref="contactPersonRef" :model="form" :rules="rules" label-width="110px">
        
        <div class="section-title">个人资料</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人类型" prop="roleId">
              <el-radio-group v-model="form.roleId">
                <el-radio :label="'1'">公司职员</el-radio>
                <el-radio :label="'2'">关系资源人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio :label="'0'">男</el-radio>
                <el-radio :label="'1'">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable
                v-model="form.birthday"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生日"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="section-title" style="margin-top: 10px;">办公信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="归属公司" prop="belongCompanyId">
              <el-select v-model="form.belongCompanyId" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in companyOptions" :key="item.id" :label="item.companyName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择" style="width: 100%" filterable clearable @change="handleCustomerChange">
                <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在职状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="'0'">在职</el-radio>
                <el-radio :label="'1'">离职</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职位" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8">
            <el-form-item label="办公座机" prop="officePhone">
              <el-input v-model="form.officePhone" placeholder="请输入办公座机" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="办公地址" prop="addressDetail">
              <div style="display: flex; gap: 10px; width: 100%">
                <el-cascader
                  v-model="form.region"
                  :options="areaOptions"
                  :props="{ label: 'areaName', value: 'id', children: 'children' }"
                  placeholder="请选择省/市/县"
                  style="width: 200px"
                  clearable
                />
                <el-input v-model="form.addressDetail" placeholder="请输入详细地址" style="flex: 1" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="工作内容" prop="jobContent">
              <el-input v-model="form.jobContent" type="textarea" placeholder="请输入内容" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>

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

<script setup name="ContactPersonAdd">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { addContactPerson } from "@/api/customer/contactPerson";
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listProvinceWithCities } from "@/api/customer/addressArea";

const proxy = getCurrentInstance().proxy;
const router = useRouter();

const visible = ref(false);

const companyOptions = ref([]);
const customerOptions = ref([]);
const areaOptions = ref([]);

const form = reactive({
  id: null,
  contactNo: null,
  contactName: null,
  roleId: null,
  roleName: null,
  gender: null,
  age: null,
  nativePlace: null,
  birthday: null,
  belongCompanyId: null,
  customerId: null,
  customerName: null,
  status: null,
  deptId: null,
  deptName: null,
  phone: null,
  officePhone: null,
  region: [],
  homeProvinceId: null,
  homeCityId: null,
  homeAreaId: null,
  homeAddressDetail: null,
  remark: null,
  jobContent: null
});

const rules = reactive({
  contactName: [
    { required: true, message: "姓名不能为空", trigger: "blur" }
  ],
  belongCompanyId: [
    { required: true, message: "归属公司不能为空", trigger: "change" }
  ],
  customerId: [
    { required: true, message: "客户名称不能为空", trigger: "change" }
  ],
  deptName: [
    { required: true, message: "部门不能为空", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" }
  ]
});

const initOptions = async () => {
  try {
    const resCompany = await listCompanyOption();
    companyOptions.value = resCompany.data || [];

    const resCustomer = await listCustomerInfo({ pageNum: 1, pageSize: 1000 });
    customerOptions.value = resCustomer.rows || resCustomer.data || [];
    
    const resArea = await listProvinceWithCities();
    areaOptions.value = resArea.data || [];
  } catch (error) {
    console.error("加载选项失败", error);
  }
};

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

const handleCustomerChange = (val) => {
  const customer = customerOptions.value.find(item => item.id === val);
  if (customer) {
    form.customerName = customer.customerName;
  } else {
    form.customerName = '';
  }
};

const open = () => {
  visible.value = true;
  Object.assign(form, {
    id: null,
    contactNo: null,
    contactName: null,
    roleId: null,
    roleName: null,
    gender: null,
    age: null,
    nativePlace: null,
    birthday: null,
    belongCompanyId: null,
    customerId: null,
    customerName: null,
    status: null,
    deptId: null,
    deptName: null,
    phone: null,
    officePhone: null,
    region: [],
    homeProvinceId: null,
    homeCityId: null,
    homeAreaId: null,
    homeAddressDetail: null,
    remark: null,
    jobContent: null
  });
};

const emit = defineEmits(['success']);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contactPersonRef"].validate(valid => {
    if (valid) {
      // 转换地理位置 ID
      if (form.region && form.region.length > 0) {
        form.homeProvinceId = form.region[0];
        form.homeCityId = form.region[1];
        form.homeAreaId = form.region[2] || null;
      }
      // 这里的 addressDetail 实际上对应后端扩展表的 homeAddressDetail
      form.homeAddressDetail = form.addressDetail;
      
      addContactPerson(form).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        visible.value = false;
        emit('success');
      });
    }
  });
}

/** 关闭抽屉 */
function handleClose() {
  visible.value = false;
}

defineExpose({ open });
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 0;
}

.section-title {
  font-size: 15px;
  color: #409eff;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item) {
  margin-bottom: 14px;
}

.drawer-footer {
  padding: 15px 25px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 强制所有字体不加粗 */
:deep(*) {
  font-weight: 400 !important;
}
</style>

<style lang="scss">
.custom-drawer {
  .el-drawer__header {
    margin-bottom: 10px !important;
    padding-bottom: 0 !important;
  }
  .el-drawer__body {
    padding-top: 10px !important;
    padding-bottom: 0 !important;
  }
}
</style>
