<template>
  <el-drawer
    v-model="visible"
    direction="rtl"
    size="80%"
    destroy-on-close
    :with-header="false"
    class="detail-drawer"
  >
    <div class="detail-container" v-loading="loading">
      <!-- 顶部 Header -->
      <div class="detail-header">
        <span class="detail-header-title">{{ form.contactPerson || '客户关怀明细' }}</span>
        <el-icon class="detail-close-btn" @click="handleClose"><Close /></el-icon>
      </div>

      <div class="detail-body">
        <!-- 左侧主内容区 -->
        <div class="detail-main">
          <!-- Tab 栏 -->
          <div class="detail-tabs">
            <div class="tab-item active">资料</div>
          </div>

          <div class="detail-content-inner">
            <!-- 基本信息 -->
            <div class="detail-section">
              <div class="section-header">基本信息</div>
              <div class="field-grid">
                <div class="field-item">
                  <span class="label">单据编号</span>
                  <span class="value">{{ form.receiptId }}</span>
                </div>
                <div class="field-item">
                  <span class="label">客户编号</span>
                  <span class="value">{{ form.customerId }}</span>
                </div>
                <div class="field-item">
                  <span class="label">客户名称</span>
                  <span class="value">{{ form.customerName }}</span>
                </div>
                <div class="field-item">
                  <span class="label">行业</span>
                  <span class="value">{{ form.profession }}</span>
                </div>
                <div class="field-item">
                  <span class="label">部门</span>
                  <span class="value">{{ getDeptName(form.department) }}</span>
                </div>
                <div class="field-item">
                  <span class="label">业务员</span>
                  <span class="value">{{ getStaffName(form.salesman) }}</span>
                </div>
              </div>
            </div>

            <!-- 关怀信息 -->
            <div class="detail-section">
              <div class="section-header">关怀信息</div>
              <div class="field-grid">
                <div class="field-item">
                  <span class="label">客户联系人</span>
                  <span class="value">{{ form.contactPerson }}</span>
                </div>
                <div class="field-item">
                  <span class="label">手机</span>
                  <span class="value">{{ form.phone }}</span>
                </div>
                <div class="field-item">
                  <span class="label">固定电话</span>
                  <span class="value">{{ form.telephone }}</span>
                </div>
                <div class="field-item">
                  <span class="label">关怀类型</span>
                  <span class="value">{{ careTypeText(form.concernType) }}</span>
                </div>
                <div class="field-item">
                  <span class="label">金额</span>
                  <span class="value">{{ formatAmount(form.amount) }}</span>
                </div>
                <div class="field-item">
                  <span class="label">需求时间</span>
                  <span class="value">{{ form.requirementDate ? form.requirementDate.substring(0, 10) : '' }}</span>
                </div>
                <div class="field-item">
                  <span class="label">状态</span>
                  <span class="value">
                    <span v-if="statusText(form.auditStatus)" class="status-tag" :class="form.auditStatus == 1 ? 'success' : 'applying'">
                      {{ statusText(form.auditStatus) }}
                    </span>
                  </span>
                </div>
                <div class="field-item">
                  <span class="label">礼品描述</span>
                  <span class="value">{{ form.giftDesc }}</span>
                </div>
                <div class="field-item full-width">
                  <span class="label">关怀理由</span>
                  <span class="value">{{ form.concernArgument }}</span>
                </div>
              </div>
            </div>

            <!-- 附件 -->
            <div class="detail-section">
              <div class="section-header">附件</div>
              <div class="attachment-area">
                <div class="attachment-label">附件</div>
                <el-table :data="fileList" border size="small" class="attachment-table" :header-cell-style="{ background: '#f8fafc' }">
                  <el-table-column prop="name" label="文件名称" />
                  <el-table-column prop="type" label="文件类型" width="120" align="center" />
                  <el-table-column prop="time" label="上传时间" width="180" align="center" />
                  <el-table-column label="操作" width="120" align="center">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleDownloadFile(scope.row)">下载</el-button>
                      <el-button link type="danger" @click="handleDeleteFile(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧侧边栏 (通用业务活动组件) -->
        <div class="detail-sidebar">
          <BusinessActivity 
            v-if="form.id"
            :business-id="form.id" 
            business-type="care"
            :info-data="{
              ...form,
              customerName: form.customerName,
              department: getDeptName(form.department),
              deptName: getDeptName(form.department)
            }"
          >
            <template #management>
              <div class="sidebar-grid">
                <div class="sidebar-item">
                  <span class="label">创建日期</span>
                  <span class="value">{{ form.createTime ? form.createTime.substring(0, 10) : '' }}</span>
                </div>
                <div class="sidebar-item">
                  <span class="label">创建人</span>
                  <span class="value">{{ (form.createByName && form.createByName !== 'admin') ? form.createByName : getStaffName(form.createBy || form.createByName) || '超级管理员' }}</span>
                </div>
                <div class="sidebar-item">
                  <span class="label">修改日期</span>
                  <span class="value">{{ form.updateTime ? form.updateTime.substring(0, 10) : '' }}</span>
                </div>
                <div class="sidebar-item">
                  <span class="label">最后修改人</span>
                  <span class="value">{{ (form.updateByName && form.updateByName !== 'admin') ? form.updateByName : getStaffName(form.updateBy || form.updateByName) || '' }}</span>
                </div>
              </div>
            </template>
          </BusinessActivity>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup name="CustomerCareDetail">
import { ref, onMounted, getCurrentInstance, toRefs } from 'vue';
import { Close } from '@element-plus/icons-vue';
import { getCare } from "@/api/customer/crmCare";
import { listComStaff } from "@/api/system/comStaff/index";
import { deptTreeSelect } from "@/api/system/user/index";
import BusinessActivity from '../../common/businessActivity.vue';

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

