<template>
  <el-drawer
    v-model="visible"
    :title="form.id ? '编辑联系人' : '新建联系人'"
    size="80%"
    :modal="false"
    @close="handleClose"
    destroy-on-close
    class="contact-form-drawer"
    :with-header="false"
  >
    <div class="form-container" v-loading="loading">
      <div class="form-toolbar">
        <div class="toolbar-left">
          <span class="breadcrumb" v-if="form.contactNo">个人资料 / <span class="highlight">人员编号: {{ form.contactNo }}</span></span>
          <span class="breadcrumb" v-else>新建联系人</span>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" icon="Check" @click="submitForm">保存</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </div>

      <el-form ref="contactPersonRef" :model="form" :rules="rules" label-width="120px" label-position="right" label-suffix="：">
        <!-- 个人信息 -->
        <div class="form-section">
          <div class="section-title">个人信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="人员编号">
                <el-input :model-value="form.contactNo || ''" disabled />
              </el-form-item>
            </el-col>
            <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="type">
                <el-select v-model="form.type" placeholder="请选择" class="w100">
                  <el-option label="公司职员" value="1" />
                  <el-option label="关系资源人" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="form.gender" placeholder="请选择" class="w100">
                  <el-option label="男" value="0" />
                  <el-option label="女" value="1" />
                </el-select>
              </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-col :span="8">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <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="3" maxlength="200" show-word-limit />
              </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="归属公司">
                <el-input :model-value="form.companyName || '优易达科技集团有限公司'" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input :model-value="form.customerName || ''" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="在职状态" prop="jobStatus">
                <el-select v-model="form.jobStatus" placeholder="请选择" class="w100">
                  <el-option label="在职" value="1" />
                  <el-option label="离职" value="2" />
                </el-select>
              </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-col :span="8">
              <el-form-item label="部门" prop="deptName">
                <el-input v-model="form.deptName" placeholder="请输入部门" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="职位" prop="position">
                <el-input v-model="form.position" placeholder="请输入职位" />
              </el-form-item>
            </el-col>
            <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="8">
              <el-form-item label="办公地址" prop="addressDetail">
                <div style="display: flex; gap: 10px; width: 100%">
                  <el-cascader
                    v-model="form.region"
                    ref="regionCascader"
                    :options="areaOptions"
                    :props="{ label: 'areaName', value: 'id', children: 'children' }"
                    placeholder="请选择"
                    style="width: 150px"
                    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="2" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目角色" prop="projectRole">
                <el-select v-model="form.projectRole" placeholder="请选择项目角色" class="w100" clearable>
                  <el-option v-for="dict in projectRoleOptions" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否关键人" prop="isKeyPerson">
                <el-select v-model="form.isKeyPerson" placeholder="请选择" class="w100" clearable>
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="公关情况" prop="prStatus">
                <el-input v-model="form.prStatus" type="textarea" placeholder="请输入内容" :rows="2" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

        <div class="section-title" style="margin-top: 10px;">家庭信息</div>
        <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="家庭住址" prop="homeAddressDetail">
                <div style="display: flex; gap: 10px; width: 100%">
                  <el-cascader
                    v-model="form.homeRegion"
                    :options="areaOptions"
                    :props="{ label: 'areaName', value: 'id', children: 'children' }"
                    placeholder="请选择"
                    style="width: 200px"
                    clearable
                  />
                  <el-input v-model="form.homeAddressDetail" placeholder="请输入详细地址" style="flex: 1" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="家庭情况" prop="familyStatus">
                <el-input v-model="form.familyStatus" placeholder="请输入家庭情况" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="爱好" prop="hobby">
                <el-input v-model="form.hobby" placeholder="请输入爱好" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性格特征" prop="characterTrait">
                <el-input v-model="form.characterTrait" placeholder="请输入性格特征" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="是否抽烟" prop="isSmoke">
                <el-radio-group v-model="form.isSmoke">
                  <el-radio value="1">是</el-radio>
                  <el-radio value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否喝酒" prop="isDrink">
                <el-radio-group v-model="form.isDrink">
                  <el-radio value="1">是</el-radio>
                  <el-radio value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script setup name="ContactPersonEdit">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getContactPerson } from "@/api/customer/contactPerson";
import { updateContact } from "@/api/customer/crmContact";
import { listProvinceWithCities } from "@/api/customer/addressArea";
const { proxy } = getCurrentInstance();
const { LXRJE0001: projectRoleOptions } = proxy.useDict("LXRJE0001");
const router = useRouter();
const route = useRoute();

const visible = ref(false);
const loading = ref(false);
const activeTab = ref("basic");

const areaOptions = ref([]);
const regionCascader = ref(null);

const data = reactive({
  form: {
    id: null,
    customerId: null,
    contactNo: null,
    contactName: null,
    type: '1',
    gender: '0',
    age: null,
    nativePlace: null,
    birthday: null,
    jobStatus: '1',
    deptName: null,
    position: null,
    phone: null,
    officePhone: null,
    region: [],
    addressDetail: null,
    jobContent: null,
    projectRole: null,
    isKeyPerson: 0,
    prStatus: null,
    homeRegion: [],
    homeAddressDetail: null,
    familyStatus: null,
    hobby: null,
    characterTrait: null,
    isSmoke: '0',
    isDrink: '0',
    remark: null
  },
  rules: {
    contactName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "联系人类型不能为空", trigger: "change" }
    ],
    jobStatus: [
      { required: true, message: "在职状态不能为空", trigger: "change" }
    ],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }
    ],
    deptName: [
      { required: true, message: "部门不能为空", trigger: "blur" }
    ],
    position: [
      { required: true, message: "职位不能为空", trigger: "blur" }
    ]
  }
});

