<template>
  <el-drawer
    v-model="visible"
    title="编辑联系人"
    size="80%"
    :modal="false"
    @close="handleClose"
    destroy-on-close
  >
    <div class="drawer-content">
      <el-form ref="contactPersonRef" :model="form" :rules="rules" label-width="110px" v-loading="loading">
        <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="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="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-row>

        <el-row :gutter="20">
          <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-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="在职状态" 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-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-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <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: 250px"
                  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="请选择项目角色" style="width: 100%" 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="请选择" style="width: 100%" 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="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="24">
            <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: 250px"
                  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>
      </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="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 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: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

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