<template>
  <el-drawer v-model="visible" @update:model-value="val => $emit('update:modelValue', val)" size="80%" destroy-on-close class="custom-drawer" :with-header="false">
    <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">
          <el-tab-pane label="基本资料" name="baseInfo">
            <div class="info-section">
              <div class="info-title">基本信息</div>
              <el-row class="info-row">
                <el-col :span="12" class="info-col">
                  <span class="info-label">日程编号</span>
                  <span class="info-value">{{ detailData.scheduleNo?.replace('RC', '') }}</span>
                </el-col>
                <el-col :span="12" class="info-col">
                  <span class="info-label">客户名称</span>
                  <span class="info-value">{{ detailData.customerName }}</span>
                </el-col>
              </el-row>
              <el-row class="info-row">
                <el-col :span="12" class="info-col">
                  <span class="info-label">拜访人</span>
                  <span class="info-value">{{ staffOptions.find(s => String(s.staffId) === String(detailData.callPeopleNo || detailData.callPeopleName))?.staffName || detailData.callPeopleName }}</span>
                </el-col>
                <el-col :span="12" class="info-col">
                  <span class="info-label">拜访日期</span>
                  <span class="info-value">{{ parseTime(detailData.callDate, '{y}-{m}-{d}') }}</span>
                </el-col>
                <el-col :span="12" class="info-col" style="margin-top: 15px;">
                  <span class="info-label">随访人</span>
                  <span class="info-value">{{ detailData.followPeopleName }}</span>
                </el-col>
              </el-row>
              <el-row class="info-row">
                <el-col :span="12" class="info-col">
                  <span class="info-label">状态</span>
                  <span class="info-value">{{ scheduleStatusOptions.find(d => String(d.value) === String(detailData.scheduleStatus))?.label || (String(detailData.scheduleStatus) === '0' ? '未执行' : (String(detailData.scheduleStatus) === '1' ? '已执行' : '放弃执行')) }}</span>
                </el-col>
                <el-col :span="12" class="info-col">
                  <span class="info-label">拜访目的</span>
                  <span class="info-value">{{ detailData.purposeVisit }}</span>
                </el-col>
              </el-row>
              <el-row class="info-row">
                <el-col :span="12" class="info-col">
                  <span class="info-label">关联类型</span>
                  <span class="info-value">{{ relevanceOptions.find(d => String(d.value) === String(detailData.relevanceType))?.label || (String(detailData.relevanceType) === '0' ? '客户' : (String(detailData.relevanceType) === '1' ? '项目' : '供应商')) }}</span>
                </el-col>
                <el-col :span="12" class="info-col">
                  <span class="info-label">关联对象</span>
                  <span class="info-value">{{ detailData.objectName }}</span>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="right-panel">
        <BusinessActivity 
          v-if="detailData.id"
          :business-id="detailData.id" 
          business-type="routine"
          :info-data="detailData"
        >
          <template #management>
            <div class="manage-info">
              <el-row class="manage-row">
                <el-col :span="12" class="manage-col">
                  <span class="label">创建日期</span>
                  <span class="value">{{ detailData.createTime || detailData.createDate ? parseTime(detailData.createTime || detailData.createDate, '{y}-{m}-{d}') : '' }}</span>
                </el-col>
                <el-col :span="12" class="manage-col">
                  <span class="label">创建人</span>
                  <span class="value">{{ findStaffName(detailData.createByName || detailData.createUserName || detailData.nickName || detailData.createBy) || '' }}</span>
                </el-col>
              </el-row>
              <el-row class="manage-row">
                <el-col :span="12" class="manage-col">
                  <span class="label">修改日期</span>
                  <span class="value">{{ detailData.updateTime || detailData.updateDate ? parseTime(detailData.updateTime || detailData.updateDate, '{y}-{m}-{d}') : '' }}</span>
                </el-col>
                <el-col :span="12" class="manage-col">
                  <span class="label">最后修改人</span>
                  <span class="value">{{ findStaffName(detailData.updateByName || detailData.updateUserName || detailData.updateBy) || '' }}</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </BusinessActivity>
      </div>
    </div>

    <!-- 新增跟进记录对话框 -->
    <el-dialog title="跟进记录" v-model="recordDialogOpen" width="800px" append-to-body destroy-on-close class="record-add-dialog">
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="120px">
        <el-form-item label="客户：">
          <span style="color: #333;">{{ detailData.customerName || '' }}</span>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="随访人：" prop="accompanyPerson">
              <el-select v-model="recordForm.accompanyPerson" placeholder="请选择" style="width: 100%" clearable filterable>
                  <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拜访方式：" prop="visitType">
              <el-select v-model="recordForm.visitType" placeholder="请选择" style="width: 100%">
                <el-option v-for="dict in visitTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访时间：" prop="visitTime">
              <el-date-picker v-model="recordForm.visitTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次拜访时间：" prop="nextVisitTime">
              <el-date-picker v-model="recordForm.nextVisitTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="拜访目的：" prop="purpose">
          <el-input v-model="recordForm.purpose" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="跟进情况：" prop="progress">
          <el-input v-model="recordForm.progress" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="记录图片：">
          <div style="width: 80px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 4px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: #999;">
            <el-icon :size="20"><Plus /></el-icon>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRecord">确 认</el-button>
          <el-button @click="recordDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance, toRefs } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { getRoutine } from "@/api/visit/routine";
