<template>
  <el-drawer
    v-model="visible"
    :with-header="false"
    size="80%"
    @close="handleClose"
    destroy-on-close
    class="custom-drawer"
  >
    <div class="drawer-header">
      <div class="header-title">新增联系人</div>
      <el-icon class="close-icon" @click="handleClose"><Close /></el-icon>
    </div>
    <div class="drawer-content">
      <el-form 
        ref="contactPersonRef" 
        :model="form" 
        :rules="rules" 
        label-width="85px" 
        label-position="right"
        size="default"
      >
        <!-- 个人资料部分 -->
        <div class="section-title">个人资料</div>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="姓名：" prop="contactName">
              <el-input v-model="form.contactName" placeholder="姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型：" prop="type">
              <el-radio-group v-model="form.type">
                <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="年龄" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <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="请输入籍贯" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生日：" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="描述：" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入描述内容" 
                :rows="2" 
                maxlength="200" 
                show-word-limit 
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 办公信息部分 -->
        <div class="section-title compact-title">办公信息</div>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="归属公司：" prop="deptId">
              <el-select v-model="form.deptId" placeholder="归属公司" style="width: 100%" clearable filterable>
                <el-option v-for="item in companyOptions" :key="item.companyCode || 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%" clearable filterable>
                <el-option v-for="item in customerOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在职状态：" prop="jobStatus">
              <el-radio-group v-model="form.jobStatus">
                <el-radio label="1">在职</el-radio>
                <el-radio label="2">离职</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="部门：" prop="deptName">
              <el-input v-model="form.deptName" placeholder="部门" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职位：" prop="position">
              <el-input v-model="form.position" placeholder="职位" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码：" prop="phone">
              <el-input v-model="form.phone" placeholder="手机号码" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="办公座机：" prop="officePhone">
              <el-input v-model="form.officePhone" placeholder="座机" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="办公地址：" prop="addressDetail">
              <div style="display: flex; gap: 8px; width: 100%">
                <el-cascader
                  v-model="form.region"
                  ref="regionCascader"
                  :options="areaOptions"
                  :props="{ label: 'areaName', value: 'id', children: 'children' }"
                  placeholder="省/市/区"
                  style="width: 200px"
                  clearable
                />
                <el-input v-model="form.addressDetail" placeholder="详细地址" style="flex: 1" clearable />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="工作内容：" prop="jobContent">
              <el-input 
                v-model="form.jobContent" 
                type="textarea" 
                placeholder="工作职责描述" 
                :rows="2" 
                maxlength="200" 
                show-word-limit 
              />
            </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, getCurrentInstance, onMounted } from 'vue';
import { Close } from '@element-plus/icons-vue';
import { addContact } from "@/api/customer/crmContact";
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo";
import { listProvinceWithCities } from "@/api/customer/addressArea";

const { proxy } = getCurrentInstance();
const visible = ref(false);
const areaOptions = ref([]);
const companyOptions = ref([]);
const customerOptions = ref([]);
const regionCascader = ref(null);

const form = reactive({
  id: null,
  contactName: '',
  type: '1',
  age: '',
  gender: '0',
  nativePlace: '',
  birthday: '',
  remark: '',
  deptId: null,
  customerId: null,
  jobStatus: '1',
  deptName: '',
  position: '',
  phone: '',
  officePhone: '',
  region: [],
  addressDetail: '',
  jobContent: ''
});

const rules = reactive({
  contactName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号码", trigger: "blur" }
  ],
  officePhone: [
    { pattern: /^1[3-9]\d{9}$/, message: "座机号请输入正确的11位手机号码", trigger: "blur" }
  ]
});

const initOptions = async () => {
  try {
    const resArea = await listProvinceWithCities();
    const list = resArea.rows || [];
    areaOptions.value = handleTree(list, "id", "parentId");
    
    // 还原归属公司选项加载
    listCompanyOption().then(res => {
      companyOptions.value = res.data || [];
    });

    // 改为查询前 500 条记录，平衡数据量和性能
    listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => {
      customerOptions.value = (res.rows || []).map(item => ({ 
        label: item.customerName, 
        value: item.id,
        customerNo: item.customerNo
      }));
    });
  } catch (error) {
    console.error("加载选项失败", error);
  }
};

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

