<template>
	<view class="my-v" v-if="loading">
		<view class="u-flex user-box">
			<view class="u-m-r-10">
				<u-avatar size="127" @click='chooseAvatar' :src='avatarSrc'></u-avatar>
			</view>
			<view class="u-flex-1 f-right" @click="personalPage('/pages/my/personalData/index')">
				<view class="u-font-36 u-m-l-16">{{baseInfo.realName}}</view>
				<view class="u-m-l-10 u-p-10">
					<u-icon name="arrow-right" color="#969799" size="28"></u-icon>
				</view>
			</view>
		</view>
		<view class="u-m-t-20 my-group-box" v-for="(group, index) in cellGroups" :key="index">
			<view class="my-group-box-inner">
				<u-cell-group :border="false" class="cell-group">
					<view v-for="(item, idx) in group.items" :key="idx">
						<u-cell-item :title="$t(item.title)" @click="openPage(item.page, item.param)"
							:title-style="titleStyle" :border-bottom="item.borderBottom"
							v-if="item.title!='app.my.scanCode'">
							<template #icon>
								<text :class="['icon-ym', item.icon, 'u-m-r-16', 'u-font-32', 'my-list']"
									:style="{ color: item.color }" />
							</template>
						</u-cell-item>
						<!-- #ifndef H5 -->
						<u-cell-item :title="$t(item.title)" @click="scanCode()" :title-style="titleStyle"
							:border-bottom="item.borderBottom" v-if="item.title=='app.my.scanCode'">
							<template #icon>
								<text :class="['icon-ym', item.icon, 'u-m-r-16', 'u-font-32', 'my-list']"
									:style="{ color: item.color }" />
							</template>
						</u-cell-item>
						<!-- #endif -->
					</view>
				</u-cell-group>
			</view>
		</view>
		<view class="u-p-t-20">
			<view class="logout-cell" hover-class="u-cell-hover" @click="logout">{{$t('app.my.logout')}}</view>
		</view>
	</view>
