<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="openShowDrawer()">
						<view class="input_box_text">用户名/手机号/时间范围</view>
					</view>
					<view class="button" @click="openShowDrawer()">搜索</view>
				</view>
			</view>
			<view class="card" v-for="(v,k) in tableList_1" :key="k">
				<view style="width: 70%;" @click="clue_info(v)">
					<view style="display: flex;align-items: center;padding: 20rpx;">
						<view>
							<image :src="$util.img('/uniapp_src/static/images/index/myk.png')" class="card-image">
							</image>
						</view>
						<view class="card-text">{{ v.customerResource.name }}</view>
						<!--            <view class="card-label">{{ v.is_status == 1 ? '试听' : '成交' }}</view>-->
					</view>
					<view class="card-con">
						首联系人：{{ v.customerResource.name }} <span
							class="card-con-span">{{ v.customerResource.decision_maker }}</span>
					</view>
					<view class="card-date">
						<view class="card-con">
							{{ $util.formatToDateTime((v.customerResource.updated_at || ''), 'm-d H:i') }}
							跟进
						</view>
						<view style="margin-left: 30rpx;">
							<view style="display: flex;align-items: center;">
								<view style="padding: 12rpx;">
									<image v-if="v.customerResource.initial_intent == 'high'"
										:src="$util.img('/uniapp_src/static/images/index/intention3.png')"
										class="drop-image-x"></image>
									<image v-else-if="v.customerResource.initial_intent == 'medium'"
										:src="$util.img('/uniapp_src/static/images/index/intention2.png')"
										class="drop-image-x"></image>
									<image v-else :src="$util.img('/uniapp_src/static/images/index/intention1.png')"
										class="drop-image-x"></image>
								</view>
								<view class="title-x">
									意向：{{ v.customerResource && v.customerResource.initial_intent_name || '' }}</view>
							</view>
						</view>
					</view>
				</view>
				<!--只有注册了member表的账号才可操作IM对话-->
				<view style="width: 15%;">
					<image v-if="v.customerResource.member_id"
						:src="$util.img('/uniapp_src/static/images/index/message.png')" class="image"
						@click="openViewMyMessage(v)"></image>
				</view>
				<view style="width: 15%;">
					<image v-if="v.customerResource.phone_number"
						:src="$util.img('/uniapp_src/static/images/index/phone.png')" class="image" @click="dialTel(v)">
					</image>
				</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="openShowDrawer()">
						<view class="input_box_text">用户名/手机号/时间范围</view>
					</view>
					<view class="button" @click="openShowDrawer()">搜索</view>
				</view>
			</view>
			<view class="card" v-for="(v,k) in tableList_2" :key="k">
				<view style="width: 70%;">
					<view style="display: flex;align-items: center;padding: 20rpx;">
						<view>
							<image :src="$util.img('/uniapp_src/static/images/index/myk.png')" class="card-image">
							</image>
						</view>
						<view class="card-text">{{v.customerResource.name}}</view>
						<!--            <view class="card-label">{{v.is_status == 1 ? '试听' : '成交'}}</view>-->
					</view>
					<view class="card-con">
						决策人：{{v.customerResource.name}} <span
							class="card-con-span">{{v.customerResource.decision_maker}}</span>
					</view>
					<view class="card-date">
						<view class="card-con">
							{{ $util.formatToDateTime((v.customerResource.updated_at || ''),'m-d H:i') }} 跟进
						</view>
						<view style="margin-left: 30rpx;">
							<view style="display: flex;align-items: center;">
								<view style="padding: 12rpx;">
									<image v-if="v.customerResource.initial_intent == 'high'"
										:src="$util.img('/uniapp_src/static/images/index/intention3.png')"
										class="drop-image-x"></image>
									<image v-else-if="v.customerResource.initial_intent == 'medium'"
										:src="$util.img('/uniapp_src/static/images/index/intention2.png')"
										class="drop-image-x"></image>
									<image v-else :src="$util.img('/uniapp_src/static/images/index/intention1.png')"
										class="drop-image-x"></image>
								</view>
								<view class="title-x">
									意向：{{ v.customerResource && v.customerResource.initial_intent_name || '' }}</view>
							</view>
						</view>
					</view>
				</view>
				<view style="width: 15%;">
					<!--          <image :src="$util.img('/uniapp_src/static/images/index/message.png')" class="image"></image>-->
				</view>
				<view style="width: 15%;" @click="openAssign(v)">
					<view class="ling">领</view>
				</view>
			</view>
		</scroll-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"></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="开始时间-结束时间"
										@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>
		<AQTabber />
	</view>