const open = (initData) => {
  visible.value = true;
  reset();
  
  // 处理传入参数：支持直接传 ID 或 传对象
  if (initData) {
    if (typeof initData === 'object') {
      const cId = initData.customerId ? Number(initData.customerId) : null;
      const dId = initData.deptId ? Number(initData.deptId) : null;
      
      if (cId) {
        form.customerId = cId;
        // 如果选项中没有当前客户，手动添加一个以确保回显名称
        if (initData.customerName && !customerOptions.value.find(o => o.value === cId)) {
          customerOptions.value.push({ label: initData.customerName, value: cId });
        }
      }
      
      if (dId) {
        form.deptId = dId;
        // 归属公司回显处理
        if (initData.deptName && !companyOptions.value.find(o => o.id === dId)) {
          companyOptions.value.push({ companyName: initData.deptName, id: dId });
        }
      }
    } else {
      form.customerId = Number(initData);
    }
  }
};

function reset() {
  Object.assign(form, {
    id: null,
    contactName: '',
    type: '1',
    age: '',
    gender: '0',
    nativePlace: '',
    birthday: '',
    remark: '',
    deptId: null,
    customerId: null,
    jobStatus: '1',
    deptName: '',
    position: '',
    phone: '',
    officePhone: '',
    region: [],
    addressDetail: '',
    jobContent: ''
  });
  if (proxy.$refs["contactPersonRef"]) {
    proxy.$refs["contactPersonRef"].resetFields();
  }
}

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

function submitForm() {
  proxy.$refs["contactPersonRef"].validate(async valid => {
    if (valid) {
      const selectedCustomer = customerOptions.value.find(c => c.value === form.customerId);
      const payload = {
        ...form,
        customerNo: selectedCustomer ? selectedCustomer.customerNo : null,
        addressProvince: form.region?.[0] ? String(form.region[0]) : null,
        addressCity: form.region?.[1] ? String(form.region[1]) : null,
        addressCounty: form.region?.[2] ? String(form.region[2]) : null,
        age: form.age ? parseInt(form.age) : null,
        platformCode: 'crm'
      };
      addContact(payload).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        visible.value = false;
        emit('success');
      });
    }
  });
}

function handleClose() {
  visible.value = false;
}

defineExpose({ open });

/** 构造树型结构数据 */
function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let pId = d[config.parentId];
    if (childrenListMap[pId] == null) {
      childrenListMap[pId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[pId].push(d);
  }

  for (let d of data) {
    let pId = d[config.parentId];
    if (nodeIds[pId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}
</script>

<style scoped lang="scss">
/* 核心：消除抽屉默认的巨大空隙 */
.drawer-header {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e2e8f0;
  .header-title {
    font-size: 15px;
    font-weight: 600;
    color: #333;
  }
  .close-icon {
    font-size: 18px;
    color: #94a3b8;
    cursor: pointer;
    &:hover { color: #409eff; }
  }
}

.drawer-content {
  padding: 10px 20px; 
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 15px;
  padding: 0 0 8px 0;
  border-bottom: 1px solid #f0f2f5;
  
  &.compact-title {
    margin-top: 10px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 18px; // 调大间距，不再极致紧凑
}

:deep(.el-form-item__label) {
  padding-right: 6px;
  font-size: 13px;
  color: #606266;
}

:deep(.el-radio-group) {
  height: 30px;
}

.drawer-footer {
  padding: 10px 20px;
  text-align: right;
  border-top: 1px solid #f2f6fc;
}

:deep(.el-input__wrapper), :deep(.el-textarea__inner) {
  padding: 1px 10px;
}

/* 适配窄屏幕 */
@media (max-width: 1200px) {
  :deep(.el-col-8) {
    max-width: 50%;
    flex: 0 0 50%;
  }
}
</style>