const { form, rules } = toRefs(data);

const open = (id, customerId) => {
  reset();
  visible.value = true;
  if (id) {
    loadData(id);
  } else if (customerId) {
    form.value.customerId = customerId;
  }
};

/** 重置表单 */
function reset() {
  form.value = {
    id: null,
    customerId: null,
    contactNo: null,
    contactName: null,
    type: '1',
    gender: '0',
    age: null,
    nativePlace: null,
    birthday: null,
    jobStatus: '1',
    deptName: null,
    position: null,
    phone: null,
    officePhone: null,
    region: [],
    addressDetail: null,
    jobContent: null,
    projectRole: null,
    isKeyPerson: 0,
    prStatus: null,
    homeRegion: [],
    homeAddressDetail: null,
    familyStatus: null,
    hobby: null,
    characterTrait: null,
    isSmoke: '0',
    isDrink: '0',
    remark: null
  };
  if (proxy.$refs["contactPersonRef"]) {
    proxy.$refs["contactPersonRef"].resetFields();
  }
}

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

/** 获取详情 */
function loadData(id) {
  loading.value = true;
  getContactPerson(id).then(response => {
    const resData = response.data;
    
    // 区域反查逻辑 (适配代码转换)
    const findIdByCode = (code) => {
        if (!code) return null;
        const findInTree = (nodes, targetCode) => {
            for (const node of nodes) {
                if (String(node.areaCode) === String(targetCode)) return node.id;
                if (node.children) {
                    const found = findInTree(node.children, targetCode);
                    if (found) return found;
                }
            }
            return null;
        };
        return findInTree(areaOptions.value, code);
    };

    // 初始化办公地址 region (使用 addressProvince/City/County)
    resData.region = [];
    if (resData.addressProvince) {
        const pid = /^\d+$/.test(resData.addressProvince) && resData.addressProvince.length < 5 ? resData.addressProvince : findIdByCode(resData.addressProvince);
        if (pid) resData.region.push(Number(pid));
    }
    if (resData.addressCity) {
        const cid = /^\d+$/.test(resData.addressCity) && resData.addressCity.length < 7 ? resData.addressCity : findIdByCode(resData.addressCity);
        if (cid) resData.region.push(Number(cid));
    }
    if (resData.addressCounty) {
        const aid = /^\d+$/.test(resData.addressCounty) && resData.addressCounty.length < 9 ? resData.addressCounty : findIdByCode(resData.addressCounty);
        if (aid) resData.region.push(Number(aid));
    }

    // 初始化家庭地址 homeRegion
    resData.homeRegion = [];
    if (resData.homeProvinceId) resData.homeRegion.push(Number(resData.homeProvinceId));
    if (resData.homeCityId) resData.homeRegion.push(Number(resData.homeCityId));
    if (resData.homeAreaId) resData.homeRegion.push(Number(resData.homeAreaId));
    
    form.value = resData;
    loading.value = false;
  });
}

onMounted(async () => {
  const resArea = await listProvinceWithCities();
  const list = resArea.rows || [];
  if (list.length > 0) {
    areaOptions.value = handleTree(list, "id", "parentId");
  }
});

/** 构造树型结构数据 */
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;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contactPersonRef"].validate(valid => {
    if (valid) {
      // 自动映射 roleId
      form.value.roleId = form.value.type === '1' ? 1 : 2;

      // 获取地址名称
      const checkedNodes = regionCascader.value?.getCheckedNodes();
      let provincialCityCounty = form.value.provincialCityCounty;
      if (checkedNodes && checkedNodes.length > 0) {
        provincialCityCounty = checkedNodes[0].pathLabels.join("");
      }

      // 获取选中的 AreaCode 列表 (用于办公地址转换)
      const findCodeById = (id) => {
          const findInTree = (nodes, targetId) => {
              for (const node of nodes) {
                  if (Number(node.id) === Number(targetId)) return node.areaCode;
                  if (node.children) {
                      const found = findInTree(node.children, targetId);
                      if (found) return found;
                  }
              }
              return null;
          };
          return findInTree(areaOptions.value, id);
      };

      const payload = {
        ...form.value,
        // 办公地址 ID (Long)
        provinceId: form.value.region?.[0] || null,
        cityId: form.value.region?.[1] || null,
        districtId: form.value.region?.[2] || null,
        // 办公地址编码 (String) - 转换为后端需要的 AreaCode
        addressProvince: form.value.region?.[0] ? findCodeById(form.value.region[0]) : null,
        addressCity: form.value.region?.[1] ? findCodeById(form.value.region[1]) : null,
        addressCounty: form.value.region?.[2] ? findCodeById(form.value.region[2]) : null,
        provincialCityCounty: provincialCityCounty,
        // 家庭地址 ID
        homeProvinceId: form.value.homeRegion?.[0] || null,
        homeCityId: form.value.homeRegion?.[1] || null,
        homeAreaId: form.value.homeRegion?.[2] || null
      };
      
      updateContact(payload).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        visible.value = false;
        emit('success');
      });
    }
  });
}

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

defineExpose({ open });
</script>

<style lang="scss" scoped>
.contact-form-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
  }
}

.form-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.form-toolbar {
  height: 56px;
  padding: 0 24px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;

  .toolbar-left {
    .breadcrumb {
      font-size: 14px;
      color: #606266;
      .highlight {
        color: #409eff;
        font-weight: 500;
      }
    }
  }
}

.el-form {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  
  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}

.form-section {
  padding: 0;
  margin-bottom: 0;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 24px;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      width: 4px;
      height: 16px;
      background-color: #409eff;
      margin-right: 8px;
      border-radius: 2px;
    }
  }
}

.w100 {
  width: 100%;
}
</style>
