<template>
  <el-drawer
    v-model="visible"
    size="80%"
    :with-header="false"
    destroy-on-close
    class="custom-detail-drawer"
  >
    <div class="detail-container" v-loading="loading">
      <!-- 自定义页眉 (放入 Body 以实现 0 间距控制) -->
      <div class="detail-header">
        <div class="header-left">
          <span class="company-name">{{ form.customerName }}</span>
        </div>

        <div class="header-right">
          <el-icon class="close-btn" @click="handleClose"><Close /></el-icon>
        </div>
      </div>

      <div class="detail-main">
        <!-- 左侧主内容区 -->
        <div class="main-content">
          <el-tabs v-model="activeTab" class="custom-tabs" @tab-change="handleTabChange">
            <el-tab-pane label="资料" name="info">
              <div class="tab-scroll-pane">
                <div class="action-bar">
                  <el-button type="primary" class="blue-btn" icon="Edit" @click="handleUpdate">编辑</el-button>
                </div>

                <div class="info-section">
                  <div class="section-title">个人信息</div>
                  <el-row class="info-row" :gutter="40">
                    <el-col :span="8"><div class="info-cell"><span class="label">人员编号</span><span class="value">{{ form.contactNo }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">姓名</span><span class="value">{{ form.contactName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">联系人类型</span><span class="value">{{ form.type == '1' ? '公司职员' : (form.type == '2' ? '关系资源人' : '') }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">性别</span><span class="value">{{ form.gender == '0' ? '男' : (form.gender == '1' ? '女' : '') }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">年龄</span><span class="value">{{ form.age }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">籍贯</span><span class="value">{{ form.nativePlace }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">生日</span><span class="value">{{ form.birthday ? form.birthday.substring(0, 10) : '' }}</span></div></el-col>
                    <el-col :span="24"><div class="info-cell"><span class="label">描述</span><span class="value">{{ form.remark }}</span></div></el-col>
                  </el-row>
                </div>

                <div class="info-section">
                  <div class="section-title">办公信息</div>
                  <el-row class="info-row" :gutter="40">
                    <el-col :span="8"><div class="info-cell"><span class="label">归属公司</span><span class="value">{{ form.belongCompanyId }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">客户名称</span><span class="value">{{ form.customerName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">在职状态</span><span class="value">{{ form.jobStatus == '1' ? '在职' : (form.jobStatus == '2' ? '离职' : '') }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">手机号码</span><span class="value">{{ form.phone }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">部门</span><span class="value">{{ form.deptName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">职位</span><span class="value">{{ form.position }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">办公座机</span><span class="value">{{ form.officePhone }}</span></div></el-col>
                    <el-col :span="16"><div class="info-cell"><span class="label">办公地址</span><span class="value">{{ (form.provincialCityCounty || '') + (form.addressDetail || '') }}</span></div></el-col>
                    <el-col :span="24"><div class="info-cell"><span class="label">工作内容</span><span class="value">{{ form.jobContent }}</span></div></el-col>
                  </el-row>
                </div>

                <div class="info-section no-border">
                  <div class="section-title">家庭信息</div>
                  <el-row class="info-row" :gutter="40">
                    <el-col :span="24"><div class="info-cell"><span class="label">家庭住址</span><span class="value">{{ form.homeAddressDetail }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">家庭情况</span><span class="value">{{ form.familyStatus }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">爱好</span><span class="value">{{ form.hobby }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">性格特征</span><span class="value">{{ form.characterTrait }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">是否抽烟</span><span class="value">{{ form.isSmoke == '1' ? '是' : '否' }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">是否喝酒</span><span class="value">{{ form.isDrink == '1' ? '是' : '否' }}</span></div></el-col>
                  </el-row>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="客户关怀" name="care">
              <div class="tab-scroll-pane">
                <div class="action-bar">
                  <el-button type="primary" class="blue-btn" icon="Plus" @click="handleCareAdd">新增</el-button>
                </div>
                <el-table :data="careList" border stripe class="care-table">
                  <el-table-column label="单据编号" align="center" prop="receiptId" />
                  <el-table-column label="登记日期" align="center" prop="createTime">
                    <template #default="scope">
                      <span>{{ scope.row.createTime ? scope.row.createTime.substring(0, 10) : '' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="关怀类型" align="center" prop="concernType">
                    <template #default="scope">
                      <span>{{ translateDict(scope.row.concernType, careTypeOptions) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="金额" align="center" prop="amount" />
                  <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleCareDetail(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 右侧侧边栏 (通用业务活动组件) -->
        <div class="sidebar-content">
          <BusinessActivity 
            v-if="form.id"
            :business-id="form.id" 
            business-type="contact"
            :info-data="form"
          />
        </div>
      </div>
    </div>
    <!-- 编辑抽屉 -->
    <contact-edit ref="editRef" @success="loadData(form.id)" />
    <!-- 新增客户关怀抽屉 -->
    <care-add ref="careAddRef" @success="handleCareTabClick" />
    <!-- 客户关怀详情 -->
    <care-detail ref="careDetailRef" />
  </el-drawer>
</template>

<script setup name="ContactPersonDetail">
import { ref, onMounted, getCurrentInstance, toRefs, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Close } from '@element-plus/icons-vue';
import { getContactPerson } from "@/api/customer/contactPerson";
import { getCustomerInfo } from "@/api/customer/customerInfo/index";
import { listCare } from "@/api/customer/crmCare";
import BusinessActivity from '../../common/businessActivity.vue';
import ContactEdit from './edit.vue';
import CareAdd from '../care/add.vue';
import CareDetail from '../care/detail.vue';
import { listComStaff } from "@/api/system/comStaff/index";

const proxy = getCurrentInstance().proxy;
const { care_type: careTypeOptions } = toRefs(reactive(proxy.useDict("care_type")));
const router = useRouter();
const route = useRoute();

const visible = ref(false);
const loading = ref(false);
const activeTab = ref('info');
const form = ref({});
const careList = ref([]);
const editRef = ref(null);
const careAddRef = ref(null);
const careDetailRef = ref(null);
const staffOptions = ref([]);

const open = (id) => {
  visible.value = true;
  if (id) {
    loadData(id);
  }
};

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

/** 获取详情 */
function loadData(id) {
  loading.value = true;
  getContactPerson(id).then(response => {
    form.value = response.data;
    // 如果接口未直接返回客户名称，尝试通过客户ID获取
    if (!form.value.customerName && form.value.customerId) {
      getCustomerInfo(form.value.customerId).then(res => {
        if (res.data && res.data.customerName) {
          form.value.customerName = res.data.customerName;
        }
      });
    }
    loading.value = false;
  });
}

/** Tab 切换处理 */
function handleTabChange(name) {
  if (name === 'care') {
    getCareList();
  }
}

/** 切换到关怀 Tab (外部调用/快捷操作) */
function handleCareTabClick() {
  activeTab.value = 'care';
  getCareList();
}

/** 获取关怀列表 */
function getCareList() {
  loading.value = true;
  listCare({ personnelNumber: form.value.id }).then(response => {
    careList.value = response.rows || [];
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    careList.value = [];
  });
}

/** 查看关怀详情 */
function handleCareDetail(row) {
  careDetailRef.value.open(row.id);
}

/** 客户关怀新增 */
function handleCareAdd() {
  careAddRef.value.open({
    customerName: form.value.customerName,
    customerId: form.value.customerId,
    contactName: form.value.contactName,
    contactId: form.value.id, // 关键：传入联系人ID
    phone: form.value.phone,
    officePhone: form.value.officePhone,
    profession: form.value.profession,
    department: form.value.deptName,
    salesman: form.value.salesman
  });
}

/** 修改按钮操作 */
function handleUpdate() {
  editRef.value.open(form.value.id);
}

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

/** 字典翻译 */
function translateDict(value, options) {
  if (!options || !value) return value;
  const item = options.find(o => String(o.value) === String(value));
  return item ? item.label : value;
}

const getStaffName = (staffId) => {
  if (!staffId) return '';
  const strId = String(staffId).trim();
  if (strId.toLowerCase() === 'admin' || strId === '1') return '超级管理员';
  if (staffId && isNaN(Number(staffId)) && strId.length > 4) return staffId;
  const staff = staffOptions.value.find(item => 
    String(item.staffId) === strId || 
    String(item.userId) === strId || 
    String(item.userName).toLowerCase() === strId.toLowerCase() ||
    String(item.id) === strId
  );
  return staff ? (staff.staffName || staff.userName || staff.nickName) : staffId;
};

onMounted(() => {
  listComStaff({ pageSize: 1000 }).then(res => {
    staffOptions.value = res.rows || res.data || [];
  });
});

defineExpose({ open });
</script>

<style scoped lang="scss">
.detail-container { 
  display: flex; flex-direction: column; height: 100vh; background-color: #fff;
  font-family: inherit;
}
.detail-header { 
  height: 48px; padding: 0 24px; background: #fff; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #f0f2f5;
  .company-name { font-size: 16px; color: #333; font-weight: normal; }
  .contact-name { margin-left: 24px; font-size: 14px; color: #86909c; }
  .close-btn { font-size: 20px; color: #94a3b8; cursor: pointer; &:hover { color: #333; } }
}
.detail-main { display: flex; flex: 1; overflow: hidden; }
.main-content { flex: 1; display: flex; flex-direction: column; background: #fff; overflow: hidden; }

.custom-tabs {
  flex: 1; display: flex; flex-direction: column; overflow: hidden;
  :deep(.el-tabs__header) { 
    margin: 0 !important; padding: 0 16px !important; background: #fff !important; height: 48px !important; 
    border-bottom: 1px solid #f0f2f5 !important;
    order: 1;
  }
  :deep(.el-tabs__nav-wrap::after) { display: none !important; }
  :deep(.el-tabs__item) { 
    height: 48px !important; line-height: 48px !important; font-size: 14px; color: #666; 
    &.is-active { color: #409eff; font-weight: 500 !important; } 
  }
  :deep(.el-tabs__active-bar) { 
    background-color: transparent !important;
    height: 3px !important;
    &::after {
      content: '';
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      width: 24px;
      height: 100%;
      background-color: #409eff;
      border-radius: 2px;
    }
    bottom: 0 !important; 
  }
  :deep(.el-tabs__content) { flex: 1; overflow-y: auto; order: 2; padding: 0; }
}

.tab-scroll-pane { padding: 24px; }
.info-section { 
  margin-bottom: 40px;
  .section-title { font-size: 15px; color: #409eff; margin-bottom: 20px; font-weight: 500; }
  &.no-border { margin-bottom: 0; }
}
.info-row { margin-bottom: 10px; }
.info-cell { 
  display: flex; margin-bottom: 18px; font-size: 13px; line-height: 1.6;
  .label { color: #999; width: 80px; flex-shrink: 0; }
  .value { color: #333; word-break: break-all; }
}

.action-bar { display: flex; justify-content: flex-end; margin-bottom: 16px; }
.blue-btn { background: #409eff !important; border-color: #409eff !important; color: #fff !important; }

.sidebar-content { width: 450px; display: flex; flex-direction: column; background: #fff; border-left: 1px solid #f0f2f5; flex-shrink: 0; }

/* 彻底隐藏所有滚动条 (包含抽屉内部和子容器) */
:deep(.el-drawer__body),
:deep(.el-tabs__content),
:deep(.tab-scroll-pane),
:deep(.sidebar-content),
:deep(*) {
  &::-webkit-scrollbar { width: 0 !important; height: 0 !important; display: none !important; }
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}
.el-popup-parent--hidden { padding-right: 0 !important; overflow: hidden !important; }

:deep(*) { font-weight: 400 !important; }
</style>