</template>

<script>
	import AQTabber from "@/components/AQ/AQTabber.vue"
	import apiRoute from '@/api/apiRoute.js';
	import marketApi from '@/api/market.js';

	export default {
		components: {
			AQTabber,
		},
		data() {
			return {
				loading: false, //加载状态
				lowerThreshold: 100, //距离底部多远触发
				isReachedBottom: false, //防止重复加载|true=不可加载|false=可加载
				selectedDate: this.getCurrentDate(), // 初始化当前日期
				//筛选条件
				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)
					phone_number: '', //客户资源表-手机号
					name: '', //客户资源表-用户姓名
				},
				//数据列表
				tableList_1: [], //表格数据

				//资源分配列表相关
				//筛选条件
				filteredData_2: {
					page: 1, //当前页码
					limit: 10, //每页返回数据条数
					total: 10, //数据总条数
					shared_by: '0', //共享人ID|0=未分配
					shared_at_str: '', //共享时间|[开始时间(Y-m-d),结束时间(Y-m-d)]
					phone_number: '', //客户资源表-手机号
					name: '', //客户资源表-用户姓名
				},
				//数据列表
				tableList_2: [], //表格数据

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

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

				//抽屉搜索条件展示窗相关
				showDrawer: false, //是否展示|false=否
				showDrawerForm: {
					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() {
				await this.getUserInfo();
				if (this.segmented_type == 1) {
					await this.getList_1();
				} else {
					await this.getList_2();
				}
			},

			//获取用户信息
			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() {
				let res = await apiRoute.common_getPersonnelAll({
					personnel_id: this.userInfo.id, //客户id
					account_type: 'market', //账号类型|teacher=老师,market=销售
				})
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				let arr = []
				res.data.forEach((v, k) => {
					arr.push({
						text: v.name,
						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
					uni.showToast({
						title: '暂无更多',
						icon: 'none'
					})
					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
				}

				this.tableList_1 = this.tableList_1.concat(res.data.data); // 使用 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 //数据总条数
			},
			//获取列表-资源分配
			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
					uni.showToast({
						title: '暂无更多',
						icon: 'none'
					})
					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(123123, res)

				this.tableList_2 = this.tableList_2.concat(res.data.data); // 使用 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 = '' //客户资源表-用户姓名

				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 = '' //客户资源表-用户姓名

					//我的客户
					//重置为第一页
					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 = '' //客户资源表-用户姓名
					//资源分配
					//重置为第一页
					await this.resetFilteredData_2()
					await this.getList_2()
				}

			},

			//跳转页面-我的消息
			openViewMyMessage(item) {
				let from_id = this.userInfo.id //发送者的id
				let to_id = item.customerResource.id //接收者ID
				this.$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;
				}


				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, //标签
				}

				let res = await apiRoute.xs_communicationRecordsAdd(param) //添加通过记录
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}


				uni.makePhoneCall({
					phoneNumber: tel
				})



			},

			//客户详情
			clue_info(item) {
				let resource_sharing_id = item.id ///共享资源表id
				this.$navigateTo({
					url: `/pages/market/clue/clue_info?resource_sharing_id=${resource_sharing_id}`
				})
			},

			//公海-分配客户给员工相关
			//打开分配列表
			openAssign(item) {
				this.select_item = item
				this.select_show = true
			},
			//关闭分配列表
			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() //关闭选择窗
				let param = {
					resource_sharing_id: select_item.id, //共享资源表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)
			},

			//时间选择器相关
			//监听-时间选择器结果
			changeDatePicker(e) {
				console.log('时间', e)
				let shared_at_str = `${e.startDate.result} ~ ${e.endDate.result}`
				this.showDrawerForm.shared_at_str = shared_at_str
				this.cancelDatePicker()
			},
			//打开时间选择器
			openDatePicker() {
				this.date_picker_show = true
			},
			//关闭时间选择
			cancelDatePicker() {
				this.date_picker_show = 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 //客户资源表-用户姓名
					//我的客户
					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 //客户资源表-用户姓名
					//资源分配
					await this.resetFilteredData_2()
					await this.getList_2()
				}
				this.closeShowDrawer()
			},

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