const visible = ref(false);
const loading = ref(false);
const form = ref({});
const staffOptions = ref([]);
const deptOptions = ref([]);
const fileList = ref([]);

/** 获取详情 */
function loadDetail(id) {
  if (id) {
    loading.value = true;
    getCare(id).then(response => {
      form.value = response.data;
      // 解析附件列表 (假设 fileNo 存储的是逗号分隔的 URL 或文件路径)
      if (form.value.fileNo) {
        const urls = form.value.fileNo.split(',');
        fileList.value = urls.map(url => {
          const fileName = url.substring(url.lastIndexOf('/') + 1);
          return {
            name: fileName,
            url: url,
            type: fileName.substring(fileName.lastIndexOf('.')),
            time: form.value.createTime ? form.value.createTime.substring(0, 10) : ''
          };
        });
      } else {
        fileList.value = [];
      }
      loading.value = false;
    }).catch(() => {
      loading.value = false;
    });
  }
}

/** 打开抽屉 */
function open(id) {
  visible.value = true;
  if (id) {
    loadDetail(id);
  }
}

defineExpose({ open });



const careTypeText = (val) => {
  const obj = careTypeOptions.value.find(item => String(item.value) === String(val));
  return obj ? obj.label : val;
};

const statusText = (status) => {
  const map = { 0: '申请中', 1: '已通过' };
  return map[status] || '';
};

const formatAmount = (val) => {
  if (val === null || val === undefined || val === '') return '0.00';
  return Number(val).toFixed(2);
};

const getDeptName = (deptId) => {
  if (!deptId) return '';
  if (form.value.deptName) return form.value.deptName;
  if (deptId && isNaN(Number(deptId))) return deptId;
  const findName = (list) => {
    if (!list || list.length === 0) return null;
    for (const item of list) {
      if (item.id == deptId || item.deptId == deptId) return item.label || item.deptName;
      if (item.children) {
        const name = findName(item.children);
        if (name) return name;
      }
    }
    return null;
  };
  return findName(deptOptions.value) || deptId;
};

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;
};

/** 加载基础选项 */
const initBaseOptions = () => {
  listComStaff({ pageSize: 1000 }).then(res => { staffOptions.value = res.rows || res.data || []; });
  deptTreeSelect().then(res => {
    const data = res.data || [];
    deptOptions.value = proxy.handleTree(data, "id");
  });
};

/** 下载文件 */
function handleDownloadFile(row) {
  if (row.url) {
    // 调用 Ruoyi 通用下载方法
    proxy.$download.resource(row.url);
  } else {
    proxy.$modal.msgError("文件地址无效，无法下载");
  }
}

/** 删除文件 */
function handleDeleteFile(row) {
  proxy.$modal.confirm('确认要删除文件「' + row.name + '」吗？').then(() => {
    // 此处由于是静态模拟数据，直接从数组移除
    const index = fileList.value.indexOf(row);
    if (index > -1) {
      fileList.value.splice(index, 1);
    }
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

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

onMounted(() => {
  initBaseOptions();
});
</script>

<style scoped lang="scss">
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  height: 48px;
  border-bottom: 1px solid #f2f2f2;
  .detail-header-title { font-size: 14px; color: #333; }
  .detail-close-btn { cursor: pointer; font-size: 18px; color: #999; }
}

.detail-body { display: flex; flex: 1; overflow: hidden; }

.detail-main { flex: 1; overflow-y: auto; border-right: 1px solid #f2f2f2; }

.detail-tabs {
  padding: 0 15px;
  height: 48px; /* 固定高度，对齐侧边栏 */
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f2f2f2;
  margin-bottom: 20px;
  background-color: #fff;
  .tab-item {
    display: flex;
    align-items: center;
    height: 100%;
    font-size: 14px;
    color: #409eff;
    border-bottom: 2px solid #409eff;
    cursor: pointer;
  }
}

.detail-content-inner { padding: 0 12px 30px; }

.detail-section {
  margin-bottom: 20px;
  .section-header {
    background-color: #f8faff;
    color: #409eff;
    padding: 6px 12px;
    font-size: 14px;
    margin-bottom: 12px;
  }
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 30px;
  padding: 0 12px;
}

.field-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  line-height: 1.5;
  .label {
    width: 100px; /* 增加固定宽度对齐 */
    color: #999;
    flex-shrink: 0;
  }
  .value {
    color: #333;
    flex: 1;
    word-break: break-all;
  }
  &.full-width { grid-column: span 2; }
}

.attachment-area {
  padding: 0 15px;
  .attachment-label { font-size: 13px; color: #999; margin-bottom: 10px; }
}

.detail-sidebar { 
  width: 450px; 
  padding: 0; /* 移除内边距以保证对齐 */
  background-color: #fff; 
  :deep(.activity-container) {
    /* 如果组件内部有自带 padding，在此处抵消 */
    margin-top: 0;
    .el-tabs__header {
      margin-top: 0;
      margin-bottom: 15px;
      height: 48px; /* 强制侧边栏 Tab 头部高度与左侧一致 */
      .el-tabs__nav-wrap {
        height: 100%;
        display: flex;
        align-items: center;
      }
    }
  }
}

.sidebar-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px 10px; }
.sidebar-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  .label { color: #999; width: 80px; flex-shrink: 0; }
  .value { color: #333; }
}

.status-tag {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 4px;
  font-size: 12px;
  &.applying {
    background-color: #f0f7ff;
    color: #409eff;
    border: 1px solid #d9ecff;
  }
  &.success {
    background-color: #f0f9eb;
    color: #67c23a;
    border: 1px solid #e1f3d8;
  }
}

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