<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="80px">
        <el-form-item label="拜访人" prop="callPeopleName" class="custom-form-item">
          <el-input v-model="queryParams.callPeopleName" placeholder="请输入拜访人" clearable />
        </el-form-item>
        <el-form-item label="拜访日期" prop="callDate" class="custom-form-item">
          <el-date-picker v-model="queryParams.callDate" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="日程状态" prop="scheduleStatus" class="custom-form-item">
          <el-select v-model="queryParams.scheduleStatus" placeholder="请选择" clearable>
            <el-option
              v-for="dict in scheduleStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <div class="search-btns-area">
          <el-button icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['visit:routine:add']">新增</el-button>
        </div>
      </el-form>
    </el-card>

    <div class="title-container">
      <span class="list-title">拜访日程信息列表</span>
    </div>

    <!-- 列表区域 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="dataList" border class="custom-table" :header-cell-style="{ background: '#f8fafc', color: '#333', fontWeight: 'bold' }">
        <el-table-column label="日程编号" align="center" prop="scheduleNo" width="160">
          <template #default="scope">
            <span class="link-text" @click="handleDetail(scope.row)">{{ scope.row.scheduleNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联计划" align="center" prop="planNo" width="160" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="拜访人" align="center" prop="callPeopleName" width="100">
          <template #default="scope">
            <span>{{ scope.row.callPeopleName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拜访日期" align="center" prop="callDate" width="120" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.callDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="随访人" align="center" prop="followPeopleName" width="120" />
        <el-table-column label="关联对象" align="center" prop="objectName" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.objectName || scope.row.customerName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="scheduleStatus" width="100">
          <template #default="scope">
            <el-tag :type="String(scope.row.scheduleStatus) === '0' ? 'warning' : (String(scope.row.scheduleStatus) === '1' ? 'success' : 'danger')">
              {{ scheduleStatusOptions.find(d => String(d.dictValue) === String(scope.row.scheduleStatus))?.dictLabel || (String(scope.row.scheduleStatus) === '0' ? '未执行' : (String(scope.row.scheduleStatus) === '1' ? '已执行' : '放弃执行')) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联类型" align="center" prop="relevanceType" width="100">
          <template #default="scope">
            {{ relevanceOptions.find(d => String(d.dictValue) === String(scope.row.relevanceType))?.dictLabel || (String(scope.row.relevanceType) === '0' ? '客户' : (String(scope.row.relevanceType) === '1' ? '项目' : '供应商')) }}
          </template>
        </el-table-column>
        <el-table-column label="重要级别" align="center" prop="importantLevel" width="100">
          <template #default="scope">
            <span>{{ importanceOptions.find(d => String(d.dictValue) === String(scope.row.importantLevel))?.dictLabel || scope.row.importantLevel || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['visit:routine:edit']">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['visit:routine:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="routineRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联计划：" prop="planNo">
          <el-select v-model="form.planNo" placeholder="请选择" style="width: 100%" clearable>
            <el-option v-for="item in planOptions" :key="item.id" :label="item.planNo" :value="item.planNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联类型：" prop="relevanceType">
          <el-radio-group v-model="form.relevanceType">
            <el-radio value="0">客户</el-radio>
            <el-radio value="1">项目商机</el-radio>
            <el-radio value="2">供应商</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户：" prop="customerNo">
          <el-select v-model="form.customerNo" placeholder="请选择" style="width: 100%" clearable filterable @change="handleCustomerChange">
            <el-option v-for="item in customerOptions" :key="item.customerNo" :label="item.customerName" :value="item.customerNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="拜访人：" prop="callPeopleNo">
          <el-select v-model="form.callPeopleNo" placeholder="请选择拜访人" style="width: 100%" clearable filterable @change="handleStaffChange">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="`${item.staffName}${item.staffCode ? ' (' + item.staffCode + ')' : ''}`" :value="item.staffId" />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="拜访日期：" prop="callDate">
              <el-date-picker v-model="form.callDate" 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="importantLevel">
              <el-select v-model="form.importantLevel" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dict in importanceOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="随访人：" prop="followPeopleName">
          <el-select v-model="form.followPeopleName" placeholder="请选择" style="width: 100%" clearable filterable>
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="`${item.staffName}${item.staffCode ? ' (' + item.staffCode + ')' : ''}`" :value="item.staffName" />
          </el-select>
        </el-form-item>

        <el-form-item label="拜访目的：" prop="purposeVisit">
          <el-input type="textarea" :rows="4" v-model="form.purposeVisit" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹出/抽屉界面 -->
    <el-drawer v-model="detailOpen" size="80%" destroy-on-close class="custom-drawer">
      <template #header>
        <div class="drawer-title">{{ detailData.customerName || '详情信息' }}</div>
      </template>
      <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 }}</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">{{ 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.dictValue) === String(detailData.scheduleStatus))?.dictLabel || (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.dictValue) === String(detailData.relevanceType))?.dictLabel || (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">
          <el-tabs v-model="rightTab">
            <el-tab-pane label="跟进记录" name="record">
              <div class="record-actions">
                <el-button type="primary" link icon="Plus" @click="handleNewRecord">新建跟进记录</el-button>
                <div class="visit-type-wrap">
                  <span class="visit-type-label">拜访方式</span>
                  <el-select style="width: 150px;" placeholder="请选择">
                    <el-option v-for="dict in visitTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                  </el-select>
                </div>
              </div>

              <div class="record-list" v-loading="recordLoading">
                <div v-if="recordList && recordList.length > 0">
                   <div v-for="(item, index) in recordList" :key="index" class="record-item">
                     <div class="record-header">
                       <span class="visit-person">{{ item.visitor || item.createBy || '跟进人' }}</span>
                       <span class="visit-time">{{ parseTime(item.callDate || item.createTime, '{y}-{m}-{d}') }}</span>
                       <el-tag size="small" type="success" class="type-tag">{{ visitTypeOptions.find(d => d.dictValue == item.callTypeCode)?.dictLabel || '跟进' }}</el-tag>
                     </div>
                     <div class="record-content">
                       <div class="aim-title">拜访目的：</div>
                       <div class="aim-text">{{ item.callAim || '-' }}</div>
                       <div class="progress-title">跟进情况：</div>
                       <div class="progress-text">{{ item.followUpCondition || '-' }}</div>
                     </div>
                   </div>
                </div>
                <div v-else class="empty-text">暂无跟进记录数据</div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="log">
              <div class="log-list">
                <div v-if="operateLogs && operateLogs.length > 0">
                  <div v-for="(log, index) in operateLogs" :key="index" class="log-item">
                    <span class="time">{{ parseTime(log.createTime) }}</span>
                    <span class="user">{{ log.createByName || log.operator || '系统' }}</span>
                    <span class="action">{{ log.actionType == 1 ? '新增' : (log.actionType == 2 ? '修改' : '操作') }}了 拜访：</span>
                    <span class="target">{{ log.targetObject || '资料' }}</span>
                    <div class="details" v-if="log.actionDetails" style="font-size: 12px; color: #999; margin-top: 5px;">{{ log.actionDetails }}</div>
                  </div>
                </div>
                <div v-else class="empty-text">暂无操作日志</div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="管理信息" name="manage">
              <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">{{ detailData.createByName || detailData.createUserName || detailData.nickName || detailData.callPeopleName || 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">{{ detailData.updateByName || detailData.updateUserName || detailData.followPeopleName || detailData.updateBy || '--' }}</span>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-drawer>

    <!-- 新增跟进记录对话框 -->
    <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.staffName}${item.staffCode ? ' (' + item.staffCode + ')' : ''}`" :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.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </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>
  </div>
</template>

<script setup name="VisitRoutine">
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { listRoutine, getRoutine, delRoutine, addRoutine, updateRoutine } from "@/api/visit/routine";
import { listPlan } from "@/api/visit/plan";
import { addRecord, listRecord } from "@/api/visit/record";
import { listOperateLog } from "@/api/visit/operateLog";
import { getDicts } from "@/api/system/dict/data";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listUser } from "@/api/system/user";
import { listCommonDict } from "@/api/customer/customerDict";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { useUserStore } from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const planOptions = ref([]);
const customerOptions = ref([]);
const userOptions = ref([]);
const visitTypeOptions = ref([]);
const importanceOptions = ref([]);
const importantLevelOptions = ref([]);
const scheduleStatusOptions = ref([]);
const relevanceOptions = ref([]);
const staffOptions = ref([]);

const queryRef = ref(null);
const routineRef = ref(null);

const loading = ref(false);
const dataList = ref([]);
const total = ref(0);
const recordList = ref([]);
const recordLoading = ref(false);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  callPeopleName: undefined,
  callDate: undefined,
  scheduleStatus: undefined
});

const open = ref(false);
const title = ref("");
const form = ref({});
const rules = reactive({
  customerNo: [{ required: true, message: "客户不能为空", trigger: "change" }],
  callDate: [{ required: true, message: "拜访日期不能为空", trigger: "change" }],
  importantLevel: [{ required: true, message: "重要级别不能为空", trigger: "change" }],
  purposeVisit: [{ required: true, message: "拜访目的不能为空", trigger: "blur" }]
});

const detailOpen = ref(false);
const detailData = ref({});
const leftTab = ref('baseInfo');
const rightTab = ref('record');
const operateLogs = 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" }]
});

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

const submitRecord = () => {
  if (!recordFormRef.value) return;
  recordFormRef.value.validate(valid => {
    if (valid) {
      const data = {
        objectNo: detailData.value.id,
        customerName: detailData.value.customerName,
        customerNo: detailData.value.customerNo,
        department: detailData.value.department || '', // 从日程同步部门
        profession: 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);
      });
    }
  });
};

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

const getList = () => {
  loading.value = true;
  listRoutine(queryParams).then(response => {
    dataList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const handleCustomerChange = (val) => {
  const customer = customerOptions.value.find(item => item.customerNo === val);
  if (customer) {
    form.value.customerName = customer.customerName;
    // 如果关联类型是客户(0)，同步设置关联对象
    if (form.value.relevanceType === '0') {
      form.value.objectNo = customer.customerNo;
      form.value.objectName = customer.customerName;
    }
  } else {
    form.value.customerName = undefined;
    if (form.value.relevanceType === '0') {
      form.value.objectNo = undefined;
      form.value.objectName = undefined;
    }
  }
};

const handleStaffChange = (val) => {
  const staff = staffOptions.value.find(item => item.staffId === val);
  if (staff) {
    form.value.callPeopleName = staff.staffName;
  } else {
    form.value.callPeopleName = undefined;
  }
};

const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery();
};

const reset = () => {
  const currentUserName = userStore.nickname || userStore.name;
  const defaultStaff = staffOptions.value.find(item => item.staffName === currentUserName);
  
  form.value = {
    id: undefined,
    planNo: undefined,
    scheduleNo: undefined,
    relevanceType: '0',
    customerNo: undefined,
    customerName: undefined,
    objectNo: undefined,
    objectName: undefined,
    callPeopleNo: defaultStaff ? defaultStaff.staffId : undefined,
    callPeopleName: defaultStaff ? defaultStaff.staffName : currentUserName,
    callDate: undefined,
    importantLevel: undefined,
    followPeopleName: undefined,
    purposeVisit: undefined
  };
  if (routineRef.value) {
    routineRef.value.resetFields();
  }
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "新增拜访日程";
};

const cancel = () => {
  open.value = false;
  reset();
};

const handleUpdate = (row) => {
  reset();
  const id = row.id;
  getRoutine(id).then(response => {
    const data = response.data || {};
    form.value = {
      ...form.value,
      id: data.id || row.id,
      planNo: data.planNo ?? undefined,
      scheduleNo: data.scheduleNo ?? undefined,
      relevanceType: String(data.relevanceType ?? '0'),
      customerNo: data.customerNo ?? undefined,
      customerName: data.customerName ?? undefined,
      objectNo: data.objectNo ?? undefined,
      objectName: data.objectName ?? undefined,
      callPeopleNo: data.callPeopleNo !== undefined && data.callPeopleNo !== null ? data.callPeopleNo : undefined,
      callPeopleName: data.callPeopleName ?? undefined,
      callDate: data.callDate ?? undefined,
      importantLevel: String(data.importantLevel ?? ''),
      followPeopleName: data.followPeopleName ?? undefined,
      purposeVisit: data.purposeVisit ?? undefined
    };
    title.value = "编辑拜访日程";
    nextTick(() => {
      open.value = true;
    });
  });
};

const submitForm = () => {
  if (!routineRef.value) return;
  routineRef.value.validate(valid => {
    if (valid) {
      // 提交前确保冗余字段有值
      if (!form.value.callPeopleName) {
        form.value.callPeopleName = userStore.nickname || userStore.name;
      }
      if (form.value.relevanceType === '0' && !form.value.objectName) {
        form.value.objectName = form.value.customerName;
        form.value.objectNo = form.value.customerNo;
      }

      if (form.value.id != null) {
        updateRoutine(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRoutine(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const ids = row.id;
  const scheduleNo = row.scheduleNo || ids;
  proxy.$modal.confirm(`确认删除日程编号为"${scheduleNo}"的数据项吗？`).then(() => {
    return delRoutine(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const handleDetail = (row) => {
  const id = row.id;
  getRoutine(id).then(response => {
    detailData.value = { ...row, ...(response.data || {}) };
    getRecordList(id);
    listOperateLog({ objectNo: String(id) }).then(res => {
      operateLogs.value = res.data || res.rows || [];
    });
    detailOpen.value = true;
  }).catch(() => {
    detailData.value = row;
    detailOpen.value = true;
  });
};

const getOptions = () => {
  listPlan({ pageSize: 1000 }).then(res => { planOptions.value = res.rows || []; });
  listCustomerInfo({ pageSize: 1000 }).then(res => { customerOptions.value = res.rows || []; });
  listUser({ pageSize: 1000 }).then(res => { userOptions.value = res.rows || []; });
  listCommonDict("visit_type").then(res => { visitTypeOptions.value = res.data || []; });
  listCommonDict("importance_level").then(res => { importanceOptions.value = res.data || []; });
  listCommonDict("schedule_status").then(res => { scheduleStatusOptions.value = res.data || []; });
  listCommonDict("relevance_type").then(res => { relevanceOptions.value = res.data || []; });
  selectStaffOptionList().then(res => { staffOptions.value = res.data || []; });
};

onMounted(() => { 
  getList(); 
  getOptions();
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-card {
  border: none;
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

:deep(.el-form--inline) {
  display: flex;
  align-items: center;
}

.custom-form-item {
  margin-bottom: 0 !important;
  margin-right: 0px;
  :deep(.el-form-item__label) {
    padding-right: 12px;
    color: #606266;
    font-weight: 400;
  }
  :deep(.el-input), :deep(.el-select), :deep(.el-date-editor) {
    width: 220px;
  }
}

.search-btns-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-container {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  border-radius: 4px 4px 0 0;
  .list-title { font-size: 15px; font-weight: 600; color: #333;}
}

.table-card {
  border: none;
  border-radius: 0 0 4px 4px;
  :deep(.el-card__body) { padding: 10px 20px 20px; }
}

.link-text { color: #409eff; cursor: pointer; }

/* 详情抽屉样式 */
:deep(.custom-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    color: #333;
  }
  .drawer-title {
    font-size: 18px;
    font-weight: 600;
  }
  .el-drawer__body {
    padding: 0;
    background-color: #f5f7fa;
  }
}

.detail-wrap {
  display: flex;
  height: 100%;
  
  .left-panel {
    flex: 1;
    background: #fff;
    padding: 20px;
    margin-right: 15px;
    border-right: 1px solid #ebeef5;
    
    :deep(.el-tabs__item) {
      font-size: 15px;
      font-weight: 600;
      &.is-active {
        color: #f56c6c;
      }
    }
    :deep(.el-tabs__active-bar) {
      background-color: #f56c6c;
    }

    .info-section {
      padding-top: 10px;
      
      .info-title {
        font-size: 14px;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
      }
      
      .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 {
            color: #333;
            font-size: 13px;
          }
        }
      }
    }
  }

  .right-panel {
    flex: 1;
    background: #fff;
    padding: 20px;

    :deep(.el-tabs__item) {
      font-size: 15px;
    }
    :deep(.el-tabs__item.is-active) {
      color: #f56c6c;
    }
    :deep(.el-tabs__active-bar) {
      background-color: #f56c6c;
    }

    .record-actions {
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-bottom: 20px;
      .visit-type-wrap {
        display: flex;
        align-items: center;
        margin-left: 20px;
        .visit-type-label {
          margin-right: 10px;
          font-size: 14px;
          color: #606266;
        }
      }
    }

    .log-list {
      margin-top: 20px;
      .log-item {
        margin-bottom: 20px;
        font-size: 14px;
        .time { color: #909399; margin-right: 10px; }
        .user { color: #409eff; cursor: pointer; margin-right: 5px; }
        .action { color: #909399; margin-right: 5px; }
        .target { color: #409eff; cursor: pointer; }
      }
    }

    .manage-info {
      margin-top: 20px;
      .manage-row {
        margin-bottom: 25px;
        .manage-col {
          display: flex;
          align-items: center;
          .label {
            width: 100px;
            color: #909399;
            font-size: 14px;
            flex-shrink: 0;
          }
          .value {
            color: #333;
            font-size: 14px;
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.record-list {
  padding: 10px 0;
  .record-item {
    background: #f8fafc;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid #edf2f7;
    
    .record-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      .visit-person { font-weight: bold; color: #333; margin-right: 12px; }
      .visit-time { color: #909399; font-size: 13px; flex: 1; }
    }
    
    .record-content {
      font-size: 13px;
      line-height: 1.6;
      .aim-title, .progress-title { color: #64748b; font-weight: 500; margin-top: 8px; }
      .aim-text, .progress-text { color: #334155; margin-bottom: 5px; background: #fff; padding: 8px 12px; border-radius: 4px; border: 1px solid #e2e8f0;}
    }
  }
}

.empty-text {
  text-align: center;
  color: #909399;
  font-size: 13px;
  padding: 40px 0;
}
</style>