import { listComStaff } from "@/api/system/comStaff/index";
import { addRecord, listRecord } from "@/api/visit/record";
import { listOperateLog } from "@/api/visit/operateLog";
import BusinessActivity from '../../common/businessActivity.vue';

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

const emit = defineEmits(['update:modelValue']);
const proxy = getCurrentInstance().proxy;
const { 
  visit_type: visitTypeOptions, 
  schedule_status: scheduleStatusOptions, 
  relevance_type: relevanceOptions 
} = toRefs(reactive(proxy.useDict("visit_type", "schedule_status", "relevance_type")));

const visible = ref(false);
const detailData = ref({});
const leftTab = ref('baseInfo');
const rightTab = ref('record');
const operateLogs = ref([]);
const recordList = ref([]);
const recordLoading = ref(false);

const staffOptions = ref([]);

const recordDialogOpen = ref(false);
const recordFormRef = ref(null);
const recordForm = ref({
  accompanyPerson: undefined,
  visitType: undefined,
  visitTime: undefined,
  nextVisitTime: undefined,
  purpose: undefined,
  progress: undefined
});

const recordRules = reactive({
  visitType: [{ required: true, message: "请选择拜访方式", trigger: "change" }],
  visitTime: [{ required: true, message: "请选择拜访时间", trigger: "change" }],
  purpose: [{ required: true, message: "请输入拜访目的", trigger: "blur" }],
  progress: [{ required: true, message: "请输入跟进情况", trigger: "blur" }]
});

watch(() => props.modelValue, (val) => {
  visible.value = val;
});

watch(() => props.id, (newVal) => {
  if (newVal) {
    getDetail(newVal);
  }
});

function getDetail(id) {
  getRoutine(id).then(response => {
    detailData.value = response.data || {};
    getRecordList(id);
    getOperateLogs(id);
    getOptions();
  });
}

function getRecordList(routineId) {
  recordLoading.value = true;
  listRecord({ objectNo: routineId }).then(res => {
    recordList.value = res.rows || [];
    recordLoading.value = false;
  }).catch(() => {
    recordLoading.value = false;
  });
}

function getOperateLogs(id) {
  listOperateLog({ objectNo: String(id) }).then(res => {
    operateLogs.value = res.data || res.rows || [];
  });
}

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

const findStaffName = (val) => {
  if (!val) return '';
  if (!isNaN(Number(val))) {
    const staff = staffOptions.value.find(s => String(s.staffId) === String(val) || String(s.userId) === String(val) || String(s.userNo) === String(val));
    return staff ? (staff.staffName || staff.realName || staff.userName) : val;
  }
  return val;
};

const handleNewRecord = () => {
  recordForm.value = {
    accompanyPerson: undefined,
    visitType: undefined,
    visitTime: undefined,
    nextVisitTime: undefined,
    purpose: undefined,
    progress: undefined
  };
  recordDialogOpen.value = true;
};

const submitRecord = () => {
  recordFormRef.value.validate(valid => {
    if (valid) {
      // 辅助函数：纯数字视为 ID，不写入
      const safeText = (val) => (val && !isNaN(Number(val)) ? '' : (val || ''));
      const data = {
        objectNo: detailData.value.id,
        customerName: detailData.value.customerName,
        customerNo: detailData.value.customerNo,
        department: safeText(detailData.value.department),
        deptName: safeText(detailData.value.department),
        profession: safeText(detailData.value.profession),
        salesman: detailData.value.callPeopleName || '',
        visitor: detailData.value.callPeopleName || '',
        goalObject: detailData.value.objectName || detailData.value.customerName,
        followPeopleName: recordForm.value.accompanyPerson,
        callTypeCode: recordForm.value.visitType,
        callDate: recordForm.value.visitTime,
        nextCallDate: recordForm.value.nextVisitTime,
        callAim: recordForm.value.purpose,
        followUpCondition: recordForm.value.progress,
        platformCode: 'crm'
      };
      addRecord(data).then(response => {
        proxy.$modal.msgSuccess("新增跟进记录成功");
        recordDialogOpen.value = false;
        getRecordList(detailData.value.id);
      });
    }
  });
};
</script>

