<template>
	<view class="assemble">
		<fui-segmented-control :values="values" type="text" activeColor="#29d3b4" color="#fff"
			@click="segmented"></fui-segmented-control>

		<!--我的客户-->
		<scroll-view v-if="segmented_type == 1" scroll-y="true" :lower-threshold="lowerThreshold"
			@scrolltolower="loadMoreData_1" style="height: 100vh;">

			<!-- 搜索按钮区域 -->
			<view class="search_section">
				<view class="item">
					<view class="input_box" @click="openSearchPopup">
						<view class="input_box_text">校区/用户名/手机号/时间范围</view>
					</view>
					<view class="button" @click="openSearchPopup">搜索</view>
				</view>
			</view>
			<view class="card" v-for="(v,k) in tableList_1" :key="k">
				<!-- 状态水印 -->
				<view class="status-watermark" v-if="v.customerResource && !v.customerResource.communication_time">
					新资源
				</view>
				<view class="card-content" v-if="v.customerResource">
					<view class="card-main" @click="clue_info(v)">
						<!-- 顶部信息行：头像、姓名、电话、状态标签 -->
						<view class="card-header">
							<view class="user-info-section">
								<view class="user-avatar">
									<image :src="$util.img('/uniapp_src/static/images/index/myk.png')" class="card-image">
									</image>
								</view>
								<view class="user-details">
									<view class="card-text">{{ v.customerResource.name }}</view>
									<view class="card-con-span">{{ v.customerResource.phone_number }}</view>
								</view>
							</view>
							<view class="status-section">
								<!-- 开单状态标签 -->
								<view :class="['status-tag',getOrderStatusClass(v.customerResource.order_status)]">
									{{ v.customerResource.order_status || '未报名' }}
								</view>
								<!-- 到访状态标签 - 只有未报名时才显示到访状态 -->
								<view class="visit-status" v-if="(v.customerResource.order_status || '未报名') !== '已报名'">
									<view :class="['visit-tag',getVisitStatusClass(v.customerResource.first_visit_status)]">
										一访{{ v.customerResource.first_visit_status || '未到' }}
									</view>
									<view
		                :class="['visit-tag',getVisitStatusClass(v.customerResource.second_visit_status)]"
		                v-if="v.customerResource.first_visit_status !== '未到'">
										二访{{ v.customerResource.second_visit_status || '未到' }}
									</view>
								</view>
							</view>
						</view>

						<!-- 孩子姓名单独一行 -->
						<view class="card-single-row">
							<view class="card-con">
								<text class="info-label">孩子姓名：</text>
								<text class="info-value">{{ v.customerResource.child_name || v.customerResource.name || '-' }}</text>
							</view>
						</view>

						<!-- 详细信息区域：两列布局 -->
						<view class="card-info-grid">
							<view class="info-column">
								<view class="card-con">
									<text class="info-label">孩子年龄：</text>
									<text class="info-value">{{ v.customerResource.age || '-' }}岁</text>
								</view>
								<view class="card-con">
									<text class="info-label">所属校区：</text>
									<text class="info-value">{{ v.customerResource.campus_name || '-' }}</text>
								</view>
								<view class="card-con">
									<text class="info-label">渠道来源：</text>
									<text class="info-value">{{ v.customerResource.source || '-' }}</text>
								</view>
								<view class="card-con" v-if="v.customerResource.source_channel">
									<text class="info-label">线上渠道：</text>
									<text class="info-value">{{ v.customerResource.source_channel }}</text>
								</view>
							</view>
							<view class="info-column">
								<view class="card-con">
									<text class="info-label">市场老师：</text>
									<text class="info-value">{{ v.customerResource.market_teacher || '-' }}</text>
								</view>
                <view class="card-con">
                  <text class="info-label">销售老师：</text>
                  <text class="info-value">{{ v.customerResource.sales_teacher || '-' }}</text>
                </view>
								<view class="card-con">
									<text class="info-label">是否有效：</text>
									<text class="info-value" :class="v.sixSpeed && v.sixSpeed.efficacious === 1 ? 'status-valid' : 'status-invalid'">
										{{ v.sixSpeed && v.sixSpeed.efficacious === 1 ? '有效' : '无效' }}
									</text>
								</view>
								<view class="card-con" v-if="v.sixSpeed && v.sixSpeed.consultation_remark">
									<text class="info-label">到访备注：</text>
									<text class="info-value">{{ v.sixSpeed.consultation_remark }}</text>
								</view>
							</view>
						</view>
            <view class="info-column">
              <view class="card-con">
                <text class="info-label">录入时间：</text>
                <text class="info-value">{{ v.customerResource.created_at ? $util.formatToDateTime(v.customerResource.created_at, 'Y-m-d H:i') : '-' }}</text>
              </view>
            </view>
            <view class="info-column" v-if="v.assigned_at">
              <view class="card-con">
                <text class="info-label">分配时间：</text>
                <text class="info-value">{{ v.assigned_at ? $util.formatToDateTime(v.assigned_at, 'Y-m-d H:i') : '-' }}</text>
              </view>
            </view>
					</view>
				</view>
        <!-- 底部操作按钮 -->
        <view class="card-actions">
          <view class="card-con">
            <text class="info-label">联系状态：</text>
            <text class="info-value">{{ v.customerResource.communication_time ? $util.formatToDateTime(v.customerResource.communication_time, 'm-d H:i') + ' 已联系' : '暂未联系' }}</text>
          </view>
          <!--只有注册了member表的账号才可操作IM对话-->
          <view class="btn-item">
            <image :src="$util.img('/uniapp_src/static/images/index/message.png')" class="image"
                   @click.stop="openViewMyMessage(v)"></image>
            <image :src="$util.img('/uniapp_src/static/images/index/phone.png')" class="image" style="margin-left: 30rpx"
                   @click.stop="dialTel(v)" v-if="v.customerResource.phone_number">
            </image>
          </view>
        </view>
			</view>
		</scroll-view>

		<!--资源分配-->
		<scroll-view v-if="segmented_type == 2" scroll-y="true" :lower-threshold="lowerThreshold"
			@scrolltolower="loadMoreData_2" style="height: 100vh;">
			<view class="search_section">
				<view class="item">
					<view class="input_box" @click="openSearchPopup()">
						<view class="input_box_text">校区/用户名/手机号/时间范围</view>
					</view>
					<view class="button" @click="openSearchPopup()">搜索</view>
				</view>
				<!-- 批量操作控制栏 -->
				<view class="batch_control_bar">
					<view class="batch_actions_left">
						<view v-if="!batchMode" class="batch_toggle_btn" @click="enterBatchMode()">批量操作</view>
						<view v-if="batchMode" class="batch_toggle_btn cancel" @click="exitBatchMode()">取消</view>
						<view v-if="batchMode" class="batch_select_all" @click="toggleSelectAll()">
							<text class="checkbox" :class="{ checked: isAllSelected }">✓</text>
							<text class="select_all_text">全选</text>
						</view>
					</view>
					<view v-if="batchMode && selectedItems.length > 0" class="batch_actions_right">
						<view class="batch_assign_btn" @click="batchAssign()">
							批量分配 ({{ selectedItems.length }})
						</view>
					</view>
				</view>
			</view>
			<view class="card" v-for="(v,k) in tableList_2" :key="k" @click="batchMode ? toggleItemSelection(v) : null">
				<!-- 状态水印 -->
				<view class="status-watermark" v-if="v.customerResource && !v.customerResource.communication_time">
					新资源
				</view>
				<view class="card-content">
					<view class="card-main">
						<!-- 顶部信息行：批量选择、头像、姓名、电话、状态标签 -->
						<view class="card-header">
							<view class="user-info-section">
								<!-- 批量选择复选框 -->
								<view v-if="batchMode" class="batch_checkbox" @click.stop="toggleItemSelection(v)">
									<text class="checkbox" :class="{ checked: isItemSelected(v) }">✓</text>
								</view>
								<view class="user-avatar">
									<image :src="$util.img('/uniapp_src/static/images/index/myk.png')" class="card-image">
									</image>
								</view>
								<view class="user-details">
									<view class="card-text">{{v.customerResource.name}}</view>
									<view class="card-con-span">{{v.customerResource.phone_number}}</view>
								</view>
							</view>
							<view class="status-section">
								<view class="assign-status">
									<span class="assigned-to" :class="v.shared_by_name === '未分配' ? 'unassigned' : 'assigned'">
										{{v.shared_by_name === '未分配' ? '未分配' : '已分配'}}
									</span>
								</view>
							</view>
						</view>

						<!-- 孩子姓名单独一行 -->
						<view class="card-single-row">
							<view class="card-con">
								<text class="info-label">孩子姓名：</text>
								<text class="info-value">{{ v.customerResource.child_name || v.customerResource.name || '-' }}</text>
							</view>
						</view>

						<!-- 详细信息区域：两列布局 -->
						<view class="card-info-grid">
							<view class="info-column">
								<view class="card-con">
									<text class="info-label">孩子年龄：</text>
									<text class="info-value">{{ v.customerResource.age || '-' }}岁</text>
								</view>
								<view class="card-con">
									<text class="info-label">所属校区：</text>
									<text class="info-value">{{ v.customerResource.campus_name || '-' }}</text>
								</view>
								<view class="card-con">
									<text class="info-label">决策人：</text>
									<text class="info-value">{{ v.customerResource.decision_maker || '-' }}</text>
								</view>
							</view>
							<view class="info-column">
								<view class="card-con">
									<text class="info-label">市场老师：</text>
									<text class="info-value">{{ v.customerResource.market_teacher || '-' }}</text>
								</view>
								<view class="card-con">
									<text class="info-label">分配状态：</text>
									<text class="info-value assigned-to" :class="v.shared_by_name === '未分配' ? 'unassigned' : 'assigned'">
										{{v.shared_by_name === '未分配' ? '未分配' : v.shared_by_name + '分配了资源'}}
									</text>
								</view>
							</view>

						</view>
            <view class="info-column">
              <view class="card-con">
                <text class="info-label">录入时间：</text>
                <text class="info-value">{{ v.customerResource.created_at ? $util.formatToDateTime(v.customerResource.created_at, 'Y-m-d H:i') : '-' }}</text>
              </view>
            </view>
					</view>
				</view>

				<!-- 底部操作按钮 -->
				<view class="card-actions">
					<view class="btn-item assign-btn" @click.stop="openAssign(v)">
						<view class="ling">分配</view>
					</view>
					<view class="btn-item contact-btn" @click.stop="openContact(v)">
						<view class="ling">联系</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 顶部弹出搜索组件 -->
		<view v-if="showSearchPopup" class="search_popup_mask" @tap="showSearchPopup=false">
			<view class="search_popup_content" @tap.stop>
				<view class="popup_search_content">
					<view class="popup_header">
						<view class="popup_title">筛选</view>
						<view class="popup_close" @tap="showSearchPopup=false">
							<text class="close_text">✕</text>
						</view>
					</view>

					<scroll-view :scroll-y="true" class="popup_scroll_view">
						<!-- 第一筛选区域 -->
						<view class="popup_filter_section">
							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">校区筛选</text>
									<input class="popup_filter_input" placeholder="校区筛选" v-model="searchForm.campus_name" />
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">姓名</text>
									<input class="popup_filter_input" placeholder="姓名" v-model="searchForm.name" />
								</view>
							</view>

							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">电话</text>
									<input class="popup_filter_input" placeholder="电话" v-model="searchForm.phone_number" />
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">来源</text>
									<picker :value="sourceIndex" :range="sourceOptions" @change="onSourceChange">
										<view class="popup_filter_picker">{{ sourceOptions[sourceIndex] }}</view>
									</picker>
								</view>
							</view>

							<view class="popup_filter_row" v-if="sourceIndex === 1">
								<view class="popup_filter_item full_width">
									<text class="popup_filter_label">来源渠道</text>
									<picker :value="sourceChannelIndex" :range="sourceChannelOptions" @change="onSourceChannelChange">
										<view class="popup_filter_picker">{{ sourceChannelOptions[sourceChannelIndex] }}</view>
									</picker>
								</view>
							</view>
						</view>

						<!-- 第二筛选区域 -->
						<view class="popup_filter_section">
							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">课程检索</text>
									<input class="popup_filter_input" placeholder="课程检索" v-model="searchForm.course_search" />
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">到课类型</text>
									<picker :value="attendanceIndex" :range="attendanceOptions" @change="onAttendanceChange">
										<view class="popup_filter_picker">{{ attendanceOptions[attendanceIndex] }}</view>
									</picker>
								</view>
							</view>

							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">成交类型</text>
									<picker :value="dealIndex" :range="dealOptions" @change="onDealChange">
										<view class="popup_filter_picker">{{ dealOptions[dealIndex] }}</view>
									</picker>
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">资源有效类型</text>
									<picker :value="validIndex" :range="validOptions" @change="onValidChange">
										<view class="popup_filter_picker">{{ validOptions[validIndex] }}</view>
									</picker>
								</view>
							</view>

							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">沟通情况</text>
									<picker :value="communicationIndex" :range="communicationOptions" @change="onCommunicationChange">
										<view class="popup_filter_picker">{{ communicationOptions[communicationIndex] }}</view>
									</picker>
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">时间</text>
									<view class="popup_filter_input" @click="openDatePicker">
										{{ searchForm.time_range || '开始时间-结束时间' }}
									</view>
								</view>
							</view>

							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">年龄</text>
									<input class="popup_filter_input" placeholder="请输入年龄" v-model="searchForm.age" type="digit" />
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">客户判断</text>
									<picker :value="blacklistIndex" :range="blacklistOptions" @change="onBlacklistChange">
										<view class="popup_filter_picker">{{ blacklistOptions[blacklistIndex] }}</view>
									</picker>
								</view>
							</view>
						</view>
					</scroll-view>

					<view class="popup_filter_buttons">
						<view class="popup_filter_btn reset_btn" @click="resetSearchOnly">重置</view>
						<view class="popup_filter_btn search_btn" @click="searchDataAndClose">搜索</view>
						<view class="popup_filter_btn close_btn" @click="closeSearchPopup">关闭</view>
					</view>
				</view>
			</view>
		</view>

		<!--下拉选择器-->
		<fui-select :show="select_show" :options="select_options" title="请选择员工" @confirm="getSales"
			@close="closeAssign"></fui-select>

		<!--    时间范围选择器-->
		<fui-date-picker range :show="date_picker_show" type="3" @change="changeDatePicker" :value="selectedDate"
			@cancel="cancelDatePicker" :z-index="1500"></fui-date-picker>

		<!--    我的客户搜索条件栏目-->
		<fui-drawer :show="showDrawer" direction="left" :maskClosable="true">
			<view class="fui-scroll__view">
				<view class="fui-title">筛选</view>
				<scroll-view scroll-y style="height: 720rpx;">
					<view class="drawer_box">

						<fui-list-cell>
							<view class="item">
								<view class="title">校区筛选</view>
								<view class="input_box">
									<fui-input :clearable="true" borderTop placeholder="校区筛选"
										v-model="showDrawerForm.campus_name"></fui-input>
								</view>
							</view>
						</fui-list-cell>


						<fui-list-cell>
							<view class="item">
								<view class="title">时间筛选</view>
								<view class="input_box">
									<fui-input :clearable="true" borderTop placeholder="开始时间-结束时间"
										@click="openDatePicker" v-model="showDrawerForm.shared_at_str"></fui-input>
								</view>
							</view>
						</fui-list-cell>

						<fui-list-cell>
							<view class="item">
								<view class="title">姓名筛选</view>
								<view class="input_box">
									<fui-input :clearable="true" borderTop placeholder="姓名筛选"
										v-model="showDrawerForm.name"></fui-input>
								</view>
							</view>
						</fui-list-cell>

						<fui-list-cell>
							<view class="item">
								<view class="title">电话筛选</view>
								<view class="input_box">
									<fui-input :clearable="true" borderTop placeholder="电话筛选"
										v-model="showDrawerForm.phone_number"></fui-input>
								</view>
							</view>
						</fui-list-cell>
					</view>
				</scroll-view>
				<view class="fui-btn__box">
					<view class="button clientbtn" @click="searchData()">搜索</view>
					<view class="button clientbtn" @click="closeShowDrawer()">关闭</view>
				</view>
			</view>
		</fui-drawer>

		<view style="height: 170rpx;"></view>
	</view>
