<template>
  <div class="business-activity-container">
    <el-tabs v-model="activeTab" class="custom-tabs" tab-position="top">
      <!-- 团队成员 -->
      <el-tab-pane label="团队成员" name="team">
        <div class="pane-content-custom">
          <div class="team-header">
            <span class="team-title">团队成员 ({{ teamList.length }})</span>
            <el-button link icon="Plus" class="add-btn" @click="handleAddMember" />
          </div>
          <el-input
            v-model="memberSearch"
            placeholder="请输入成员"
            prefix-icon="Search"
            class="member-search"
            clearable
          />
          <div v-if="filteredTeam.length" class="team-list">
            <div v-for="(item, index) in filteredTeam" :key="item.id" class="team-item">
              <el-avatar :size="36" :src="item.avatar" class="user-avatar">
                <img v-if="item.avatar" :src="item.avatar" />
                <el-icon v-else><User /></el-icon>
              </el-avatar>
              <div class="user-info">
                <div class="user-main">
                  <span class="user-name">{{ item.realName || item.userName || '成员' }}</span>
                  <div class="user-tags">
                    <span v-if="item.izManager === 1 || index === 0" class="leader-tag-simple">负责人</span>
                    <span class="user-role-text">{{ item.roleName }}</span>
                    <span class="permission-text-simple">{{ item.updateAccredit === 1 ? '修改权限' : '仅查看' }}</span>
                  </div>
                </div>
              </div>
              <div class="user-ops">
                <el-button 
                  v-if="!( (computedDataType === 12 && (item.roleCode === '1' || item.roleCode === 'B0001' || item.roleCode === '3')) || ((computedDataType === 1 || computedDataType === 2) && (item.roleCode === '1' || item.roleCode === '3')) )" 
                  link 
                  class="btn-edit" 
                  @click="handleEditMember(item)"
                >编辑</el-button>
                <el-button 
                  v-if="!( (computedDataType === 12 && (item.roleCode === '1' || item.roleCode === 'B0001' || item.roleCode === '3')) || ((computedDataType === 1 || computedDataType === 2) && (item.roleCode === '1' || item.roleCode === '3')) )" 
                  link 
                  class="btn-delete" 
                  @click="handleDeleteMember(item)"
                >删除</el-button>
              </div>
            </div>
          </div>
          <div v-else class="empty-status">暂无团队成员</div>
        </div>
      </el-tab-pane>

      <!-- 跟进记录 -->
      <el-tab-pane label="跟进记录" name="record">
        <div class="pane-content-custom">
          <div class="record-toolbar">
            <el-button v-if="!isReadOnly" link type="primary" icon="Plus" class="new-record-btn" @click="handleNewRecord">
              新建跟进记录
            </el-button>
            <div class="filter-item">
              <span class="filter-label">拜访方式</span>
              <el-select v-model="visitType" placeholder="请选择" size="small" style="width: 120px" @change="loadRecords" clearable>
                <el-option label="全部" value="" />
                <el-option v-for="dict in visitTypeDict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </div>
          </div>
          
          <div v-if="filteredRecords.length" class="record-list">
            <div v-for="(record, index) in filteredRecords" :key="index" class="record-item">
                 <div class="record-card">
                   <div class="record-header">
                     <span class="record-user">{{ getRecordUser(record) }}</span>
                     <span class="record-time">{{ (record.callDate || record.time || '').split(' ')[0] }}</span>
                   </div>
                   <div class="record-detail-info">
                     <div class="info-row"><span class="label">拜访方式：</span><span class="value"><dict-tag :options="visitTypeDict" :value="record.callTypeCode" /></span></div>
                     <div v-if="record.followPeopleName" class="info-row"><span class="label">随访人：</span><span class="value">{{ record.followPeopleName }}</span></div>
                     <div v-if="record.nextCallDate" class="info-row"><span class="label">下次拜访时间：</span><span class="value">{{ (record.nextCallDate || '').split(' ')[0] }}</span></div>
                     <div class="info-row"><span class="label">拜访目的：</span><span class="value">{{ record.callAim }}</span></div>
                   </div>
                   <div class="record-body">
                     <span class="label">跟进情况：</span>
                     <div class="value">{{ record.followUpCondition || record.content }}</div>
                   </div>
                   <div v-if="record.recordPicture" class="record-images">
                     <el-image 
                       :src="record.recordPicture" 
                       :preview-src-list="[record.recordPicture]"
                       fit="cover"
                       class="record-img"
                       preview-teleported
                     />
                   </div>
                 </div>
            </div>
          </div>
          <div v-else class="empty-status">暂无跟进记录</div>
        </div>
      </el-tab-pane>

      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="log">
        <div class="pane-content-custom">
          <div v-if="logList.length" class="log-list-new">
            <div v-for="log in logList" :key="log.id" class="log-row">
              <span class="log-time">{{ log.operTime || log.time }}</span>
              <span class="log-user">{{ log.operName || log.userName }}</span>
              <span class="log-content">
                {{ formatLogContent(log) }}{{ (log.subContent || log.operAction) ? ':' : '' }}
              </span>
              <span v-if="log.subContent" class="log-sub-content blue-style">{{ log.subContent }}</span>
            </div>
          </div>
          <div v-else class="empty-status">暂无操作日志</div>
        </div>
      </el-tab-pane>

      <!-- 管理信息 -->
      <el-tab-pane v-if="showManage" label="管理信息" name="manage">
        <div class="pane-content-custom">
          <slot name="management">
            <div class="manage-info-list">
              <el-row :gutter="40">
                <el-col :span="12">
                  <div class="m-item">
                    <span class="m-label">创建人</span>
                    <span class="m-value link-style">{{ (infoData.createByName && infoData.createByName !== 'admin') ? infoData.createByName : (infoData.createByStaffName || getStaffName(infoData.createBy || infoData.createByName)) }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-item">
                    <span class="m-label">创建日期</span>
                    <span class="m-value">{{ parseTime(infoData.createTime || infoData.createDate, '{y}-{m}-{d}') || '' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-item">
                    <span class="m-label">修改日期</span>
                    <span class="m-value">{{ parseTime(infoData.updateTime || infoData.updateDate, '{y}-{m}-{d}') || '' }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="m-item">
                    <span class="m-label">最后修改人</span>
                    <span class="m-value">{{ (infoData.updateByName && infoData.updateByName !== 'admin') ? infoData.updateByName : (infoData.updateByStaffName || getStaffName(infoData.updateBy || infoData.updateByName)) }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </slot>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新建跟进记录弹窗 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="跟进记录"
      width="680px"
      class="custom-dialog"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="recordFormRef"
        :model="recordForm"
        :rules="recordRules"
        label-width="100px"
        class="custom-form"
      >
        <div class="readonly-customer">
          <span class="label">客户：</span>
          <span class="value">{{ infoData.customerName || '' }}</span>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访人" prop="visitor">
              <el-select v-model="recordForm.visitor" placeholder="请选择" class="w100" filterable>
                <el-option v-for="item in teamList" :key="item.userNo" :label="item.realName" :value="item.userNo" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访人" prop="followPeople">
              <el-select v-model="recordForm.followPeople" placeholder="请选择" class="w100" filterable multiple collapse-tags>
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访方式" prop="callTypeCode">
              <el-select v-model="recordForm.callTypeCode" placeholder="请选择" class="w100">
                <el-option v-for="dict in visitTypeDict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拜访时间" prop="callDate">
              <el-date-picker
                v-model="recordForm.callDate"
                type="date"
                placeholder="请选择"
                class="w100"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

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

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

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

        <el-form-item label="记录图片" prop="recordPicture">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <img v-if="recordForm.recordPicture" :src="recordForm.recordPicture" class="uploaded-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" class="btn-confirm" :loading="submitLoading" @click="submitRecord">确认</el-button>
          <el-button class="btn-cancel" @click="recordDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑团队成员弹窗 -->
    <el-dialog
      v-model="memberDialogVisible"
      :title="isEditMember ? '编辑团队成员' : '添加团队成员'"
      width="500px"
      class="custom-dialog"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberRules"
        label-width="100px"
        class="custom-form member-form"
      >
        <el-form-item v-if="isEditMember" label="人员姓名：">
          <span class="readonly-text">{{ memberForm.realName }}</span>
        </el-form-item>
        <el-form-item v-else label="添加人员：" prop="userNo">
          <el-select v-model="memberForm.userNo" placeholder="请选择" class="w100" filterable @change="handleUserChange">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>

        <el-form-item label="团队角色：" prop="roleCode">
          <el-select v-model="memberForm.roleCode" placeholder="请选择" class="w100">
            <el-option v-for="dict in filteredTeamRoleDict" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="权限：">
          <div class="member-form">
            <el-radio-group v-model="memberForm.updateAccredit">
              <el-radio :label="0">仅查看</el-radio>
              <el-radio :label="1">修改权限</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" class="btn-confirm" :loading="submitLoading" @click="submitMember">确认</el-button>
          <el-button class="btn-cancel" @click="memberDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, reactive, getCurrentInstance, toRefs, nextTick } from 'vue';
import { User, Search, Plus } from '@element-plus/icons-vue';
import { listTeamMember, delTeamMember, addTeamMember, updateTeamMember } from "@/api/customer/teamMember";
import { listRecord, addRecord } from "@/api/visit/record";
import { listOperateLog } from "@/api/visit/operateLog";
import { listUser } from "@/api/system/user/index";
import { listComStaff } from "@/api/system/comStaff/index";
import { globalHeaders } from "@/utils/request";
import { useUserStore } from "@/store/modules/user";

const proxy = getCurrentInstance().proxy;
const { visit_type: visitTypeDict, T0001: teamRoleDict } = toRefs(reactive(proxy.useDict("visit_type", "T0001")));

const props = defineProps({
  businessId: [String, Number],
  businessType: {
    type: String,
    default: 'record'
  },
  dataType: [String, Number], // 显式传递的数据类型，优先级最高
  infoData: {
    type: Object,
    default: () => ({})
  },
  showManage: {
    type: Boolean,
    default: true
  }
});

const activeTab = ref('team');
const memberSearch = ref('');
const visitType = ref('');
const submitLoading = ref(false);
const userStore = useUserStore();

const emit = defineEmits(['update-readonly']);

// 状态
const userOptions = ref([]);
const staffOptions = ref([]);
const teamList = ref([]);
const recordList = ref([]);
const logList = ref([]);

// 弹窗相关 - 跟进记录
const recordDialogVisible = ref(false);
const recordFormRef = ref(null);
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const headers = ref(globalHeaders());

const recordForm = reactive({
  visitor: '',
  followPeople: [],
  callTypeCode: '',
  callDate: '',
  nextCallDate: '',
  callAim: '',
  followUpCondition: '',
  recordPicture: '',
  customerNo: ''
});

const recordRules = {
  visitor: [{ required: true, message: '请选择拜访人', trigger: 'change' }],
  callTypeCode: [{ required: true, message: '请选择拜访方式', trigger: 'change' }],
  callDate: [{ required: true, message: '请选择拜访时间', trigger: 'change' }],
  callAim: [{ required: true, message: '请输入拜访目的', trigger: 'blur' }],
  followUpCondition: [{ required: true, message: '请输入跟进情况', trigger: 'blur' }]
};

// 弹窗相关 - 团队成员
const memberDialogVisible = ref(false);
const isEditMember = ref(false);
const memberFormRef = ref(null);
const memberForm = reactive({
  id: '',
  userNo: '',
  realName: '',
  roleCode: '',
  updateAccredit: 0,
  izManager: 0,
  objectNo: ''
});

const memberRules = {
  userNo: [{ required: true, message: '请选择添加人员', trigger: 'change' }]
};

const filteredTeam = computed(() => {
  if (!memberSearch.value) return teamList.value;
  return teamList.value.filter(m => (m.realName || '').includes(memberSearch.value));
});

const isReadOnly = computed(() => {
  // 只有系统超级管理员（userId=1）才免除只读限制
  // 租户管理员（roleKey=admin）仍需遵守团队成员权限
  if (String(userStore.userId) === '1') {
    return false;
  }
  const member = teamList.value.find(m => String(m.userId) === String(userStore.userId));
  if (member) {
    return member.updateAccredit !== 1;
  }
  return true;
});

// 当 isReadOnly 变化时，通知父组件；用 nextTick 避免在 Vue patch 循环中同步触发更新
watch(isReadOnly, (val) => {
  nextTick(() => {
    emit('update-readonly', val);
  });
});

const filteredTeamRoleDict = computed(() => {
  if (!teamRoleDict.value) return [];
  // 获取已被其他团队成员占用的角色编码
  const existingRoleCodes = teamList.value
    .filter(m => {
      if (isEditMember.value) {
        // 编辑团队成员时，排除当前正在编辑的成员自身占用的角色
        return String(m.id) !== String(memberForm.id);
      }
      return true;
    })
    .map(m => {
      const code = String(m.roleCode);
      // 兼容可能存在的旧数据 B0001（对应字典值 1）
      if (code === 'B0001') return '1';
      return code;
    });
  
  return teamRoleDict.value.filter(dict => !existingRoleCodes.includes(String(dict.value)));
});

const filteredRecords = computed(() => {
  return recordList.value.filter(record => {
    const no = String(record.recordsNo || record.scheduleNo || '');
    // 如果没有编号，默认显示（可能是脏数据），如果有编号，则要求是纯数字
    return !no || /^\d+$/.test(no);
  });
});

// 统一计算当前业务的数据类型
const computedDataType = computed(() => {
  if (props.dataType !== undefined && props.dataType !== null) {
    return Number(props.dataType);
  }
  const typeMap = {
    'leads': 1,
    'opportunity': 2,
    'projectSelection': 3,
    'platformSelection': 3,
    'plan': 4,
    'care': 10,
    'contact': 11,
    'customer': 12,
    'record': 1
  };
  return typeMap[props.businessType] || 0;
});

// 统一计算当前业务的对象编号
const computedObjectNo = computed(() => {
  // 对于销售线索、商机、年度入围等核心模块，后端同步团队成员时统一使用的是数据库主键 ID
  // 因此这里需要优先返回 businessId (即实体 ID)
  if (['leads', 'opportunity', 'projectSelection', 'platformSelection'].includes(props.businessType)) {
    return String(props.businessId || '');
  }

  // 其他模块维持原有的优先业务编号逻辑
  const no = props.infoData?.planNo || 
             props.infoData?.receiptId || 
             props.infoData?.contactNo || 
             props.infoData?.objectNo || 
             props.infoData?.customerNo ||
             props.infoData?.projectNo;
  
  if (no) return String(no);
  
  return String(props.businessId || '');
});



// 数据加载
const loadTeam = async () => {
  const objectNo = computedObjectNo.value;
  if (objectNo && objectNo !== 'undefined') {
    listTeamMember(objectNo).then(res => {
      teamList.value = res.data || [];
    });
  }
};

const loadRecords = async () => {
  const objectNo = computedObjectNo.value;
  if (!objectNo || objectNo === 'undefined') return;
  
  const query = {
    objectNo: objectNo,
    customerNo: objectNo, // 兼容老接口
    callTypeCode: visitType.value,
    dataType: computedDataType.value
  };

  listRecord(query).then(res => {
    recordList.value = res.rows || res.data || [];
  });
};

const loadLogs = async () => {
  const objectNo = computedObjectNo.value;
  if (!objectNo || objectNo === 'undefined') return;
  const query = { 
    objectNo: objectNo, // 修正参数名为 objectNo
    dataType: computedDataType.value // 使用统一的 dataType
  };
  listOperateLog(query).then(res => {
    logList.value = res.rows || res.data || [];
  });
};

// 监听 ID 变化，自动加载数据
watch(() => computedObjectNo.value, (newVal) => {
  if (newVal && newVal !== 'undefined' && newVal !== 'null') {
    loadTeam();
    loadRecords();
    loadLogs();
  }
}, { immediate: true });

const loadUsers = async () => {
  listUser({ pageSize: 1000 }).then(res => {
    userOptions.value = res.rows || res.data || [];
  });
};

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

const loadDicts = async () => {
};

const fetchDynamicData = () => {
  loadTeam();
  loadRecords();
  loadLogs();
};

watch(() => props.businessId, (val) => { if (val) fetchDynamicData(); }, { immediate: true });
watch(() => props.infoData, (val) => { if (val) fetchDynamicData(); }, { deep: true });

// 团队成员操作
const handleAddMember = () => {
  isEditMember.value = false;
  Object.assign(memberForm, {
    id: '',
    userNo: '',
    realName: '',
    roleCode: '',
    updateAccredit: 0,
    izManager: 0,
    objectNo: computedObjectNo.value,
    dataType: computedDataType.value
  });
  memberDialogVisible.value = true;
};

const handleEditMember = (item) => {
  isEditMember.value = true;
  Object.assign(memberForm, {
    id: item.id,
    userNo: item.userNo,
    realName: item.realName,
    roleCode: item.roleCode,
    updateAccredit: item.updateAccredit || 0,
    izManager: item.izManager || 0,
    objectNo: computedObjectNo.value,
    dataType: computedDataType.value
  });
  memberDialogVisible.value = true;
};

const handleDeleteMember = (item) => {
  proxy.$modal.confirm('确认删除该成员吗？').then(() => {
    delTeamMember(item.id).then(() => {
      proxy.$modal.msgSuccess("删除成功");
      loadTeam();
    });
  });
};

const handleUserChange = (val) => {
  const staff = staffOptions.value.find(s => s.staffId === val);
  if (staff) {
    memberForm.realName = staff.staffName;
  }
};

const submitMember = async () => {
  if (!memberFormRef.value) return;
  
  // 确保 objectNo 存在
  if (!memberForm.objectNo) {
    memberForm.objectNo = computedObjectNo.value;
  }
  
  if (!memberForm.objectNo || memberForm.objectNo === 'undefined') {
    proxy.$modal.msgError("关联对象编号缺失，无法保存");
    return;
  }

  // 补全数据类型
  memberForm.dataType = computedDataType.value;

  // 重复性检查 (针对新增场景)
  if (!isEditMember.value) {
    const isExist = teamList.value.some(m => String(m.userNo) === String(memberForm.userNo));
    if (isExist) {
      proxy.$modal.msgError("该人员已在团队成员中，请勿重复添加");
      return;
    }
  }

  await memberFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      const data = { ...memberForm };
      const action = isEditMember.value ? updateTeamMember : addTeamMember;
      action(data).then(() => {
        proxy.$modal.msgSuccess("操作成功");
        memberDialogVisible.value = false;
        loadTeam();
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
};

// 跟进记录操作
const handleNewRecord = () => {
  Object.assign(recordForm, {
    visitor: '',
    followPeople: [],
    callTypeCode: '',
    callDate: new Date().toISOString().split('T')[0],
    nextCallDate: '',
    callAim: '',
    followUpCondition: '',
    recordPicture: '',
    customerNo: computedObjectNo.value
  });
  recordDialogVisible.value = true;
};

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    recordForm.recordPicture = res.data.url;
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg || "上传失败");
  }
};

const submitRecord = async () => {
  if (!recordFormRef.value) return;
  await recordFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      const objectNo = computedObjectNo.value;
      // 获取拜访人姓名
      const visitorItem = teamList.value.find(m => String(m.userNo) === String(recordForm.visitor));
      // 获取随访人姓名列表
      const followNames = (recordForm.followPeople || []).map(id => {
        const staff = staffOptions.value.find(s => s.staffId === id);
        return staff ? staff.staffName : '';
      }).filter(n => n).join(',');

      // 辅助函数：如果值是纯数字（ID），则视为无效，返回空字符串
      const safeText = (val) => (val && !isNaN(Number(val)) ? '' : (val || ''));

      const data = { 
        ...recordForm,
        objectNo: objectNo,
        customerNo: objectNo,
        visitorName: visitorItem ? visitorItem.realName : '',
        followPeopleName: followNames,
        // 自动补全列表所需字段（过滤掉可能是数字 ID 的情况）
        customerName: props.infoData?.customerName || props.infoData?.customName || props.infoData?.companyName || '',
        goalObject: props.infoData?.projectName || props.infoData?.customerName || props.infoData?.customName || '',
        salesman: props.infoData?.leaderName || props.infoData?.salesPersonName || props.infoData?.salesPerson || props.infoData?.staffName || props.infoData?.managerName || props.infoData?.salesman || '',
        department: safeText(props.infoData?.deptName) || safeText(props.infoData?.department) || '',
        deptName: safeText(props.infoData?.deptName) || safeText(props.infoData?.department) || '',
        profession: safeText(props.infoData?.profession) || safeText(props.infoData?.industry) || '',
        industryName: safeText(props.infoData?.industryName) || safeText(props.infoData?.industry) || '',
        dataType: computedDataType.value
      };
      if (Array.isArray(data.followPeople)) {
        data.followPeople = data.followPeople.join(',');
      }
      addRecord(data).then(() => {
        proxy.$modal.msgSuccess("保存成功");
        recordDialogVisible.value = false;
        loadRecords();
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
};

const getStaffName = (id) => {
  if (!id) return '';
  const strId = String(id).trim();
  if (strId.toLowerCase() === 'admin' || strId === '1') return '超级管理员';
  // 避免将非 ID 字符串（已是姓名）再次查找
  if (id && isNaN(Number(id)) && strId.length > 4) return id; 

  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) : id;
};

// 获取记录显示的用户名
const getRecordUser = (record) => {
  if (record.visitorName) return record.visitorName;
  if (record.userName) return record.userName;
  // 如果字段缺失，尝试从团队成员列表中匹配
  const member = teamList.value.find(m => String(m.userNo) === String(record.visitor));
  return member ? (member.realName || member.userName) : '未知用户';
};


// 格式化日志内容，移除“了”字并避免重复
const formatLogContent = (log) => {
  const actionMap = {
    1: '添加',
    2: '编辑',
    3: '删除'
  };
  
  const prefix = actionMap[log.operAction];
  let content = (log.operContent || log.content || '执行操作').trim();
  
  // 移除开头可能存在的冒号
  content = content.replace(/^[:：\s]+/, '');

  if (prefix) {
    // 定义常见同义词（包含带“了”和不带“了”的情况）
    const synonyms = {
      '添加': ['创建了', '创建', '新增了', '新增', '添加了', '添加', '录入了', '录入'],
      '编辑': ['编辑了', '编辑', '修改了', '修改', '更新了', '更新', '完善了', '完善'],
      '删除': ['删除了', '删除', '移除了', '移除']
    };
    
    const currentSynonyms = synonyms[prefix] || [prefix];
    // 优先匹配长度较长的词（如“修改了”优先于“修改”）
    currentSynonyms.sort((a, b) => b.length - a.length);
    
    for (const syn of currentSynonyms) {
      if (content.startsWith(syn)) {
        const rest = content.substring(syn.length).trim().replace(/^[:：\s]+/, '');
        return rest ? `${prefix} ${rest}` : prefix;
      }
    }
    
    return `${prefix} ${content}`;
  }

  // 对于其他没有 action 映射的内容，也尝试移除“了”
  return content.replace('了', '');
};


onMounted(() => {
  loadUsers();
  loadStaffs();
  loadDicts();
  fetchDynamicData();
  nextTick(() => {
    emit('update-readonly', isReadOnly.value);
  });
});
</script>


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

/* 自定义 Tab 样式 (对齐图 1 极简风格) */
.custom-tabs {
  flex: 1; display: flex; flex-direction: column; overflow: hidden;
  :deep(.el-tabs__header) { 
    margin: 0; 
    padding: 0 16px; 
    background: #fff; 
    border-bottom: 1px solid #f0f2f5; 
    order: 1; 
    height: 48px; 
    box-sizing: border-box;
  }
  :deep(.el-tabs__nav-wrap::after) { height: 0; } 
  :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;
    }
    z-index: 1;
  }
  :deep(.el-tabs__item) { 
    font-size: 14px; 
    color: #333; 
    height: 48px; 
    line-height: 48px; 
    padding: 0 15px !important;
    &.is-active { color: #409eff; font-weight: 500 !important; }
    &:hover { color: #409eff; } 
  }
  :deep(.el-tabs__content) { 
    flex: 1; 
    padding: 0; 
    overflow-y: auto;
    order: 2; 
  }
}

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

/* 团队成员列表样式 (原型图极简风格) */
.team-header {
  display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;
  .team-title { font-size: 14px; color: #333; }
  .add-btn { font-size: 18px; color: #999; }
}
.member-search { margin-bottom: 20px; :deep(.el-input__wrapper) { box-shadow: 0 0 0 1px #e4e7ed inset; border-radius: 2px; height: 32px; } }
.team-list {
  .team-item {
    display: flex; align-items: center; padding: 15px 0; border-bottom: 1px solid #f8f9fb;
    &:last-child { border-bottom: none; }
    .user-avatar { margin-right: 12px; background-color: #f1f5f9; color: #94a3b8; flex-shrink: 0; }
    .user-info { 
      flex: 1; min-width: 0;
      .user-main { 
        display: flex; align-items: center; 
        .user-name { font-size: 14px; color: #333; margin-right: 15px; flex-shrink: 0; } 
        .user-tags {
          display: flex; align-items: center; gap: 12px;
          .leader-tag-simple { font-size: 13px; color: #52c41a; border: 1px solid #52c41a; padding: 1px 6px; border-radius: 2px; line-height: 1.2; }
          .user-role-text, .permission-text-simple { font-size: 13px; color: #999; }
        }
      } 
    }
    .user-ops { 
      display: flex; gap: 12px; margin-left: 12px;
      .btn-edit { color: #faad14; font-size: 14px; } 
      .btn-delete { color: #999; font-size: 14px; } 
    }
  }
}

/* 弹窗通用样式 */
.custom-dialog {
  :deep(.el-dialog__header) { border-bottom: 1px solid #f0f0f0; margin-right: 0; padding: 15px 20px; .el-dialog__title { font-size: 16px; font-weight: normal; } }
  :deep(.el-dialog__body) { padding: 20px 30px; }
  :deep(.el-dialog__footer) { border-top: 1px solid #f0f0f0; padding: 15px 20px; }
  .dialog-footer { display: flex; justify-content: flex-end; gap: 12px; .btn-confirm { background-color: #409eff; border-color: #409eff; padding: 8px 25px; } .btn-cancel { border-color: #dcdfe6; color: #606266; padding: 8px 25px; } }
}

.custom-form {
  :deep(.el-form-item__label) { color: #666; font-weight: normal; }
  :deep(.el-form-item) { margin-bottom: 22px; }
  .readonly-customer { margin-bottom: 25px; font-size: 14px; .label { color: #666; } .value { color: #333; } }
  .w100 { width: 100%; }
  .readonly-text { font-size: 14px; color: #333; }
}

/* 团队成员表单特定样式 */
.member-form {
  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
  }
  :deep(.el-radio-group) {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  :deep(.el-radio) {
    margin-right: 0;
    font-weight: normal;
    &.is-checked .el-radio__label {
      color: #409eff;
    }
  }
}

/* 弹窗关闭按钮颜色优化 (匹配图片) */
:deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #ff6a00;
}
:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #ff6a00;
  font-size: 20px;
}

/* 其他样式保持不变 */
.record-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; .new-record-btn { color: #409eff; font-size: 14px; } .filter-item { display: flex; align-items: center; gap: 10px; .filter-label { font-size: 13px; color: #666; } } }
.record-card { 
  padding: 15px; background: #f8fafc; border-radius: 4px; margin-bottom: 15px; 
  .record-header { 
    display: flex; justify-content: space-between; margin-bottom: 12px; 
    .record-user { font-size: 14px; font-weight: 500; color: #333; } 
    .record-time { font-size: 12px; color: #999; } 
  } 
  .record-detail-info {
    margin-bottom: 10px;
    .info-row {
      font-size: 13px; line-height: 1.8; color: #666;
      display: flex;
      .label { color: #999; width: 100px; flex-shrink: 0; }
      .value { color: #333; flex: 1; }
    }
  }
  .record-body { 
    font-size: 13px; color: #666; line-height: 1.5; margin-bottom: 10px;
    display: flex;
    .label { color: #999; width: 100px; flex-shrink: 0; }
    .value { color: #333; flex: 1; }
  } 
  .record-images {
    display: flex; flex-wrap: wrap; gap: 8px;
    .record-img {
      width: 80px; height: 80px; border-radius: 4px; border: 1px solid #eee;
    }
  }
}
.log-list-new { .log-row { font-size: 13px; line-height: 2.2; color: #666; display: flex; flex-wrap: wrap; align-items: center; .log-time { color: #999; margin-right: 15px; width: 140px; } .log-user { color: #409eff; margin-right: 12px; cursor: pointer; } .log-content { color: #666; margin-right: 4px; } .blue-style { color: #409eff; cursor: pointer; } .link-style { color: #409eff; cursor: pointer; &:hover { text-decoration: underline; } } } }
.manage-info-list {
  padding-top: 10px;
  .m-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 13px;
    .m-label { color: #999; width: 80px; flex-shrink: 0; }
    .m-value { color: #333; word-break: break-all; line-height: 1.4; }
  }
}
.image-uploader { .uploader-icon { font-size: 28px; color: #8c939d; width: 80px; height: 80px; text-align: center; line-height: 80px; border: 1px dashed #d9d9d9; border-radius: 4px; } .uploaded-image { width: 80px; height: 80px; display: block; border-radius: 4px; object-fit: cover; } }
.link-style, .blue-style { color: #409eff; cursor: pointer; }
.empty-status { text-align: center; color: #999; font-size: 13px; padding: 60px 0; }

/* 隐藏组件内部滑动条 */
:deep(.el-tabs__content), .team-list, .record-list, .log-list-new {
  &::-webkit-scrollbar { width: 0 !important; height: 0 !important; display: none !important; }
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}
</style>
