<template>
  <el-drawer
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    size="80%"
    destroy-on-close
    :with-header="false"
    append-to-body
    class="custom-drawer"
  >
    <div class="drawer-container">
      <!-- 顶部标题栏 -->
      <div class="drawer-header">
        <span class="header-title">{{ detailData.customerName || '详情' }}</span>
        <el-icon class="close-icon" @click="$emit('update:modelValue', false)"><Close /></el-icon>
      </div>
      <div class="detail-wrap">
        <!-- 左侧：跟进资料与附件 -->
        <div class="left-panel">
          <el-tabs v-model="leftTab" class="blue-tabs" tab-position="top">
            <el-tab-pane label="跟进资料" name="followup">
              <div class="pane-content">
                <!-- 基本信息 -->
                <div class="section-container">
                  <div class="section-header">基本信息</div>
                  <el-row :gutter="20" class="info-grid">
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">记录编号</span>
                        <span class="value">{{ detailData.recordsNo }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">客户编号</span>
                        <span class="value">{{ detailData.customerNo || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">客户名称</span>
                        <span class="value">{{ detailData.customerName }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">部门</span>
                        <span class="value">{{ detailData.department || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">行业</span>
                        <span class="value">{{ detailData.profession || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">负责人</span>
                        <span class="value">{{ detailData.salesman || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">对象类型</span>
                        <span class="value">
                          <template v-if="String(detailData.dataType) === '1'">项目</template>
                          <template v-else-if="String(detailData.dataType) === '2'">项目商机</template>
                          <template v-else-if="String(detailData.dataType) === '3'">年度入围</template>
                          <template v-else>通用</template>
                        </span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">拜访对象</span>
                        <span class="value">{{ detailData.goalObject }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">拜访人</span>
                        <span class="value">{{ staffOptions.find(s => String(s.staffId) === String(detailData.visitor || detailData.visitorNo))?.staffName || detailData.visitorName || detailData.visitor }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">随访人</span>
                        <span class="value">{{ detailData.followPeopleName }}</span>
                      </div>
                    </el-col>
                  </el-row>
                </div>

                <!-- 拜访信息 -->
                <div class="section-container">
                  <div class="section-header">拜访信息</div>
                  <el-row :gutter="20" class="info-grid">
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">拜访时间</span>
                        <span class="value">{{ parseTime(detailData.callDate, '{y}-{m}-{d}') }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">下次拜访时间</span>
                        <span class="value">{{ parseTime(detailData.nextCallDate, '{y}-{m}-{d}') }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">拜访方式</span>
                        <span class="value">{{ getVisitTypeName(detailData.callTypeCode) }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">拜访目的</span>
                        <span class="value">{{ detailData.callAim }}</span>
                      </div>
                    </el-col>
                    <el-col :span="24">
                      <div class="info-item">
                        <span class="label">拜访情况</span>
                        <span class="value">{{ detailData.followUpCondition }}</span>
                      </div>
                    </el-col>
                  </el-row>
                </div>

                <!-- 记录图片 -->
                <div class="section-container">
                  <div class="section-header">记录图片</div>
                  <div class="image-list">
                    <el-image
                      v-if="detailData.recordPicture"
                      style="width: 100px; height: 100px; border-radius: 4px"
                      :src="detailData.recordPicture"
                      :preview-src-list="[detailData.recordPicture]"
                    />
                    <span v-else class="empty-text">暂无图片</span>
                  </div>
                </div>

                <!-- 签到信息 -->
                <div class="section-container">
                  <div class="section-header">签到信息</div>
                  <el-row :gutter="20" class="info-grid">
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签到时间</span>
                        <span class="value">{{ detailData.signInTime ? parseTime(detailData.signInTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签退时间</span>
                        <span class="value">{{ detailData.signOutTime ? parseTime(detailData.signOutTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签到地址</span>
                        <span class="value">{{ detailData.signInAddress || detailData.address || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签到精度</span>
                        <span class="value">{{ detailData.signInAccuracy || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签到经度</span>
                        <span class="value">{{ detailData.signInLongitude || detailData.longitude || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签退精度</span>
                        <span class="value">{{ detailData.signOutAccuracy || '' }}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="info-item">
                        <span class="label">签退经度</span>
                        <span class="value">{{ detailData.signOutLongitude || '' }}</span>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="附件" name="attachment">
              <div class="pane-content">
                <div class="file-upload-row">
                  <el-upload
                    multiple
                    :action="uploadFileUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                  >
                    <el-button type="primary" icon="Upload" size="small">上传附件</el-button>
                  </el-upload>
                </div>
                <el-table :data="fileList" border class="file-table" empty-text="暂无附件">
                  <el-table-column label="文件名称" align="left" prop="fileName" min-width="200" show-overflow-tooltip />
                  <el-table-column label="文件类型" align="center" prop="fileType" width="100" />
                  <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
                    <template #default="scope">
                      {{ scope.row.fileSize ? (scope.row.fileSize / 1024).toFixed(1) + 'KB' : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="上传时间" align="center" prop="uploadTime" width="160" />
                  <el-table-column label="上传人" align="center" prop="uploader" width="100" show-overflow-tooltip />
                  <el-table-column label="操作" align="center" width="140">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="handleDownloadFile(scope.row)">下载</el-button>
                      <el-button link type="danger" size="small" @click="handleDeleteFile(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 右侧：业务动态与管理信息 (通用组件) -->
        <div class="right-panel">
          <BusinessActivity 
            :business-id="props.id" 
            business-type="record" 
            :info-data="detailData"
          >
            <template #management>
              <el-row :gutter="20" class="manage-grid">
                <el-col :span="12">
                  <div class="m-info-item">
                    <span class="m-label">创建日期</span>
                    <span class="m-value">{{ detailData.createTime || detailData.createDate ? parseTime(detailData.createTime || detailData.createDate, '{y}-{m}-{d}') : '' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-info-item">
                    <span class="m-label">创建人</span>
                    <span class="m-value">{{ getStaffName(detailData.createBy) || detailData.createByName || detailData.createUserName || detailData.nickName || detailData.visitor || '' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-info-item">
                    <span class="m-label">修改日期</span>
                    <span class="m-value">{{ detailData.updateTime || detailData.updateDate ? parseTime(detailData.updateTime || detailData.updateDate, '{y}-{m}-{d}') : '' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-info-item">
                    <span class="m-label">最后修改人</span>
                    <span class="m-value">{{ getStaffName(detailData.updateBy) || detailData.updateByName || detailData.updateUserName || detailData.followPeopleName || '' }}</span>
                  </div>
                </el-col>
              </el-row>
            </template>
          </BusinessActivity>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, watch, getCurrentInstance, toRefs } from 'vue';
import { Close, ChatLineRound, Upload } from '@element-plus/icons-vue';
import { getRecord, listRecord } from "@/api/visit/record";
import { listComStaff } from "@/api/system/comStaff/index";
import { globalHeaders } from "@/utils/request";
import BusinessActivity from '../../common/businessActivity.vue';

const proxy = getCurrentInstance().proxy;
const { visit_type: callTypeOptions } = toRefs(reactive(proxy.useDict("visit_type")));

const props = defineProps({
  modelValue: Boolean,
  id: [String, Number]
});

const emit = defineEmits(['update:modelValue']);

const detailData = ref({});
const leftTab = ref('followup');
const fileList = ref([]);

const staffOptions = ref([]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const headers = ref(globalHeaders());

// 监听 ID 变化，获取详情
watch(() => props.id, (newId) => {
  if (newId) {
    getData(newId);
  }
}, { immediate: true });

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (val) => {
  if (val && props.id) {
    getData(props.id);
  }
});

function getData(id) {
  getRecord(id).then(response => {
    detailData.value = response.data || {};
    fileList.value = response.data?.fileList || [];
  });
}



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

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.id) === strId
  );
  return staff ? (staff.staffName || staff.userName || staff.nickName) : null;
};

const getVisitTypeName = (code) => {
  if (!code && code !== 0) return '上门拜访';
  const dict = callTypeOptions.value.find(d => String(d.value) === String(code));
  return dict ? dict.label : '上门拜访';
};

const handleUploadSuccess = (res, file) => {
  if (res.code === 200) {
    const item = res.data;
    const name = item.originalName || item.fileName || file.name;
    const getExt = (n) => {
      const parts = n.split('.');
      return parts.length > 1 ? parts[parts.length - 1].toUpperCase() : '文件';
    };
    fileList.value.push({
      ossId: item.ossId,
      fileName: name,
      fileType: getExt(name),
      fileUrl: item.url,
      url: item.url,
      uploadTime: new Date().toISOString().split('T')[0],
      uploader: '当前用户'
    });
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg || '上传失败');
  }
};

const handleDeleteFile = (index) => {
  fileList.value.splice(index, 1);
};

const handleDownloadFile = (row) => {
  if (!row.fileUrl && !row.url) return;
  window.open(row.fileUrl || row.url, '_blank');
};
</script>

<style scoped lang="scss">
.drawer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-header {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  z-index: 10;
  box-sizing: border-box;
  .header-title { font-size: 16px; color: #333; font-weight: normal; line-height: 64px; }
  .close-icon { font-size: 20px; cursor: pointer; color: #999; &:hover { color: #409eff; } }
}

.detail-wrap {
  display: flex;
  height: calc(100vh - 56px);
  overflow: hidden;
  background: #fff;
  margin: 0;
  padding: 0;
}

.left-panel {
  flex: 7;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #f0f0f0;
  overflow-y: auto;
  &::-webkit-scrollbar { display: none; } /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE/Edge */
  scrollbar-width: none; /* Firefox */
}

.right-panel {
  flex: 3;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  &::-webkit-scrollbar { display: none; } /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE/Edge */
  scrollbar-width: none; /* Firefox */
  
  :deep(.activity-container) {
    .el-tabs__header {
      margin-top: 0;
      margin-bottom: 0;
      height: 48px;
      .el-tabs__nav-wrap {
        height: 100%;
        display: flex;
        align-items: center;
      }
    }
  }
}

/* 蓝色 Tab 覆盖样式 */
.blue-tabs {
  flex: 1;
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 15px;
    background: #fff;
    border-bottom: 1px solid #f2f2f2;
    height: 48px;
  }
  :deep(.el-tabs__nav-wrap::after) { height: 0; }
  :deep(.el-tabs__nav-wrap) { height: 100%; display: flex; align-items: center; }
  :deep(.el-tabs__active-bar) { background-color: #409eff; height: 3px; }
  :deep(.el-tabs__item) {
    font-size: 14px;
    color: #333;
    height: 48px;
    line-height: 48px;
    font-weight: normal !important; /* 确保不加粗 */
    &.is-active { color: #409eff; }
    &:hover { color: #409eff; }
  }
  :deep(.el-tabs__content) { 
    padding: 0;
    overflow-y: auto;
  }
}

.pane-content-custom {
  padding: 20px;
}

.pane-content {
  padding: 16px 20px;
}

.file-upload-row {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.file-table {
  width: 100%;
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    font-size: 13px;
    color: #475569;
    font-weight: normal; /* 确保不加粗 */
  }
  :deep(td.el-table__cell) {
    font-size: 13px;
  }
}

.comment-input-section {
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
  .comment-textarea {
    :deep(.el-textarea__inner) {
      border: 1px solid #e1e1e1;
      box-shadow: none;
      resize: none;
      padding: 10px;
      font-size: 13px;
      &:focus { border-color: #409eff; }
    }
  }
}

.comment-btn-row {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  .btn-comment-blue {
    background-color: #409eff;
    border-color: #409eff;
    font-size: 13px;
    padding: 7px 18px;
    display: flex;
    align-items: center;
    .mr5 { margin-right: 5px; }
  }
}

.comment-list-empty {
  text-align: center;
  color: #999;
  font-size: 13px;
  padding-top: 20px;
}

.comment-list {
  .comment-item {
    display: flex;
    padding: 14px 0;
    border-bottom: 1px solid #f0f0f0;
    &:last-child { border-bottom: none; }
  }
  .comment-avatar {
    flex-shrink: 0;
    margin-right: 12px;
    background-color: #409eff;
    font-size: 13px;
  }
  .comment-body {
    flex: 1;
    min-width: 0;
  }
  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 6px;
  }
  .comment-user {
    font-size: 13px;
    color: #333;
  }
  .comment-time {
    font-size: 12px;
    color: #999;
  }
  .comment-content {
    font-size: 13px;
    color: #555;
    line-height: 1.6;
    word-break: break-all;
  }
}

.section-container {
  margin-bottom: 30px;
}

.section-header {
  font-size: 15px;
  color: #333;
  margin-bottom: 15px;
  font-weight: normal; /* 确保不加粗 */
}

.info-grid {
  .info-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;
    font-size: 13px;
    line-height: 1.5;
    .label { color: #909399; width: 90px; flex-shrink: 0; }
    .value { color: #333; word-break: break-all; }
  }
}

.image-list {
  padding: 10px 0;
  .empty-text { color: #c0c4cc; font-size: 13px; }
}

.m-info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 13px;
  .m-label {
    color: #999;
  }
  .m-value {
    color: #333;
  }
}
</style>

<!-- 全局样式覆盖：由于 el-drawer 使用了 append-to-body，局部 scoped 样式无法穿透，必须使用全局或非 scoped 样式 -->
<style lang="scss">
.custom-drawer {
  .el-drawer__header { 
    display: none !important; 
  }
  .el-drawer__body { 
    padding: 0 !important; 
    background: #fff !important;
  }
}
</style>
