<template>
	<view class="page flex-col">
		<view class="box_1 flex-col justify-end">


			<view class="box_7 flex-row justify-between">
				<view class="image-text_1 flex-row justify-between">
					<view class="group_1 flex-col">
						<view class="image-wrapper_2 flex-col">
							<image class="image_2" referrerpolicy="no-referrer"
								:src="selfInfo && selfInfo.avatar ? imageUrl + '/' + selfInfo.avatar : '/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG185e54e3ffd47170ac4e6e5108c9a54f.png'" />
						</view>
					</view>
					<view class="text-group_1 flex-col justify-between">
						<view v-if="selfInfo.nickname" class="text_3">{{ selfInfo.nickname }}</view>
						<view v-if="selfInfo.username" class="text_3">{{ selfInfo.username }}</view>
						<view v-else @click="toLogin()" class="text_2">登录/注册</view>
						<text v-if="!selfInfo.username" class="text_3">登录将开启全部服务</text>
					</view>
				</view>
				<view class="image-text_2 flex-col justify-between" @click="toMyQrCode()">
					<image class="label_1" referrerpolicy="no-referrer"
						src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG7e67772393591f7c5436c0b59f7b3b17.png" />
					<text class="text-group_2">学车码</text>
				</view>
			</view>
			<view class="box_8 flex-row">
				<view class="image-wrapper_3 flex-col justify-center">
					<image class="label_2" referrerpolicy="no-referrer"
						:src="coachDetails && coachDetails.image ? imageUrl + '/' + coachDetails.image : '/static/lanhu_gerenzhongxin/FigmaDDSSlicePNGa95a4d1d98d08b238a3082514eefafd0.png'" />
				</view>
				<view class="text-group_3 flex-col justify-between">
					<text class="text_4" v-if="coachDetails.name != null">{{ coachDetails.name }}</text>
					<text class="text_111" v-else> 暂无教练信息</text>
					<view class="text-wrapper_1" v-if="coachDetails.seniority != null">
						<text class="text_5">教龄：</text>
						<text class="text_6">{{ coachDetails.seniority }}</text>
						<text class="text_7">年</text>
					</view>

				</view>
				<!-- <view class="text-wrapper_2" v-if="coachDetails">
          <text class="text_8">学员数：</text>
          <text class="text_9">{{}}</text>
        </view>
		<view class="text-wrapper_2" v-else>
		  <text class="text_8">暂无数据</text>
		</view> -->
			</view>
		</view>
		<view class="box_9 flex-col">
			<view class="block_1 flex-col">
				<text class="text_10">我的订单</text>
				<view class="list_1 flex-row">
					<view class="image-text_3 flex-col justify-between" v-for="(item, index) in loopData" :key="index"
						@click="toOrderPage(item.orderType,item.type)">
						<image class="label_3" referrerpolicy="no-referrer" :src="item.url" />
						<text class="text-group_4" v-text="item.text"></text>
					</view>
				</view>
			</view>

			<view class="menu-list">
				<!-- 个人信息 -->
				<view class="menu-item" @click="goMyInDetails()">
					<image class="menu-icon"
						src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG1bb0cdc369203c305a42d848736e8f01.png" />
					<text class="menu-text">个人信息</text>
					<image class="menu-arrow"
						src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG4f20daae79bb7c60189f8702897465d1.png" />
				</view>

				<!-- <view class="menu-item">
		  <button open-type="contact" class="menu-item-btn">
			<image class="menu-icon" src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNGb5e90b5b4c1f154eb4e27313164118a4.png" />
			<text class="menu-text">在线客服</text>
			<image class="menu-arrow" src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG4f20daae79bb7c60189f8702897465d1.png" />
		  </button></view> -->

				<!-- 消息中心 -->
				<view class="menu-item" @click="goFeedback">
					<image class="menu-icon"
						src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNGa728895586dafec1bde5f90c89d05c48.png" />
					<text class="menu-text">消息中心</text>
					<text class="message-num" v-if="noReadNum > 0">{{ noReadNum }}</text>
					<image class="menu-arrow"
						src="/static/lanhu_gerenzhongxin/FigmaDDSSlicePNG4f20daae79bb7c60189f8702897465d1.png" />
				</view>
			</view>
		</view>

		<!-- <tabbar :msg='msg'></tabbar> -->
		<u-popup round="20" :show="showQrCode" @close="closeQrCode" mode="center" zoom="false" @open="openQrCode">
			<view style="padding: 50rpx 50rpx 20rpx 50rpx">
				<canvas id="qrcode" canvas-id="qrcode" style="width: 300rpx;height: 300rpx" />
			</view>
			<span style="text-align: center;margin-bottom: 20rpx;">学车码</span>
		</u-popup>
	</view>