</template>
<script>
	import IndexMixin from './mixin.js'
	import {
		UpdateAvatar,
		UserSettingInfo,
		setMajor
	} from '@/api/common'
	import chat from '@/libs/chat.js'
	import {
		useUserStore
	} from '@/store/modules/user'
	import {
		useChatStore
	} from '@/store/modules/chat'

	export default {
		mixins: [IndexMixin],
		data() {
			return {
				titleStyle: {
					color: '#606266'
				},
				userInfo: '',
				avatarSrc: '',
				baseInfo: {},
				loading: false,
				cellGroups: [{
						items: [{
								title: 'app.my.organization',
								page: '/pages/my/organization/index',
								param: 'position',
								icon: 'icon-ym-zuzhi',
								color: '#6071F5',
								borderBottom: true
							},
							{
								title: 'app.my.switchIdentity',
								page: '/pages/my/identity/index',
								param: 'standing',
								icon: 'icon-ym-position1',
								color: '#F4A02F',
								borderBottom: true
							},
							{
								title: 'app.my.changeSystem',
								page: '/pages/my/changeSystem/index',
								icon: 'icon-ym-header-sys-toggle',
								color: '#3686F2',
								borderBottom: false
							},
						],
					},
					{
						items: [{
								title: 'app.my.personalSetting',
								page: '/pages/my/personalSetting/index',
								icon: 'icon-ym-shezhi',
								color: '#F46E1B',
								borderBottom: true
							},
							{
								title: 'app.my.accountSecurity',
								page: '/pages/my/accountSecurity/index',
								icon: 'icon-ym-secure',
								color: '#26C6A1',
								borderBottom: true
							},
							{
								title: 'app.my.contacts',
								page: '/pages/my/contacts/index',
								icon: 'icon-ym-contacts',
								color: '#6071F5',
								borderBottom: true
							},
							{
								title: 'app.my.chat',
								page: '/pages/message/chat/index',
								icon: 'icon-ym-chat',
								color: '#4CBF2A',
								borderBottom: false
							},
						],
					},
					{
						items: [{
								title: 'app.my.scanCode',
								page: '',
								icon: 'icon-ym-scanCode1',
								color: '#F7AA41',
								borderBottom: true
							},
							{
								title: 'app.my.setting',
								page: '/pages/my/settings/index',
								icon: 'icon-ym-route-appMenu',
								color: '#5944FC',
								borderBottom: false
							},
						],
					},
				],

			}
		},
		computed: {
			baseURL() {
				return this.define.comUploadUrl
			},
			baseURL2() {
				return this.define.baseURL
			},
			token() {
				return uni.getStorageSync('token')
			},
			report() {
				return this.define.report
			}
		},
		onLoad() {
			const chatStore = useChatStore()
			if (!chatStore.getSocket) chat.initSocket()
		},
		onShow() {
			// UserSettingInfo().then(res => {
			// 	this.baseInfo = res.data || {}
			// 	this.avatarSrc = this.baseURL2 + this.baseInfo.avatar
			// 	this.loading = true
			// })
			this.baseInfo = {
  "id": "777911634713641349",
  "account": "chenl",
  "realName": "默认",
  "organize": "引迈信息技术有限公司/总裁办",
  "company": null,
  "position": "总裁",
  "manager": null,
  "roleId": "",
  "creatorTime": 1767604989000,
  "prevLogTime": 1768896697000,
  "signature": null,
  "gender": "1",
  "nation": null,
  "nativePlace": null,
  "entryDate": null,
  "certificatesType": null,
  "certificatesNumber": null,
  "education": null,
  "birthday": null,
  "telePhone": null,
  "landline": null,
  "mobilePhone": null,
  "email": null,
  "urgentContacts": null,
  "urgentTelePhone": null,
  "postalAddress": null,
  "avatar": "/api/file/Image/userAvatar/001.png",
  "theme": "W-001",
  "language": "zh-CN",
  "ranks": null,
  "isTenant": false,
  "currentTenantInfo": null,
  "preferenceJson": null,
  "propertyJson": null,
  "pcOnlineModelList": [],
  "appOnlineModelList": [
    {
      "userId": "777911634713641349",
      "userAccount": null,
      "userName": "陈力/chenl",
      "loginTime": "2026-01-20 16:11",
      "loginIPAddress": "61.183.89.14",
      "loginSystem": "iPhone 18_5",
      "tenantId": "",
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiI3Nzc5MTE2MzQ3MTM2NDEzNDkiLCJyblN0ciI6IkdWczEzRTRBNWRkQU4zMEVIanM3d0JXOFlSQ1h5ZUs5IiwidXNlcl9pZCI6Ijc3NzkxMTYzNDcxMzY0MTM0OSIsInVzZXJfbmFtZSI6ImNoZW5sIiwic2luZ2xlTG9naW4iOjIsImV4cCI6MTc2ODk1MDY5NjYyNywidG9rZW4iOiJsb2dpbl90b2tlbl83ODMzMjk0NTA3OTUyMDQ2NzcifQ.85PXC7GbqgLEuoEcmgeuBBXyFCfgLJX-mq8_5a-cr8Y",
      "device": "APP",
      "organize": null,
      "loginBrowser": "Safari 18.5",
      "loginAddress": "湖北省武汉市 电信",
      "isCurrent": true
    },
    {
      "userId": "777911634713641349",
      "userAccount": null,
      "userName": "陈力/chenl",
      "loginTime": "2026-01-20 09:59",
      "loginIPAddress": "61.183.89.14",
      "loginSystem": "iPhone 18_5",
      "tenantId": "",
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiI3Nzc5MTE2MzQ3MTM2NDEzNDkiLCJyblN0ciI6Ik0yVDI5T2o3cEd0bTZiZkN1aXBYUklrR3BUaTZrT0FxIiwidXNlcl9pZCI6Ijc3NzkxMTYzNDcxMzY0MTM0OSIsInVzZXJfbmFtZSI6ImNoZW5sIiwic2luZ2xlTG9naW4iOjIsImV4cCI6MTc2ODkyODM5NDcyNywidG9rZW4iOiJsb2dpbl90b2tlbl83ODMyMzU5MDk4NDY4MjcwNzcifQ.wRKZT-ZEYc4Tao8k7LI9OPlPvnBhLFrzWdQsAljQIRA",
      "device": "APP",
      "organize": null,
      "loginBrowser": "Safari 18.5",
      "loginAddress": "湖北省武汉市 电信",
      "isCurrent": false
    }
  ]
}
this.loading = true
			uni.setNavigationBarTitle({
				title: "我的"
			})
		},
		methods: {
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					success: (res) => {
						// #ifdef H5
						let isAccept = new RegExp('image/*').test(res.tempFiles[0].type)
						if (!isAccept) return this.$u.toast(`请上传图片`)
						// #endif
						let tempFilePaths = res.tempFilePaths[0]
						uni.uploadFile({
							url: this.baseURL + 'userAvatar',
							filePath: tempFilePaths,
							name: 'file',
							header: {
								'Authorization': this.token
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data)
								if (data.code === 200) {
									UpdateAvatar(data.data.name).then(res => {
										this.$u.toast('头像更换成功')
										this.avatarSrc = this.baseURL2 + data.data.url
									})
								} else {
									this.$u.toast(data.msg)
								}
							},
							fail: (err) => {
								this.$u.toast('头像更换失败')
							}
						});
					}
				});
			},
			openPage(path, type) {
				if (!path) return
				let url = !!type ? path + '?majorType=' + type : path
				uni.navigateTo({
					url: url
				})
			},
			personalPage(path) {
				if (!path) return;
				const neededFields = [
					'realName', 'nation', 'gender', 'nativePlace', 'certificatesType',
					'certificatesNumber', 'education', 'birthday', 'telePhone', 'landline',
					'urgentContacts', 'urgentTelePhone', 'postalAddress', 'signature'
				];
				const baseInfo = neededFields.reduce((obj, key) => {
					if (this.baseInfo[key] !== undefined) {
						obj[key] = this.baseInfo[key];
					}
					return obj;
				}, {});
				uni.navigateTo({
					url: `${path}?baseInfo=${JSON.stringify(baseInfo)}`
				});
			},
			isJSON(str) {
				try {
					var obj = JSON.parse(str);
					if (typeof obj == 'object' && obj) {
						return true;
					} else {
						return false;
					}
				} catch (e) {
					return false;
				}
			},
			logout() {
				uni.showModal({
					title: '提示',
					content: '确定退出当前账号吗？',
					success: res => {
						if (res.confirm) {
							const userStore = useUserStore()
							userStore.logout().then(() => {
								uni.closeSocket()
								uni.reLaunch({
									url: '/pages/login/index'
								})
							})
							this.removeAccount()
						}
					}
				})
			},
			removeAccount() {
				let model = uni.getStorageSync('rememberAccount')
				if (!model.remember) {
					model.account = ''
					model.password = ''
					model.remember = false
					uni.setStorageSync('rememberAccount', model)
				}
			},
			scanCode() {
				uni.scanCode({
					success: res => {
						let url = ""
						if (this.isJSON(res.result.trim())) {
							const result = JSON.parse(res.result.trim())
							if (result.t === 'ADP') {
								let config = {
									isPreview: 1,
									moduleId: result.id,
									previewType: result.previewType
								}
								url = '/pages/apply/dynamicModel/index?config=' + this.jnpf.base64.encode(JSON
									.stringify(config))
							}
							if (result.t === 'DFD') {
								url = '/pages/apply/dynamicModel/scanForm?config=' + JSON.stringify(result)
							}
							if (result.t === 'WFP') {
								url = '/pages/workFlow/scanForm/index?config=' + JSON.stringify(result)
							}
							if (result.t === 'report') {
								userInfo = uni.getStorageSync('userInfo') || {}
								const appCode = userInfo.systemCode
								let url_ =
									`${this.report}/preview.html?id=${result.id}&token=${this.token}&appCode=${appCode}&page=1&from=menu`
								url = '/pages/apply/externalLink/index?url=' + encodeURIComponent(url_) +
									'&fullName= ' + result.fullName
							}
							if (result.t === 'portal') {
								url = '/pages/portal/scanPortal/index?id=' + result.id
							}
							if (result.t === 'login') {
								url = '/pages/login/scanLogin?id=' + result.id
							}
						} else {
							url = '/pages/my/scanResult/index?result=' + res.result
						}
						uni.navigateTo({
							url,
							fail: (err) => {
								this.$u.toast("暂无此页面")
							}
						})
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f0f2f6;
	}

	.my-v {
		:deep(.u-cell) {
			height: 112rpx;
			padding: 0;
		}

		.my-group-box {
			.my-group-box-inner {
				background-color: #fff;

				.cell-group {
					/* #ifndef MP-WEIXIN */
					padding: 0 20rpx;
					/* #endif */
					// padding: 0 20rpx;
				}
			}
		}

		.user-box {
			background-color: #fff;
			padding: 0 10rpx 10rpx 20rpx;
			/* #ifdef MP-WEIXIN */
			padding: 0 20rpx 20rpx 20rpx !important;
			/* #endif */
		}

		.logout-cell {
			text-align: center;
			font-size: 32rpx;
			height: 108rpx;
			background-color: #fff;
			color: #D82828;
			line-height: 98rpx;
			font-family: PingFang SC;
		}

		.f-right {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			text-align: center;
		}
	}
</style>