<style lang="less" scoped>
	.assemble {
		width: 100%;
		height: 100vh;
		background-color: #292929;
		overflow: auto;

		.search_section {
			margin-top: 20rpx;
			padding: 10rpx 20rpx;
			display: flex;
			flex-direction: column;

			.item {
				height: 60rpx;
				display: flex;
				justify-content: center;

				.input_box {
					width: 75%;

					.input_box_text {
						height: 60rpx;
						line-height: 60rpx;
						background-color: #fff;
						padding-left: 20rpx;
						color: #cccccc;
						font-size: 28rpx;
					}
				}
			}
		}
	}

	.search {
		width: 92%;
		margin: auto;
		display: flex;
		margin-top: 20rpx;
	}

	.selected {
		background: #294e48;
		border-radius: 16rpx;
		padding: 12rpx 8rpx;
		text-align: center;
		color: #29d3b4;
		margin-left: 5rpx;
	}

	.not-selected {
		margin-left: 5rpx;
		background: #ffffff;
		border: 4rpx #959595 solid;
		border-radius: 16rpx;
		padding: 12rpx 8rpx;
		text-align: center;
	}

	.card {
		width: 92%;
		margin: 20rpx auto;
		background: #434544;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
	}

	.card-image {
		width: 60rpx;
		height: 60rpx;
	}

	.card-text {
		font-size: 32rpx;
		padding-left: 16rpx;
		color: #fff;
	}

	.card-label {
		margin-left: 30rpx;
		background: #76575a;
		width: 130rpx;
		padding: 8rpx 20rpx;
		color: #c9595a;
		text-align: center;
		border-radius: 0 50rpx 50rpx 40rpx;
	}

	.card-con {
		font-size: 30rpx;
		padding: 20rpx 10rpx 20rpx 16rpx;
		color: #fff;
	}

	.card-con-span {
		font-size: 24rpx;
		color: #a47332;
		padding-left: 12rpx;
	}

	.drop-image-x {
		width: 20rpx;
		height: 20rpx;
	}

	.title-x {
		font-size: 28rpx;
		color: #fff;
		padding-left: 10rpx;
	}

	.card-date {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.image {
		width: 70rpx;
		height: 70rpx;
	}

	.neck {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: #f59a23;
		color: #fff;
		line-height: 60rpx;
		text-align: center;
	}

	//领取按钮
	.ling {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		color: #fff;
		width: 50rpx;
		height: 50rpx;
		background-color: #F59A23;
	}

	//抽屉搜索栏
	.fui-scroll__view {
		margin-top: 60rpx;
		width: 520rpx;
		flex: 1;
		overflow: hidden;

		.fui-title {
			padding: 40rpx 32rpx;
			padding-bottom: 20rpx;
			box-sizing: border-box;
			font-weight: bold;
		}

		.drawer_box {
			.item {
				display: flex;
				flex-direction: column;
				gap: 15rpx;

				.title {}

				.input_box {
					border: 1px solid #292929;
					width: 450rpx;

					::v-deep .fui-input__wrap {
						padding: 10rpx !important;
						height: 100%;
					}
				}
			}
		}

		.fui-btn__box {
			padding: 40rpx 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			gap: 30rpx;
		}

	}

	.button {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 5rpx;
		font-size: 24rpx;
		color: #fff;
		background-color: #29d3b4;
		width: 20%;
		height: 100%;


	}

	.clientbtn {
		width: 200px;
		height: 40px;
		font-size: 16px;
		border-radius: 5px;
	}
</style>