<template>
	<view>
		<view class="bgf center ptb20">客户详情</view>
		<view class="topBgline plr20 column justify-center">
			<view class="justify-between align-center  radius12">
				<view class="justify-start align-center">
					<u-avatar :src='user.avatar' size="60"></u-avatar>
					<view class="ml16 colorf">
						<view class="bold fs28 ">{{user.name?user.name:'用户信息加载中...'}}</view>
						<view class="fs24 mt20">备注：{{user.remark}}</view>
					</view>
				</view>
				<view class="ml90">
					<view @click="clearhuan()" class=" bgcolf fs24 w160 center radius40 colorf ptb10"
					 >清除缓存</view>
				</view>
			</view>
		</view>
		<view class="justify-between align-center bgf newsbox plr20">
			<view class="justify-start align-center pt20">
				<view class="fs28  fs32 bold" >看课记录</view>
				<text class=" fs24 ml10 u-border base-color-6 plr16 radius30 ptb2" 
				@click="seltype()">色盲模式</text>
			</view>
			<view class="lh45 plr20 fs24 radius40 h50 justify-between align-center" style="color: #999;"
			 @click="todetail">
				<view>	{{typestate==0?'更多详情':'点击收起'}}</view>
				<image src="/static/arrow_up.png" class="w30 h30 ml10" v-if='typestate==1'></image>
				<image src="/static/arrow_down.png" class="w30 h30 ml10" v-else></image>
			 </view>
		</view>
		<view class="bgf p20" v-if="!answertype">
			<view class="justify-start ">
				<view v-for="(item,index) in titname" :key="index" class="justify-start align-center ml28">
					<view :style="{ backgroundColor: statusColors[index] || '#CCCCCC' }" 
					class="w24 h24 radius4"></view>
					<view class="fs24 mr6 ml10">{{item}}</view>
				</view>
			</view>
			<view class="fs24 mt20 base-color-6" >近{{typestate==0?'7':'30'}}天看课记录</view>
			<view class="justify-between mt20">
				<view class="justify-start align-center mt12 " style="width: 100%;flex-wrap: wrap">
					<view class="w54 h54 mr20 radius4 mb12" v-for="(item,index) in answerlist" :key="index"
					>
						<view class="fs24 base-color-6">{{item.date.slice(-2)}}</view>
						<view :style="{ backgroundColor: statusColors[item.logType] || '#CCCCCC' }" 
						class="w30 h30 radius4"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="bgf p20" v-else>
			<view class="justify-start ">
				<view v-for="(item,index) in titname" :key="index" class="justify-start align-center ml28">
					<view class="w30 h30 radius4 base-bg-f5 u-border fs24 lh24"
					style="text-align: center;">{{statusText[index]}}</view>
					<view class="fs24 mr6 ml10">{{item}}</view>
				</view>
			</view>
			<view class="fs24 mt20 base-color-6" >近{{typestate==0?'7':'30'}}天看课记录</view>
			<view class="justify-between mt20">
				<view class="justify-start align-center mt12 " style="width: 100%;flex-wrap: wrap">
					<view class="w54 h54 mr20 radius4 mb12" v-for="(item,index) in answerlist"
					 :key="index">
						<view class="fs24 base-color-6">{{item.date.slice(-2)}}</view>
						<view class="w30 h30 radius4 base-bg-f5 u-border fs24 lh24"
						style="text-align: center;">{{statusText[item.logType]}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bgf p20 mt20">
			<view class="justify-between align-center"> 
				<view class="bold fs32">用户信息</view>
				<view @click="changeuser()" class="plr20 ptb6 radius40 justify-between align-center editbox">
					<image src="/static/services_edit.png " class="w28 h28"></image>
					<view class="fs24 ml10">修改用户信息</view>
				</view>
			</view>
			<view class="justify-between align-center fs24 mt20 " >
				<view class="base-color-9 mr40">性别</view>
				<view>{{moreInfo.sex?moreInfo.sex:'未知'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28 " >
				<view class="base-color-9 mr40">年龄</view>
				<view>{{moreInfo.age?moreInfo.age:'未知'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28">
				<view class="base-color-9 mr40">行为习惯</view>
				<view>{{moreInfo.habits?moreInfo.habits:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28">
				<view class="base-color-9 mr40">患病时间</view>
				<view>{{moreInfo.illnessTime?moreInfo.illnessTime:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28" >
				<view class="base-color-9 mr40">疾病</view>
				<view>{{moreInfo.disease?moreInfo.disease:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28" >
				<view class="base-color-9 mr40">家人的疾病</view>
				<view>{{moreInfo.familyDisease?moreInfo.familyDisease:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28 ">
				<view class="base-color-9 mr40">是否线下就诊</view>
				<view>{{moreInfo.isLine?'已线下就诊':'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28 " >
				<view class="base-color-9 mr40 ">体质</view>
				<view>{{moreInfo.constitution?moreInfo.constitution:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28" >
				<view class="base-color-9 mr40">使用药品</view>
				<view>{{moreInfo.medicine?moreInfo.medicine:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28" >
				<view class="base-color-9 mr40">咨询产品</view>
				<view>{{moreInfo.consultProduct?moreInfo.consultProduct:'无'}}</view>
			</view>
			<view class="justify-between align-center fs24 mt28" >
				<view class="base-color-9 mr40">是否已经购买产品</view>
				<view class="prodcutbox ">{{moreInfo.isBuy?'已购买':'无'}}</view>
			</view>
		</view>
		
		<!-- <view>首次进入接口{{msg122}}</view>
		<view>验签接口{{msg123}}</view>
		<view>获取详情接口{{msg124}}</view>
		<view>获取用户信息接口{{msg125}}</view> -->
		<view class="pt120"></view>
		<view class="justify-around botfun bgf">
			<view class="justify-start align-center bottom-btns" 
			style="background: linear-gradient( 90deg, #348ff0 0%, #267EF0 100%);"
			@click="navTo('/pages/user/courseManage?userId='+userId)" >
				<view class="colorf ml12">课程管理</view>
			</view>
			<view class="justify-start align-center bottom-btns" 
			style="background: linear-gradient( 90deg, #FE8227 0%, #FE4E12 100%);"
			@click="navTo('/pages/user/UrgeClasses?userId='+userId+'&corpId='+corpId)">
				<view class="colorf ml12" >催课管理</view>
			</view>
			
			<u-loading-page :loading='loadingimg' bg-color="rgba(0,0,0,0.6)" loading-mode="semicircle"></u-loading-page>
		</view>
	</view>
</template>

<script>
	import {
		getcustomerlist,
		getcustomer
	} from "@/api/user.js";
	import { getConfigSignature,getQwExternalContactDetails } from '@/api/common.js'
	export default {
		data() {
			return {
				answertype:false,
				typeOption: [{
					label: '全部',
					value: 0
				}, {
					label: '今天',
					value: 1
				}, {
					label: '昨天',
					value: 2
				}, {
					label: '前天',
					value: 3
				}, {
					label: '近七天',
					value: 4
				}],
				tabindex: 0,
				detailUser: [],
				user: [],
				answerlist:[],
				answerText:'禁用',
				id:'',
				dateTag:'',
				qwUserId:'',
				startTime:"",
				endTime:'',
				todayday: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				moreInfo:{},
				statusColors: {
					0: '#909399',
					1: '#0bc6ff',
					2: '#67c23a',
					3: '#f55a4f',
					4: '#ffd700',
				  },
				  statusText: {
				  	0: '﹨',
				  	1: '∎',
				  	2: '✔',
				  	3: '✖',
				  	4: '◇',
				    },
				titname:['未看课','看课中','完课','待看课','看课中断',],
				statelist:[
				{  status: 4 },
				{  status: 1 },
				{  status: 2 },
				{  status: 5 },
				{  status: 3 },
				{  status: 5 },
				{  status: 3 },
				  ],
				typestate:0,
				externalUserId:'',
				userId:null,
				qwUserExternalId:'',
				loadingimg:true,
				msg122:'',
				msg123:'',
				msg124:'',
				msg125:'',
				timer: null, // 定时器ID
			}
		},
		onShow() {
			// this.getuser()
			// this.detailUser =uni.getStorageSync('detailUser')
			// if(this.detailUser.status==0){
			// 	this.answerText='取消禁用'
			// }
			this.qwUserId=uni.getStorageSync('qwUserId')
			if(this.qwUserExternalId){
				this.getuser()
				this.getAnswerlists()
			}
			// this.$nextTick(()=>{
			// 	setTimeout(()=>{
			// 		console.log(12121212121)
			// 	})
			// },100)
		},
		mounted() {
			
		},
		 beforeDestroy() {
		    // 组件销毁时清除定时器
		    clearTimeout(this.timer);
		  },
		onLoad(options) {
			// 启动超时计时器（10秒）
			    this.timer = setTimeout(() => {
			      if (!this.requestCompleted) {
			        this.loadingimg = false;
			        uni.showToast({
			          title: '请求超时，请清除缓存！',
			          icon: 'none'
			        });
			      }
			    }, 10000);
			// this.id=option.id
			this.url=window.location.href;
			this.code=options.code;
			this.corpId=options.corpId;
			uni.setStorageSync("corpId",this.corpId);
			this.externalUserId=uni.getStorageSync("externalUserId");
			// var userId=uni.getStorageSync("qwUserId");
			// if(userId!=null&&userId!=undefined&&userId!=""){
			// 	this.userId=userId;
			// }
			// if(uni.getStorageSync("qwUserId")){
			// 	this.userId=uni.getStorageSync("qwUserId");
			// }
			this.msg122=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
			this.getConfigSignature()
			uni.$on('urgeUser', (data) => {
				console.log(data)
			  this.urgetoUser(data);
			});
			// uni.$on('urgeUser', this.urgetoUser(data));
			uni.$on('course', (data) => {
			  this.sendInput(data);
			});
			// uni.$on('course', this.sendInput(data));
			// if(this.externalUserId!=null&&this.externalUserId!=undefined&&this.userId!=null&&this.userId!=undefined){
			// 	this.getQwExternalContactDetails()
			// }
		},
		 onUnload() {
		    // 移除事件监听（避免内存泄漏）
		    uni.$off('course', this.sendInput());
			uni.$off('urgeUser', this.urgetoUser());
		  },
		methods: {
			seltype(){
				console.log(this.answertype)
				this.answertype=!this.answertype
			},
			clearhuan(){
				uni.removeStorageSync('qwarrid')
				uni.removeStorageSync('fsUserId')
				uni.removeStorageSync('externalUserId')
				uni.removeStorageSync('corpId')
				uni.showToast({
					title: "请退出页面后重新进入",
					icon: 'none',
				});
			},
			urgetoUser(data){
				setTimeout(function(){
					uni.navigateTo({
						url:data.pageurl
					})
					console.log(data)
				},200);
				this.loadingimg=false
				clearTimeout(this.timer);
				jWeixin.openEnterpriseChat({
						// 注意：userIds和externalUserIds至少选填一个。内部群最多2000人；外部群最多500人；如果有微信联系人，最多40人
					externalUserIds: data.nextExternalUserIds, // 参与会话的外部联系人列表，格式为userId1;userId2;…，用分号隔开。
					groupName: '',  // 会话名称。单聊时该参数传入空字符串""即可。
					chatId: "", // 若要打开已有会话，需指定此参数。如果是新建会话，chatId必须为空串
					success: function(res) {
						console.log(res);
						console.log("切换成功")
						uni.showToast({
							title: "切换成功",
							icon: 'none',
						});
						var data={cmd:"switchPage"};
						uni.$emit('sendMsg',data);
						 
					},
					fail: function(res) {
						console.log(res);
						console.log("切换失败")
						uni.showToast({
							title: "切换失败",
							icon: 'none',
						});
						var data={cmd:"switchPage"};
						uni.$emit('sendMsg',data);
					}
				});
			},
			sendInput(data){
				this.loadingimg=false
				clearTimeout(this.timer);
				jWeixin.invoke('sendChatMessage', {
					msgtype:"news", //消息类型，必填
					enterChat: true,
					news:
					{
						desc: data.linkDescribe,
						title: data.linkTitle, 
						imgUrl: data.linkImageUrl,
						link: data.linkUrl
					}
				}, function(res) {
					console.log("发送成功")
					console.log(res)
					uni.showToast({
						title: "发送成功",
					});
					jWeixin.invoke('closeWindow',{
					},function(res){
						// alert('关闭窗口')
					})
				})
			},
			changeuser(){
				if(!this.qwUserExternalId){
					uni.showToast({
						icon: 'none',
						title: '用户信息加载中...'
					})
					return
				}
				uni.navigateTo({
					url:'/pages/user/editUser?externalUserId='+this.qwUserExternalId
				})
			},
			getQwExternalContactDetails(){
				uni.showLoading({
					title: "加载中..."
				})
				var that=this
				var data = {
					corpId: this.corpId,
					userId:this.userId,
					externalUserId:this.externalUserId,
					
				};
				getQwExternalContactDetails(data).then(res => {
					if(res.code==200){
						uni.hideLoading()
						this.user=res.data;
						this.qwUserExternalId=res.data.id
						uni.setStorageSync('qwarrid',res.data.id)
						uni.setStorageSync('fsUserId',res.data.fsUserId)
						console.log("获取外部联系人详情接口",res)
						this.msg124=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
						this.getuser()
						this.getAnswerlists()
					}else{
					}
				});
			},
			getConfigSignature(){
				uni.showLoading({
					title: "加载中..."
				})
				
				var data = {
					corpId: this.corpId,
					url: this.url,
					code: this.code
				};
				// if(this.userId==null || this.userId==""){
					data.isGetUserId=1;
				// }
				// else{
					// data.isGetUserId=0;
				// }
				getConfigSignature(data).then(
					res => { 
						if(res.code==200){
							this.isConfig=true;
							const agentConfigSignature = res.config.agentConfigSignature;
							const configSignature = res.config.configSignature;
							const corpId = res.config.corpId;
							const nonceStr = res.config.nonceStr;
							const timestamp = res.config.timestamp;
							const agentId = res.config.agentId;
							
							if(res.config.userid!=null || res.config.userid!=''){
								this.userId = res.config.userid;//当前员工ID
								uni.setStorageSync("qwUserId",this.userId);
								// console.log("获取到USERID")
							}
							else{
								// console.log("不需要获取USERID")
							}
							// console.log(this.userId)
							var that=this;
							jWeixin.config({
								beta: true,
								debug: false,
								appId: corpId,
								timestamp: timestamp,
								nonceStr: nonceStr,
								signature: configSignature,
								jsApiList: ['getCurExternalContact','sendChatMessage','openEnterpriseChat','shareToExternalContact','closeWindow']
							});
							jWeixin.ready(() => {
								jWeixin.agentConfig({
									corpid: corpId,
									agentid: agentId,
									timestamp: timestamp,
									nonceStr: nonceStr,
									signature: agentConfigSignature,
									jsApiList: ['getCurExternalContact','sendChatMessage','openEnterpriseChat','shareToExternalContact','closeWindow'],
									success: (res) => {
										jWeixin.invoke('getCurExternalContact', {}, async (res) => {
											if (res.err_msg === "getCurExternalContact:ok") {
												this.msg123=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
												uni.hideLoading()
												that.externalUserId = res.userId;
												uni.setStorageSync("externalUserId",res.userId)
												that.getQwExternalContactDetails()
											} else {
												// 错误处理
											}
										});
										
									},
									fail: (res) => {
										console.error('agentConfig fail:', res);
									},
								});
							});
							jWeixin.error((res) => {
								console.error('wx.error:', res);
							});
						}
						else{
							// uni.setStorageSync("qwUserId",null);
							// console.log("获取USERID失败")
							// setTimeout(function(){
							// 	window.location.reload();
							// },5000);
						}
					},
					rej => {
						setTimeout(function(){
							window.location.reload();
						},500);
					}
				);
			},
			todetail(){
				if(this.typestate==0){
					this.typestate=1
				}else{
					this.typestate=0
				}
				this.getAnswerlists()
			},
			getuser(){
				uni.showLoading({
					title: "加载中..."
				})
				const data={
					qwExternalContactId:this.qwUserExternalId
				}
				getcustomer(data).then(res=>{
					console.log('获取客户详情记录接口',res)
					if (res.code == 200) {
						uni.hideLoading()
						this.msg125=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
						console.log('用户详情',this.detailUser)
						this.moreInfo=res.moreInfo
						console.log('用户的ai信息详情',this.moreInfo)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				})
			},
			getAnswerlists() {
				if(!this.qwUserExternalId){
					uni.showToast({
						icon: 'none',
						title: '用户信息加载中...'
					})
					return
				}
				uni.showLoading({
					title: "加载中..."
				})
				const params = {
					type:this.typestate,
					qwExternalContactId:this.qwUserExternalId,
					// qwExternalContactId:'19594956',
				}
				getcustomerlist(params).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						clearTimeout(this.timer);
						this.loadingimg=false
						this.answerlist=res.data.data
						console.log('看课记录内容',this.answerlist)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				})
			},
			navTo(url){
				uni.navigateTo({
					url
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #F5F7FA;
	}
	.prodcutbox{
		max-width: 60%;
		word-wrap: break-word;
	}
	.editbox{
		border: 2rpx #ECECEC solid;
		color: #757575;
	}
	.topBgline {
		background:#3975C6;
		// padding-top: 40rpx;
		height: 220rpx;
	}
	.newsbox{
		margin-top: -20rpx;
		border-radius: 24rpx 24rpx 0 0;
	}
	.bgcolf {
		background: rgba(255, 255, 255, 0.3);
	}

	.actsel {
		background-color: #1773ff;
		color: #fff;
		transition: background-color 0.4s ease-in-out;
	}

	.notact {
		background-color: #f8f8f8;
	}

	.livebox {
		width: calc(50% - 10rpx);
		background-color: #f8f8f8;
		padding: 20rpx 10rpx;
		border-radius: 12rpx;
	}

	.liveboxs {
		width: calc(33% - 10rpx);
		background-color: #f8f8f8;
		padding: 20rpx 10rpx;
		border-radius: 12rpx;
	}

	.bottom-btns {
		padding: 16rpx 80rpx;
		border-radius: 50rpx;
	}

	.botfun {
		position: fixed;
		width: 100%;
		bottom: 0rpx;
		padding: 20rpx 0;
	}
</style>