</template>
<script>
	import headers from '../../components/header/headers.vue'
	import tabbar from '../../components/tabbar/tabbar.vue'
	import request from '@/utils/request.js'
	import UQRCode from 'uqrcodejs';
	import {
		getLocalUserInfo,
		getToken,
		setLocalUserInfo
	} from '@/utils/auth'

	export default {

		data() {
			return {
				msg: "3",
				selfInfo: {},
				selfInfoLocal: {},
				coachDetails: {},
				userDetails: {},
				orderList: {},
				processList: {},
				showQrCode: false,
				isCreateQrCode: true,
				noReadNum: 0,
				rpxUnit: 2,
				loopData: [{
						url: '/static/myImgs/alreadyPaid.png',
						text: '已付款',
						orderType: '2',
						type: '2',
					},
					{
						url: '/static/myImgs/alreadyInterviewed.png',
						text: '已面签',
						orderType: '4',
						type: '3',
					},
					{
						url: '/static/myImgs/registered.png',
						text: '已报名',
						orderType: '2',
						type: '4',
					},
					{
						url: '/static/myImgs/allOrder.png',
						text: '全部订单',
						orderType: '',
						type: '1',
					}
				],
				constants: {},
				imageUrl: this.$imagesUrl,
			};
		},
		onLoad() {
			console.log('userInfo', getLocalUserInfo())
			console.log('myToken', getToken())
			this.selfInfoLocal = getLocalUserInfo()
			this.getUserInfo()
			this.systemInfo()

		},
		onShow() {
			if (getToken()) {
				this.selfInfoLocal = getLocalUserInfo()
				this.getUserInfo()
				this.systemInfo()
			}

		},
		onPullDownRefresh() {
			console.log("刷新");
			uni.stopPullDownRefresh()
			this.getUserInfo()
		},
		onReachBottom() {
			// this.show = true
			setTimeout(() => {
				console.log("加载执行");
			}, 2000)
		},
		components: {
			headers,
			tabbar
		},
		methods: {
			systemInfo() {
				const systemInfo = uni.getSystemInfoSync();
				//1rpx 转换px 的单位
				this.rpxUnit = (systemInfo.screenWidth / 750)
			},
			goback() {
				uni.navigateBack()
			},
			toLogin() {
				uni.navigateTo({
					url: "/pages/login/login"
				})
			},
			createQrCode(data) {
				const qr = new UQRCode();
				qr.data = data;
				qr.size = 300 * this.rpxUnit - 10;
				qr.make();
				const ctx = uni.createCanvasContext('qrcode',
					this); // 组件内调用需传this，vue3 中 this 为 getCurrentInstance()?.proxy
				qr.canvasContext = ctx;
				qr.drawCanvas();
				this.isCreateQrCode = false
			},
			closeQrCode() {
				this.showQrCode = false
			},
			openQrCode() {

				// 判断是否有二维码 有了不需要绘制
				if (this.isCreateQrCode) {
					this.createQrCode(this.userDetails.uniqueCode)
				}
			},
			/*async findSelfInfo() {
			  let res = await request({
			    url: `/app-api/small/driving/findSelfInfo`,
			    method: 'get',
			  })
			  console.log(res, 138);
			  this.selfInfo = res
			},*/
			toMyQrCode() {
				if (!getToken()) {
					uni.showModal({
						title: '未登录',
						content: '请先登录',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								});
							}
						}
					});
					return;
				}
				this.showQrCode = true
			},

			toOrderPage(orderType, type) {
				if (!getToken()) {
					uni.navigateTo({
						url: "/pages/login/login"
					})
					return
				}
				uni.navigateTo({
					url: `/newPages/orderList/index?orderType=${orderType}&type=${type}&userId=${this.selfInfo.id}`
				})
			},
			goMyInDetails() {
				if (!getToken()) {
					uni.navigateTo({
						url: "/pages/login/login"
					})
					return
				}
				uni.navigateTo({
					url: `/pagesA/information/index?userId=${this.selfInfo.id}`
				})
			},
			goFeedback() {
				uni.navigateTo({
					url: "/newPages/messageCenter/index"
				})
			},


			getUserInfo() {
				if (!getToken()) {
					return;
				}
				request({
					url: '/app-api/small/dl-drive-school-student/getUsersInfo',
					method: 'GET',
				}).then(res => {
					this.selfInfo = res.data
					if (this.selfInfo != null) {
						setLocalUserInfo(this.selfInfo)
					}
					this.getOrder()
					this.getStudentInfo()
					this.getNoReadNum()
				})
			},
			getStudentInfo() {
				request({
					url: '/app-api/small/dl-drive-school-student/getByUserId',
					method: 'GET',
					params: {
						userId: this.selfInfo.id
					}
				}).then(res => {
					this.userDetails = {
						...res.data
					};
				});
			},

			getCoachDetails(coachId) {
				request({
					url: '/app-api/dl-drive-school-coach-small/getCoachByUserId',
					method: 'GET',
					params: {
						userId: coachId
					}
				}).then(res => {
					this.coachDetails = res.data
				})
			},

			getOrder() {
				request({
					url: '/app-api/small/drive/school-course-order/getCourseByLoginUser',
					method: 'GET',
				}).then(res => {
					this.orderList = res.data
					if (this.orderList.length > 0) {
						this.getProcess(this.orderList[0].courseId)

					}
				})
			},

			getProcess(courseId) {
				request({
					url: '/app-api/process/getAllByCourseId',
					method: 'GET',
					params: {
						courseId: courseId
					}
				}).then(res => {
					let result = null; // 默认返回 null（如果没有符合条件的数据）

					if (res.data && Array.isArray(res.data)) {
						this.processList = res.data;

						// 1. 筛选出所有 status === "1" 的数据（注意是字符串 "1"）
						const statusOneItems = this.processList.filter(item => item.status === "1");

						if (statusOneItems.length === 1) {
							// 2. 如果只有一条，直接赋值
							result = statusOneItems[0];
							this.getCoachDetails(result.coachId)
						} else if (statusOneItems.length > 1) {
							// 3. 如果有多条，按 subject（int 类型）降序排序，取第一条（subject 最大的）
							const sortedItems = [...statusOneItems].sort((a, b) => b.subject - a.subject);
							result = sortedItems[0];
							this.getCoachDetails(result.coachId)
						}
						// 如果没有数据，result 保持 null
					}

					return result; // 如果需要返回结果，可以加上 return
				}).catch(error => {
					console.error('请求出错:', error);
					return null; // 出错时也返回 null
				});
			},

			//获取未读消息数量
			async getNoReadNum() {
				await request({
					url: "/app-api/system/notify-message/get-unread-count",
					method: "GET",
					tenantIdFlag: false
				}).then((res) => {
					if (res.code == 0) {
						this.noReadNum = res.data
					}
				})
			},

		}
	};
</script>
<style lang='scss'>
	@import '../common/common.scss';
	@import './assets/style/index.rpx.scss';
</style>