</template>

<script>
	import apiRoute from '@/api/apiRoute.js';
	export default {
		data() {
			return {
				loading: false, //加载状态
				lowerThreshold: 100, //距离底部多远触发
				isReachedBottom: false, //防止重复加载|true=不可加载|false=可加载
				selectedDate: this.getCurrentDate(), // 初始化当前日期

				// 新增筛选相关数据
				showSearchPopup: false, // 搜索弹窗是否显示
				tempHideSearchPopup: false, // 临时隐藏搜索弹窗的状态
				searchForm: {
					campus_name: '',
					name: '',
					phone_number: '',
					source: '',
					source_channel: '',
					course_search: '',
					attendance_type: '',
					deal_type: '',
					valid_type: '',
					communication_status: '',
					time_range: '',
					age: '', // 年龄字段，只能输入数字或小数
					blacklist: '' // 客户判断字段：1可追单，2黑名单
				},

				// 选择器相关
				sourceIndex: 0,
				sourceOptions: ['全部', '线上', '线下'], // 默认值，会被动态替换
				sourceDict: {}, // 来源名称到ID的映射
				sourceChannelIndex: 0,
				sourceChannelOptions: ['全部'], // 渠道选项，会被动态替换
				sourceChannelDict: {}, // 渠道名称到ID的映射
				attendanceIndex: 0,
				attendanceOptions: ['全部', '一访未到', '一访已到', '二访未到', '二访已到', '未到访'],
				dealIndex: 0,
				dealOptions: ['全部', '已成交','定金', '未成交'],
				validIndex: 0,
				validOptions: ['全部', '有效', '无效'],
				communicationIndex: 0,
				communicationOptions: ['全部', '已沟通', '未沟通'],
				blacklistIndex: 0,
				blacklistOptions: ['全部', '可追单', '黑名单'],
				//筛选条件
				filteredData: {
					page: 1, //当前页码
					limit: 10, //每页返回数据条数
					total: 10, //数据总条数
					type: '0', //0=全部,1=待跟进,2=7天,3=30天
					is_gh: '2', //1=资源分配,2=我的客户
				},

				//顶部Tab栏
				values: [{
						id: 1,
						name: '我的客户'
					},
					// {
					//   id: 2,
					//   name: '资源分配'
					// }
				],
				segmented_type: 1, //当前选中的Tab栏目|1=我的客户,2=资源分配

				userInfo: {}, //用户信息
				//我的客户列表相关
				//筛选条件
				filteredData_1: {
					page: 1, //当前页码
					limit: 10, //每页返回数据条数
					total: 10, //数据总条数
					shared_by: '', //共享人ID|0=未分配
					shared_at_str: '', //共享时间|开始时间(Y-m-d)-结束时间(Y-m-d)
					shared_at_arr: [], //时间范围数组格式
					phone_number: '', //客户资源表-手机号
					name: '', //客户资源表-用户姓名
					campus_name: '', //校区名称
					source: '', //来源
					source_channel: '', //来源渠道
					attendance_type: '', //到课类型
					deal_type: '', //成交类型
					valid_type: '', //资源有效类型
					age: '', //年龄
					blacklist: '', //客户判断：1可追单，2黑名单
				},
				//数据列表
				tableList_1: [], //表格数据

				//资源分配列表相关
				//筛选条件
				filteredData_2: {
					page: 1, //当前页码
					limit: 10, //每页返回数据条数
					total: 10, //数据总条数
					shared_scope: 'all', //查询范围：all=全部资源
					shared_at_str: '', //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					phone_number: '', //客户资源表-手机号
					name: '', //客户资源表-用户姓名
					campus_name: '',
					age: '', //年龄
					blacklist: '', //客户判断：1可追单，2黑名单
				},
				//数据列表
				tableList_2: [], //表格数据

				// 批量操作相关
				batchMode: false, // 是否进入批量操作模式
				selectedItems: [], // 已选择的资源ID列表
				isAllSelected: false, // 是否全选

				//员工select选择器
				select_show: false, //是否展示选择器
				select_item: {}, //当前选中的选项
				select_options: [
					// {
					//   text: '张三',
					//   value: '1',
					// }
				], //选择器可选项

				//时间选择器相关
				date_picker_show: false, //是否展示时间选择器

				//抽屉搜索条件展示窗相关
				showDrawer: false, //是否展示|false=否
				showDrawerForm: {
					campus_name: '',
					shared_at_str: '', //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					phone_number: '', //客户资源表-手机号
					name: '', //客户资源表-用户姓名
				},


			}
		},
		onLoad(options) {},
		onShow() {
			this.init() //初始化
		},
		//下拉刷新
		async onPullDownRefresh() {
			//重置为第一页
			if (this.segmented_type == 1) {
				//我的客户
				await this.resetFilteredData_1()
				await this.getList_1()
			} else {
				//资源分配
				await this.resetFilteredData_2()
				await this.getList_2()
			}


		},
		methods: {
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`; // 示例：2024-04-15
			},
			//初始化
			async init() {
				// 确保选择器数据已初始化
				this.initSelectorsData();
				await this.getUserInfo();
				await this.initDictData(); // 初始化字典数据
				if (this.segmented_type == 1) {
					await this.getList_1();
				} else {
					await this.getList_2();
				}
			},

			// 初始化选择器数据
			initSelectorsData() {
				// 确保blacklistIndex有效
				if (this.blacklistIndex < 0 || this.blacklistIndex >= this.blacklistOptions.length) {
					this.blacklistIndex = 0;
				}
				console.log('初始化选择器数据:', {
					blacklistOptions: this.blacklistOptions,
					blacklistIndex: this.blacklistIndex
				});
			},

			// 初始化字典数据
			async initDictData() {
				try {
					// 获取来源字典
					const sourceRes = await apiRoute.common_Dictionary({key: 'source'})
					if (sourceRes.code === 1 && sourceRes.data) {
						// 直接使用返回的数据数组
						const sourceData = sourceRes.data
						this.sourceOptions = ['全部', ...sourceData.map(item => item.name)]
						this.sourceDict = sourceData.reduce((acc, item) => {
							acc[item.name] = item.value
							return acc
						}, {})
						console.log('来源字典加载成功:', this.sourceOptions)
					}

					// 获取渠道字典
					const channelRes = await apiRoute.common_Dictionary({key: 'SourceChannel'})
					if (channelRes.code === 1 && channelRes.data) {
						// 直接使用返回的数据数组
						const channelData = channelRes.data
						this.sourceChannelOptions = ['全部', ...channelData.map(item => item.name)]
						this.sourceChannelDict = channelData.reduce((acc, item) => {
							acc[item.name] = item.value
							return acc
						}, {})
						console.log('渠道字典加载成功:', this.sourceChannelOptions, this.sourceChannelDict)
					}
				} catch (error) {
					console.error('字典数据加载失败:', error)
				}
			},

			//获取用户信息
			async getUserInfo() {
				let res = await apiRoute.getPersonnelInfo({})
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				this.userInfo = res.data

				this.filteredData_1.shared_by = this.userInfo.id //共享人ID始终是当前登录的员工

				//判断用户是不是销售经理,是就展示"资源分配"
				if (this.userInfo.role_key_arr.includes('market_manager')) {
					this.values = [{
							id: 1,
							name: '我的客户'
						},
						{
							id: 2,
							name: '资源分配'
						}
					]
					//是经理的情况下,获取这个校区的全部用户(身份是销售的)
					// await this.getPersonnelAll();
				} else {
					this.values = [{
						id: 1,
						name: '我的客户'
					}, ]
				}
			},


			//获取销售部门员工（根据校区筛选）
			async getPersonnelAll(campus = '') {
				let res = await apiRoute.getSalesPersonnelByCampus({
					campus: campus // 传入校区参数
				})
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				let arr = []
				res.data.forEach((v, k) => {
					// 拼接姓名和电话显示
					let displayText = `${v.name} ${v.phone}`
					arr.push({
						text: displayText,
						value: v.id,
					})
				})
				this.select_options = arr
				console.log('销售部门员工', this.select_options)
			},

			//获取列表-我的客户相关
			//加载更多(下一页)
			loadMoreData_1() {
				//判断是否加载
				if (!this.isReachedBottom) {
					this.isReachedBottom = true; //设置为不可请求状态
					this.getList_1();
				}
			},
			//重置为第一页
			async resetFilteredData_1() {
				this.isReachedBottom = false; // 重置状态，以便下次触发加载更多

				this.filteredData_1.page = 1 //当前页码
				this.filteredData_1.limit = 10 //每页返回数据条数
				this.filteredData_1.total = 10 //数据总条数
			},
			//获取列表-我的客户
			async getList_1() {
				this.loading = true

				let data = {
					...this.filteredData_1
				}

				//判断是否还有数据
				if (this.filteredData_1.page * this.filteredData_1.limit > this.filteredData_1.total) {
					this.loading = false
					return
				}

				this.filteredData_1.shared_by = this.userInfo.id //共享人ID始终是当前登录的员工

				if (data.page == 1) {
					this.tableList_1 = []
				}

				let res = await apiRoute.xs_resourceSharingIndex(data)
				this.loading = false
				this.isReachedBottom = false;
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				console.log('getList_1 API响应:', res)
				console.log('getList_1 第一条数据的customerResource:', res.data.data[0]?.customerResource)
				console.log('getList_1 consultant字段:', res.data.data[0]?.customerResource?.consultant)
				console.log('getList_1 consultant_name字段:', res.data.data[0]?.customerResource?.consultant_name)

				const normalizedData = this.normalizeResourceList(res.data.data)
				this.tableList_1 = this.tableList_1.concat(normalizedData); // 使用 concat 方法 将新数据追加到数组中

				console.log('列表1', this.tableList_1)
				this.filteredData_1.total = res.data.total
				this.filteredData_1.page++

			},

			//获取列表-资源分配相关
			//加载更多(下一页)
			loadMoreData_2() {
				//判断是否加载
				if (!this.isReachedBottom) {
					this.isReachedBottom = true; //设置为不可请求状态
					this.getList_2();
				}
			},
			//重置为第一页
			async resetFilteredData_2() {
				this.isReachedBottom = false; // 重置状态，以便下次触发加载更多
				this.filteredData_2.page = 1 //当前页码
				this.filteredData_2.limit = 10 //每页返回数据条数
				this.filteredData_2.total = 10 //数据总条数
				this.filteredData_2.shared_scope = 'all' //重置查询范围
			},
			//获取列表-资源分配
			async getList_2() {
				this.loading = true

				let data = {
					...this.filteredData_2
				}

				//判断是否还有数据
				if (this.filteredData_2.page * this.filteredData_2.limit > this.filteredData_2.total) {
					this.loading = false
					return
				}

				if (data.page == 1) {
					this.tableList_2 = []
				}

				let res = await apiRoute.xs_resourceSharingIndex(data)
				this.loading = false
				this.isReachedBottom = false;
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				console.log('API响应数据:', res)
				console.log('第一条数据的customerResource:', res.data.data[0]?.customerResource)

				const normalizedData = this.normalizeResourceList(res.data.data)
				this.tableList_2 = this.tableList_2.concat(normalizedData); // 使用 concat 方法 将新数据追加到数组中

				console.log('列表2', this.tableList_2)
				this.filteredData_2.total = res.data.total
				this.filteredData_2.page++
			},


			//切换tag列表
			async segmented(param) {
				this.segmented_type = param.id //1=我的客户,2=资源分配

				//重置筛选抽屉中的表单数据
				this.showDrawerForm.shared_at_str = '' //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
				this.showDrawerForm.phone_number = '' //客户资源表-手机号
				this.showDrawerForm.name = '' //客户资源表-用户姓名
				this.campus_name = ''
				if (this.segmented_type == 1) {
					this.filteredData_1.shared_at_str = '' //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					this.filteredData_1.phone_number = '' //客户资源表-手机号
					this.filteredData_1.name = '' //客户资源表-用户姓名
					this.filteredData_1.campus_name = ''
					this.filteredData_1.age = '' //年龄
					this.filteredData_1.blacklist = '' //客户判断

					//我的客户
					//重置为第一页
					await this.resetFilteredData_1()
					await this.getList_1()
				} else {
					this.filteredData_2.shared_at_str = '' //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					this.filteredData_2.phone_number = '' //客户资源表-手机号
					this.filteredData_2.name = '' //客户资源表-用户姓名
					this.filteredData_2.campus_name = ''
					this.filteredData_2.age = '' //年龄
					this.filteredData_2.blacklist = '' //客户判断
					//资源分配
					//重置为第一页
					await this.resetFilteredData_2()
					await this.getList_2()
				}

			},

			//跳转页面-我的消息
			openViewMyMessage(item) {
				let from_id = this.userInfo.id //发送者的id
				let to_id = item.customerResource.id //接收者ID
				uni.navigateTo({
					url: `/pages-common/im_chat_info?from_id=${from_id}&to_id=${to_id}`
				})
			},

			//拨打电话
			async dialTel(item) {

				let tel = item.customerResource.phone_number

				if (!tel) {
					uni.showToast({
						title: '电话号码为空',
						icon: 'none'
					});
					return;
				}

				uni.makePhoneCall({
					phoneNumber: tel,
					success: () => {
						let param = {
							staff_id: this.userInfo.id, //员工id
							resource_id: item.customerResource.id, //资源ID
							resource_type: '', //资源类型（如设备、文件、系统等）
							communication_type: 'phone', //沟通类型: phone-电话, email-邮件, meeting-会议, other-其他
							communication_result: 'success', //沟通结果: success-成功, failure-失败, pending-待定
							remarks: null, //备注
							tag: null, //标签
						}
						apiRoute.xs_communicationRecordsAdd(param).then(ressuccess=>{
							if(ressuccess.code != 1){
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						})
					}
				})
			},

			//客户详情
			clue_info(item) {
				const resource_sharing_id = this.ensureResourceSharingId(item, '未找到对应的资源记录')
				if (!resource_sharing_id) return
				console.log('跳转到客户详情页面:', resource_sharing_id);
				uni.navigateTo({
					url: `/pages-market/clue/clue_info?resource_sharing_id=${resource_sharing_id}`,
					complete: function(res) {
						console.log('客户详情页面跳转结果:', res)
					},
					fail: (err) => {
						console.error('跳转到客户详情页面失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				})
			},

			//公海-分配客户给员工相关
			//打开分配列表
			openAssign(item) {
				const shareId = this.ensureResourceSharingId(item, '未找到资源ID，无法分配')
				if (!shareId) return
				this.getPersonnelAll(item.customerResource.campus)
				this.select_item = {
					...item,
					_resourceSharingId: shareId
				}
				this.select_show = true
			},
			//联系客户
			openContact(item) {
				// 这里可以添加联系功能，比如拨打电话或发送消息
				const phoneNumber = item.customerResource.phone_number
				if (phoneNumber) {
					uni.makePhoneCall({
						phoneNumber: phoneNumber,
						success: () => {
							console.log('拨打电话成功')
						},
						fail: () => {
							uni.showToast({
								title: '拨打电话失败',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '联系方式不存在',
						icon: 'none'
					})
				}
			},
			//关闭分配列表
			closeAssign(item) {
				this.select_item = {}
				this.select_show = false
				this.select_options = this.select_options.map(v => ({
					...v,
					checked: false
				}));
			},
			//公海-分配客户给员工（支持单个和批量）
			async getSales(e) {
				let select_item = {
					...this.select_item
				}
				console.log('选中', e, select_item)
				this.closeAssign() //关闭选择窗

				// 检查是否为批量操作
				if (select_item.isBatch && select_item.selectedIds) {
					// 批量分配
					await this.batchAssignResources(select_item.selectedIds, e.options.value)
				} else {
				// 单个分配
				const resourceSharingId = select_item._resourceSharingId || this.extractResourceSharingId(select_item)
				if (!resourceSharingId) {
					uni.showToast({
						title: '资源标识缺失，无法分配',
						icon: 'none'
					})
					return
				}
				let param = {
					resource_sharing_id: resourceSharingId, //共享资源表id
					shared_by: e.options.value, //分给员工的id
				}
					let res = await apiRoute.xs_resourceSharingAssign(param)
					if (res.code != 1) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						return
					}
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
					//延迟1s执行
					setTimeout(() => {
						let param = {
							id: 2,
							index: 1,
							name: "资源分配",
						}
						this.segmented(param)
					}, 1000)
				}
			},

			// 批量分配资源
			async batchAssignResources(selectedIds, assigneeId) {
				let successCount = 0
				let failCount = 0

				for (let resourceId of selectedIds) {
					if (!resourceId) {
						failCount++
						continue
					}
					try {
						let param = {
							resource_sharing_id: resourceId,
							shared_by: assigneeId
						}
						let res = await apiRoute.xs_resourceSharingAssign(param)
						if (res.code == 1) {
							successCount++
						} else {
							failCount++
						}
					} catch (error) {
						failCount++
					}
				}

				// 显示批量操作结果
				if (failCount === 0) {
					uni.showToast({
						title: `成功分配 ${successCount} 个资源`,
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: `成功分配 ${successCount} 个，失败 ${failCount} 个`,
						icon: 'none'
					})
				}

				// 退出批量模式并刷新列表
				this.exitBatchMode()
				setTimeout(() => {
					let param = {
						id: 2,
						index: 1,
						name: "资源分配",
					}
					this.segmented(param)
				}, 1000)
			},

			//时间选择器相关
			//监听-时间选择器结果
			changeDatePicker(e) {
				console.log('时间', e)
				let time_range = `${e.startDate.result} ~ ${e.endDate.result}`
				this.searchForm.time_range = time_range
				this.showDrawerForm.shared_at_str = time_range
				this.cancelDatePicker()
			},
			//打开时间选择器
			openDatePicker() {
				console.log('打开时间选择器')
				this.date_picker_show = true
				// 临时隐藏搜索弹窗，避免层级冲突
				this.tempHideSearchPopup = this.showSearchPopup
				this.showSearchPopup = false
			},
			//关闭时间选择
			cancelDatePicker() {
				this.date_picker_show = false
				// 恢复搜索弹窗显示状态
				if (this.tempHideSearchPopup) {
					this.showSearchPopup = true
					this.tempHideSearchPopup = false
				}
			},

			//检索数据
			async searchData() {
				if (this.segmented_type == 1) {
					this.filteredData_1.shared_at_str = this.showDrawerForm.shared_at_str //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					this.filteredData_1.phone_number = this.showDrawerForm.phone_number //客户资源表-手机号
					this.filteredData_1.name = this.showDrawerForm.name //客户资源表-用户姓名
					this.filteredData_1.campus_name = this.showDrawerForm.campus_name //客户资源表-用户姓名
					//我的客户
					await this.resetFilteredData_1()
					await this.getList_1()
				} else {
					this.filteredData_2.shared_at_str = this.showDrawerForm.shared_at_str //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					this.filteredData_2.phone_number = this.showDrawerForm.phone_number //客户资源表-手机号
					this.filteredData_2.name = this.showDrawerForm.name //客户资源表-用户姓名
					this.filteredData_2.campus_name = this.showDrawerForm.campus_name //客户资源表-用户姓名
					//资源分配
					await this.resetFilteredData_2()
					await this.getList_2()
				}
				this.closeShowDrawer()
			},

			//打开抽屉筛选弹窗
			openShowDrawer() {
				this.showDrawer = true
			},
			//关闭抽屉筛选弹窗
			closeShowDrawer() {
				this.showDrawer = false
			},

			// 新增筛选方法
			// 打开搜索弹窗
			openSearchPopup() {
				console.log('打开搜索弹窗', this.showSearchPopup)
				this.showSearchPopup = true
				console.log('设置后的状态', this.showSearchPopup)
			},

			// 搜索并关闭弹窗
			searchDataAndClose() {
				console.log('执行搜索，表单数据:', this.searchForm)
				this.searchDataFromPopup()
				this.showSearchPopup = false
			},

			// 从弹窗搜索数据
			async searchDataFromPopup() {
				// 根据当前标签页选择对应的筛选数据对象
				const currentFilterData = this.segmented_type == 1 ? this.filteredData_1 : this.filteredData_2

				// 将弹窗搜索表单数据映射到筛选数据
				currentFilterData.campus_name = this.searchForm.campus_name
				currentFilterData.name = this.searchForm.name
				currentFilterData.phone_number = this.searchForm.phone_number

				// 处理时间范围：转换为后端需要的shared_at_arr格式
				if (this.searchForm.time_range && this.searchForm.time_range.includes(' ~ ')) {
					const timeArray = this.searchForm.time_range.split(' ~ ')
					currentFilterData.shared_at_arr = timeArray
					currentFilterData.shared_at_str = this.searchForm.time_range
				} else {
					currentFilterData.shared_at_arr = []
					currentFilterData.shared_at_str = ''
				}

				// 处理来源字段：将中文名称转换为对应的数字值
				if (this.searchForm.source && this.searchForm.source !== '全部') {
					// 使用字典映射将中文名称转换为数字值
					currentFilterData.source = this.sourceDict[this.searchForm.source] || this.searchForm.source
					console.log('source字段转换:', this.searchForm.source, '->', currentFilterData.source)
				} else {
					currentFilterData.source = ''
				}

				// 处理渠道字段：将中文名称转换为对应的数字值
				if (this.searchForm.source_channel && this.searchForm.source_channel !== '全部') {
					// 使用字典映射将中文名称转换为数字值
					currentFilterData.source_channel = this.sourceChannelDict[this.searchForm.source_channel] || this.searchForm.source_channel
					console.log('source_channel字段转换:', this.searchForm.source_channel, '->', currentFilterData.source_channel)
				} else {
					currentFilterData.source_channel = ''
				}

				// 处理其他搜索条件
				if (this.searchForm.attendance_type && this.searchForm.attendance_type !== '全部') {
					currentFilterData.attendance_type = this.searchForm.attendance_type
				} else {
					currentFilterData.attendance_type = ''
				}

				if (this.searchForm.deal_type && this.searchForm.deal_type !== '全部') {
					currentFilterData.deal_type = this.searchForm.deal_type
				} else {
					currentFilterData.deal_type = ''
				}

				if (this.searchForm.valid_type && this.searchForm.valid_type !== '全部') {
					currentFilterData.valid_type = this.searchForm.valid_type
				} else {
					currentFilterData.valid_type = ''
				}

				if (this.searchForm.communication_status && this.searchForm.communication_status !== '全部') {
					currentFilterData.communication_status = this.searchForm.communication_status
				} else {
					currentFilterData.communication_status = ''
				}

				if (this.searchForm.course_search) {
					currentFilterData.course_search = this.searchForm.course_search
				} else {
					currentFilterData.course_search = ''
				}

				// 处理年龄字段
				if (this.searchForm.age) {
					currentFilterData.age = this.searchForm.age
				} else {
					currentFilterData.age = ''
				}

				// 处理客户判断字段：将中文选择转换为数据库值
				if (this.searchForm.blacklist && this.searchForm.blacklist !== '') {
					currentFilterData.blacklist = this.searchForm.blacklist
					console.log('blacklist字段设置:', this.searchForm.blacklist)
				} else {
					currentFilterData.blacklist = ''
				}

				console.log('映射后的筛选数据:', currentFilterData)

				// 根据当前标签页重置数据并获取列表
				if (this.segmented_type == 1) {
					// 我的客户
					await this.resetFilteredData_1()
					await this.getList_1()
				} else {
					// 资源分配
					await this.resetFilteredData_2()
					await this.getList_2()
				}
			},

			// 重置搜索并关闭弹窗
			resetSearchAndClose() {
				this.resetSearch()
				this.showSearchPopup = false
			},

			// 仅重置搜索（不关闭弹窗）
			resetSearchOnly() {
				this.resetSearch()
			},

			// 关闭搜索弹窗
			closeSearchPopup() {
				this.showSearchPopup = false
			},

			// 来源选择器变化
			onSourceChange(e) {
				this.sourceIndex = e.detail.value
				this.searchForm.source = this.sourceOptions[this.sourceIndex]
				// 如果不是线上，清空来源渠道
				if (this.sourceIndex !== 1) {
					this.searchForm.source_channel = ''
					this.sourceChannelIndex = 0
				}
			},

			// 来源渠道选择器变化
			onSourceChannelChange(e) {
				this.sourceChannelIndex = e.detail.value
				this.searchForm.source_channel = this.sourceChannelOptions[this.sourceChannelIndex]
				console.log('来源渠道选择器变化:', e.detail.value, '选择的内容:', this.searchForm.source_channel)
			},

			// 到课类型选择器变化
			onAttendanceChange(e) {
				this.attendanceIndex = e.detail.value
				this.searchForm.attendance_type = this.attendanceOptions[this.attendanceIndex]
			},

			// 成交类型选择器变化
			onDealChange(e) {
				this.dealIndex = e.detail.value
				this.searchForm.deal_type = this.dealOptions[this.dealIndex]
			},

			// 资源有效类型选择器变化
			onValidChange(e) {
				this.validIndex = e.detail.value
				this.searchForm.valid_type = this.validOptions[this.validIndex]
			},

			// 沟通情况选择器变化
			onCommunicationChange(e) {
				this.communicationIndex = e.detail.value
				this.searchForm.communication_status = this.communicationOptions[this.communicationIndex]
			},

			// 客户判断选择器变化
			onBlacklistChange(e) {
				console.log('客户判断选择器变化:', e.detail.value)
				console.log('当前blacklistOptions:', this.blacklistOptions)
				this.blacklistIndex = e.detail.value
				const selectedOption = this.blacklistOptions[this.blacklistIndex]
				console.log('选中的选项:', selectedOption)
				// 将中文选项转换为对应的数值：可追单->1，黑名单->2，全部->''
				if (selectedOption === '可追单') {
					this.searchForm.blacklist = '1'
				} else if (selectedOption === '黑名单') {
					this.searchForm.blacklist = '2'
				} else {
					this.searchForm.blacklist = ''
				}
				console.log('设置blacklist值为:', this.searchForm.blacklist)
			},

			// 重置搜索
			async resetSearch() {
				this.searchForm = {
					campus_name: '',
					name: '',
					phone_number: '',
					source: '',
					source_channel: '',
					course_search: '',
					attendance_type: '',
					deal_type: '',
					valid_type: '',
					communication_status: '',
					time_range: '',
					age: '', // 重置年龄字段
					blacklist: '' // 重置客户判断字段
				}
				this.sourceIndex = 0
				this.sourceChannelIndex = 0 // 重置来源渠道选择器索引
				this.attendanceIndex = 0
				this.dealIndex = 0
				this.validIndex = 0
				this.communicationIndex = 0
				this.blacklistIndex = 0 // 重置客户判断选择器索引

				// 重置当前标签页的筛选数据
				if (this.segmented_type == 1) {
					// 我的客户
					await this.resetFilteredData_1()
					await this.getList_1()
				} else {
					// 资源分配
					await this.resetFilteredData_2()
					await this.getList_2()
				}
			},

			// 获取开单状态样式类
			getOrderStatusClass(status) {
				return status === '已开单' ? 'status-closed' : 'status-open'
			},

			// 获取到访状态样式类
			getVisitStatusClass(status) {
				return status === '已到' ? 'visit-arrived' : 'visit-not-arrived'
			},

			normalizeResourceList(list) {
				if (!Array.isArray(list)) return []
				return list.map(item => {
					const normalized = { ...item }
					const shareId = this.extractResourceSharingId(normalized)
					normalized._resourceSharingId = shareId
					if (normalized.customerResource && shareId && !normalized.customerResource.resource_sharing_id) {
						normalized.customerResource.resource_sharing_id = shareId
					}
					return normalized
				})
			},

			extractResourceSharingId(item) {
				if (!item || typeof item !== 'object') return ''

				// 添加详细调试日志
				console.log('extractResourceSharingId 调试 - 输入item:', item)
				console.log('extractResourceSharingId 调试 - item.resource_sharing_id:', item.resource_sharing_id)
				console.log('extractResourceSharingId 调试 - item.customerResource:', item.customerResource)
				console.log('extractResourceSharingId 调试 - item.customerResource?.resource_sharing_id:', item.customerResource?.resource_sharing_id)

				const candidates = [
					item._resourceSharingId,
					item.resource_sharing_id,
					item.resourceSharingId,
					item.resourceSharingID,
					item?.customerResource?.resource_sharing_id,
					item?.customerResource?.resourceSharingId,
					item?.customerResource?.resourceSharing?.sharin_id,
					item?.customerResource?.resourceSharing?.id
				]

				console.log('extractResourceSharingId 调试 - candidates:', candidates)

				for (let i = 0; i < candidates.length; i++) {
					const candidate = candidates[i]
					console.log(`extractResourceSharingId 调试 - candidate[${i}]:`, candidate, typeof candidate, candidate !== undefined && candidate !== null && candidate !== '')
					if (candidate !== undefined && candidate !== null && candidate !== '') {
						console.log('extractResourceSharingId 调试 - 找到有效ID:', String(candidate))
						return String(candidate)
					}
				}

				const relationList = item?.customerResource?.resourceSharingHasMany || item?.resourceSharingHasMany
				console.log('extractResourceSharingId 调试 - relationList:', relationList)

				if (Array.isArray(relationList) && relationList.length > 0) {
					const maybeId = relationList[0]?.id ?? relationList[0]?.resource_sharing_id
					console.log('extractResourceSharingId 调试 - relationList中的ID:', maybeId)
					if (maybeId !== undefined && maybeId !== null && maybeId !== '') {
						console.log('extractResourceSharingId 调试 - 从relationList找到ID:', String(maybeId))
						return String(maybeId)
					}
				}

				console.log('extractResourceSharingId 调试 - 未找到任何有效ID，返回空字符串')
				return ''
			},

			ensureResourceSharingId(item, toastMessage = '未找到资源ID') {
				const shareId = this.extractResourceSharingId(item)
				if (!shareId) {
					uni.showToast({
						title: toastMessage,
						icon: 'none'
					})
					return ''
				}
				return shareId
			},

			isItemSelected(item) {
				const shareId = this.extractResourceSharingId(item)
				return shareId ? this.selectedItems.includes(shareId) : false
			},

			// 批量操作相关方法
			// 进入批量操作模式
			enterBatchMode() {
				this.batchMode = true
				this.selectedItems = []
				this.isAllSelected = false
			},

			// 退出批量操作模式
			exitBatchMode() {
				this.batchMode = false
				this.selectedItems = []
				this.isAllSelected = false
			},

			// 切换单个项目的选择状态
			toggleItemSelection(item) {
				const shareId = this.extractResourceSharingId(item)
				if (!shareId) {
					uni.showToast({
						title: '当前资源缺少标识，无法选择',
						icon: 'none'
					})
					return
				}
				const index = this.selectedItems.indexOf(shareId)
				if (index > -1) {
					this.selectedItems.splice(index, 1)
				} else {
					this.selectedItems.push(shareId)
				}
				this.updateAllSelectedState()
			},

			// 切换全选状态
			toggleSelectAll() {
				const selectableItems = this.tableList_2
					.map(item => this.extractResourceSharingId(item))
					.filter(id => !!id)
				if (this.isAllSelected) {
					this.selectedItems = []
					this.isAllSelected = false
				} else {
					this.selectedItems = selectableItems
					this.isAllSelected = this.selectedItems.length === selectableItems.length && selectableItems.length > 0
				}
			},

			// 更新全选状态
			updateAllSelectedState() {
				const selectableCount = this.tableList_2.filter(item => this.extractResourceSharingId(item)).length
				this.isAllSelected = selectableCount > 0 && this.selectedItems.length === selectableCount
			},

			// 批量分配
			batchAssign() {
				if (this.selectedItems.length === 0) {
					uni.showToast({
						title: '请先选择要分配的资源',
						icon: 'none'
					})
					return
				}
				// 获取第一个选择项目的校区信息用于获取员工列表
				const firstSelectedItem = this.tableList_2.find(item => {
					const shareId = this.extractResourceSharingId(item)
					return shareId && this.selectedItems.includes(shareId)
				})
				if (firstSelectedItem) {
					this.getPersonnelAll(firstSelectedItem.customerResource.campus)
					this.select_item = { isBatch: true, selectedIds: [...this.selectedItems] }
					this.select_show = true
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 整体页面样式 */
	.assemble {
		background-color: #1a1a1a;
		min-height: 100vh;
		color: #fff;
	}

	/* 搜索区域样式 */
	.search_section {
		padding: 20rpx;
		background-color: #2a2a2a;
		margin-bottom: 20rpx;

		.item {
			display: flex;
			align-items: center;
			gap: 20rpx;
		}

		.input_box {
			flex: 1;
			background-color: #3a3a3a;
			border-radius: 8rpx;
			padding: 24rpx;

			.input_box_text {
				color: rgba(255, 255, 255, 0.6);
				font-size: 28rpx;
			}
		}

		// fui-input组件样式调整
		/deep/ .fui-input {
			height: 80rpx !important;
			min-height: 80rpx !important;
		}

		/deep/ .fui-input__input {
			height: 80rpx !important;
			line-height: 80rpx !important;
			color: rgba(255, 255, 255, 0.9) !important;
			font-size: 28rpx !important;
		}

		// fui-select组件样式调整
		/deep/ .fui-select {
			height: 80rpx !important;
			min-height: 80rpx !important;
		}

		/deep/ .fui-select__selector {
			height: 80rpx !important;
			line-height: 80rpx !important;
			color: rgba(255, 255, 255, 0.9) !important;
			font-size: 28rpx !important;
		}

		// fui-date-picker组件样式调整
		/deep/ .fui-date-picker {
			height: 80rpx !important;
			min-height: 80rpx !important;
		}

		.button {
			background-color: #29d3b4;
			color: #fff;
			padding: 24rpx 40rpx;
			border-radius: 8rpx;
			font-size: 28rpx;
			font-weight: 500;
		}
	}

	/* 卡片样式 */
	.card {
		background-color: #2a2a2a;
		margin: 20rpx;
		border-radius: 16rpx;
		overflow: hidden;
		position: relative;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
	}

	/* 新资源水印 */
	.status-watermark {
		position: absolute;
		top: 0;
		left: 0;
		background: linear-gradient(135deg, #ff6b35, #ff5722);
		color: #fff;
		font-size: 20rpx;
		font-weight: 600;
		padding: 8rpx 20rpx;
		z-index: 10;
		border-radius: 0 0 12rpx 0;
		min-width: 80rpx;
		text-align: center;
	}

	/* 卡片内容主要布局 */
	.card-content {
		display: flex;
		padding: 0;
		background: transparent;
	}

	.card-main {
		flex: 1;
		padding: 28rpx 20rpx 0 20rpx;
		background: transparent;
	}

	/* 头部信息行：头像、姓名、电话、状态标签 */
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-top: 24rpx;
		background: transparent;
	}

	.user-info-section {
		display: flex;
		align-items: center;
		flex: 1;
		background: transparent;
	}

	.user-avatar {
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.card-image {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		border: 3rpx solid rgba(255, 255, 255, 0.1);
	}

	.user-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.card-text {
		font-size: 28rpx;
		color: #fff;
		font-weight: 600;
		margin: 0;
		padding: 0;
	}

	.card-con-span {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.7);
		margin: 0;
		padding: 0;
	}

	/* 状态标签区域 */
	.status-section {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 12rpx;
	}

	.status-tag {
		font-size: 22rpx;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		color: #fff;
		text-align: center;
		font-weight: 500;
		min-width: 80rpx;
	}

	.status-tag.status-open {
		background-color: #ff4d4f;
	}

	.status-tag.status-closed {
		background-color: #52c41a;
	}

	.visit-status {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.visit-tag {
		font-size: 20rpx;
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		color: #fff;
		text-align: center;
		min-width: 80rpx;
		font-weight: 500;
	}

	.visit-tag.visit-arrived {
		background-color: #1890ff;
	}

	.visit-tag.visit-not-arrived {
		background-color: #8c8c8c;
	}

	/* 分配状态样式 */
	.assign-status .assigned-to {
		font-size: 22rpx;
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		font-weight: 500;
	}

	.assigned-to.unassigned {
		color: #ff6b35;
		background-color: rgba(255, 107, 53, 0.2);
	}

	.assigned-to.assigned {
		color: #52c41a;
		background-color: rgba(82, 196, 26, 0.2);
	}

	/* 详细信息网格布局 */
	.card-single-row {
		display: flex;
		background: transparent;
		border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
		margin-bottom: 8rpx;
	}

	.card-bottom-row {
		display: flex;
		padding: 8rpx 32rpx 16rpx 32rpx;
		background: transparent;
		border-top: 1rpx solid rgba(255, 255, 255, 0.1);
		margin-top: 8rpx;
	}

	.card-info-grid {
		display: flex;
		gap: 40rpx;
		background: transparent;
	}

	.info-column {
		flex: 1;
		background: transparent;
	}

	.card-con {
		display: flex;
		margin-bottom: 16rpx;
		font-size: 30rpx;
		line-height: 1.6;
		background: transparent;
		align-items: flex-start;
	}

	.info-label {
		color: rgba(255, 255, 255, 0.8);
		min-width: 160rpx;
		font-weight: 500;
		flex-shrink: 0;
		font-size: 28rpx;
	}

	.info-value {
		color: #fff;
		flex: 1;
		word-break: break-all;
		font-weight: 400;
		font-size: 28rpx;
	}

	/* 有效状态样式 */
	.status-valid {
		color: #52c41a !important;
		font-weight: 600 !important;
	}

	.status-invalid {
		color: #ff4d4f !important;
		font-weight: 600 !important;
	}

	/* 底部操作按钮 */
	.card-actions {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 30rpx;
		gap: 24rpx;
		background: transparent;
		border-top: 2rpx solid rgba(255, 255, 255, 0.1);
		margin-top: 24rpx;
	}

	.btn-item:active {
		transform: scale(0.95);
		background: linear-gradient(135deg, rgba(41, 211, 180, 0.4), rgba(41, 211, 180, 0.2));
	}

	.btn-item .image {
		width: 48rpx;
		height: 48rpx;
	}

	/* 分配按钮特殊样式 */
	.btn-item.assign-btn {
		background: linear-gradient(135deg, #ff6b35, #ff5722);
		border: 2rpx solid rgba(255, 107, 53, 0.5);
		border-radius: 12rpx;
		width: auto;
		height: auto;
		padding: 16rpx 32rpx;
	}

	.btn-item.assign-btn .ling {
		color: #fff;
		font-size: 26rpx;
		font-weight: 600;
	}

	.btn-item.contact-btn {
		background: linear-gradient(135deg, #4caf50, #45a049);
		border: 2rpx solid rgba(76, 175, 80, 0.5);
		border-radius: 12rpx;
		width: auto;
		height: auto;
		padding: 16rpx 32rpx;
	}

	.btn-item.contact-btn .ling {
		color: #fff;
		font-size: 26rpx;
		font-weight: 600;
	}

	/* 批量选择复选框 */
	.batch_checkbox {
		margin-right: 20rpx;
	}

	.checkbox {
		display: inline-block;
		width: 40rpx;
		height: 40rpx;
		border: 3rpx solid rgba(255, 255, 255, 0.3);
		border-radius: 8rpx;
		text-align: center;
		line-height: 34rpx;
		font-size: 24rpx;
		color: transparent;
		background-color: transparent;
		transition: all 0.3s ease;
	}

	.checkbox.checked {
		background-color: #29d3b4;
		border-color: #29d3b4;
		color: #fff;
		transform: scale(1.1);
	}

	/* 搜索弹窗样式 */
	.search_popup_mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 1000;
		display: flex;
		align-items: flex-start;
		justify-content: center;
		padding-top: 100rpx;
	}

	.search_popup_content {
		background-color: #2a2a2a;
		border-radius: 20rpx;
		width: 90%;
		max-width: 700rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.4);
	}

	.popup_header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 2rpx solid rgba(255, 255, 255, 0.1);
	}

	.popup_title {
		font-size: 36rpx;
		font-weight: 600;
		color: #fff;
	}

	.popup_close {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: rgba(255, 255, 255, 0.1);
	}

	.close_text {
		font-size: 32rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.popup_scroll_view {
		max-height: 60vh;
	}

	.popup_filter_section {
		padding: 32rpx;
	}

	.popup_filter_row {
		display: flex;
		gap: 20rpx;
		margin-bottom: 32rpx;
	}

	.popup_filter_item {
		flex: 1;
	}

	.popup_filter_item.full_width {
		flex: 2;
	}

	.popup_filter_label {
		display: block;
		color: rgba(255, 255, 255, 0.8);
		font-size: 28rpx;
		margin-bottom: 12rpx;
		font-weight: 500;
	}

	.popup_filter_input {
		width: 100%;
		padding: 20rpx;
		background-color: #3a3a3a;
		border: 2rpx solid rgba(255, 255, 255, 0.1);
		border-radius: 8rpx;
		color: #fff;
    height: 84rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}

	.popup_filter_input::placeholder {
		color: rgba(255, 255, 255, 0.4);
	}

	.popup_filter_picker {
		width: 100%;
		padding: 20rpx;
		background-color: #3a3a3a;
		border: 2rpx solid rgba(255, 255, 255, 0.1);
		border-radius: 8rpx;
		color: #fff;
		font-size: 28rpx;
		text-align: center;
		box-sizing: border-box;
	}

	.popup_filter_buttons {
		display: flex;
		padding: 32rpx;
		gap: 20rpx;
		border-top: 2rpx solid rgba(255, 255, 255, 0.1);
		background-color: #333;
	}

	.popup_filter_btn {
		flex: 1;
		padding: 24rpx 0;
		text-align: center;
		border-radius: 8rpx;
		font-size: 28rpx;
		font-weight: 500;
		transition: all 0.3s ease;
	}

	.reset_btn {
		background-color: #6c757d;
		color: #fff;
	}

	.search_btn {
		background-color: #29d3b4;
		color: #fff;
	}

	.close_btn {
		background-color: #dc3545;
		color: #fff;
	}

	/* 批量操作控制栏 */
	.batch_control_bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background-color: #333;
		border-radius: 8rpx;
		margin: 20rpx;
	}

	.batch_actions_left {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.batch_toggle_btn {
		padding: 16rpx 32rpx;
		background-color: #29d3b4;
		color: #fff;
		border-radius: 8rpx;
		font-size: 26rpx;
		font-weight: 500;
	}

	.batch_toggle_btn.cancel {
		background-color: #dc3545;
	}

	.batch_select_all {
		display: flex;
		align-items: center;
		gap: 12rpx;
		color: #fff;
		font-size: 26rpx;
	}

	.select_all_text {
		color: rgba(255, 255, 255, 0.8);
	}

	.batch_assign_btn {
		padding: 16rpx 32rpx;
		background-color: #ff6b35;
		color: #fff;
		border-radius: 8rpx;
		font-size: 26rpx;
		font-weight: 500;
	}
</style>