<style scoped lang="scss">
/* 详情抽屉样式 */
:deep(.custom-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fff !important;
    color: #333;
    font-weight: normal;
  }
}
.drawer-header {
  height: 64px; display: flex; justify-content: space-between; align-items: center;
  padding: 0 20px; border-bottom: 1px solid #f0f0f0; background-color: #fff; width: 100%; box-sizing: border-box;
  .header-title { font-size: 18px; font-weight: normal; color: #333; }
  .close-icon { cursor: pointer; color: #999; font-size: 20px; &:hover { color: #409eff; } }
}
.custom-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    background-color: #f5f7fa;
  }
}

.detail-wrap {
  display: flex;
  height: calc(100vh - 64px);
  overflow: hidden;
  
  .left-panel {
    flex: 1;
    background: #fff;
    padding: 0;
    margin-right: 10px;
    border-right: 1px solid #ebeef5;
    overflow-y: auto;
    &::-webkit-scrollbar { display: none; }
    -ms-overflow-style: none;
    scrollbar-width: none;

    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0 15px;
      height: 48px;
      border-bottom: 1px solid #f2f2f2;
    }
    :deep(.el-tabs__nav-wrap::after) { height: 0; }
    :deep(.el-tabs__nav-wrap) { height: 100%; display: flex; align-items: center; }
    :deep(.el-tabs__item) {
      font-size: 14px;
      height: 48px;
      line-height: 48px;
      font-weight: normal !important;
      &.is-active {
        color: #409eff;
      }
    }
    :deep(.el-tabs__active-bar) {
      background-color: #409eff;
    }

    .info-section {
      padding: 15px 20px;
      padding-top: 5px;
      
      .info-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 15px;
        font-weight: normal;
      }
      
      .info-row {
        margin-bottom: 15px;
        .info-col {
          display: flex;
          align-items: flex-start;
          .info-label {
            width: 80px;
            color: #909399;
            font-size: 13px;
            flex-shrink: 0;
          }
          .info-value {
            font-size: 13px;
            color: #333;
          }
        }
      }
    }
  }
  
  .right-panel {
    width: 30%;
    background: #fff;
    padding: 0;
    overflow-y: hidden; // 让内部的 tabs 自己处理滚动
    display: flex;
    flex-direction: column;
    &::-webkit-scrollbar { display: none; }
    -ms-overflow-style: none;
    scrollbar-width: none;
    
    :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;
        }
      }
    }
    :deep(.el-tabs__item) {
      font-size: 14px;
      font-weight: normal !important;
    }

    .record-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .visit-type-wrap {
        display: flex;
        align-items: center;
        .visit-type-label {
          font-size: 12px;
          color: #909399;
          margin-right: 8px;
        }
      }
    }

    .record-list {
      .record-item {
        padding: 15px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        margin-bottom: 15px;
        
        .record-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          
          .visit-person {
            font-size: 14px;
            font-weight: normal;
            color: #333;
            margin-right: 10px;
          }
          .visit-time {
            font-size: 12px;
            color: #909399;
            margin-right: auto;
          }
        }
        
        .record-content {
          font-size: 13px;
          
          .aim-title, .progress-title {
            color: #909399;
            margin-top: 8px;
          }
          .aim-text, .progress-text {
            color: #333;
            margin-top: 4px;
          }
        }
      }
      
      .empty-text {
        text-align: center;
        padding: 50px 0;
        color: #909399;
      }
    }

    .log-list {
      .log-item {
        padding: 10px 0;
        border-bottom: 1px dashed #ebeef5;
        font-size: 13px;
        
        .time { color: #909399; margin-right: 10px; }
        .user { font-weight: normal; color: #333; margin-right: 5px; }
        .action { color: #666; }
        .target { color: #409eff; }
      }
    }

    .manage-info {
      .manage-row {
        margin-bottom: 20px;
        .manage-col {
          display: flex;
          align-items: center;
          font-size: 13px;
          .label { color: #909399; margin-right: 8px; flex-shrink: 0; }
          .value { color: #333; }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>
