<template>
	<page-meta :page-style="`overflow:${show ? 'visible' : 'hidden'};height:100%;font-family:${fontFamily};`"></page-meta>
	<!-- #ifdef APP-PLUS -->
	<view class="status_bar">
		<view class="top_view"></view>
	</view>
	<!-- #endif -->
	<CustomModal ref="cusModal" />
	<view class="navBarWrapper">
		<view class="navBar" v-if="token">
			<image src="/static/menu.png" mode="aspectFit" style="width: 16px; height: 13px" @click="toggleLeftDrawerVisible"></image>
			<image src="/static/logo.png" alt="" style="width: 86px; height: 31px" @click="redirectToTarget('/pages/home/index')" />
			<image src="/static/notification.png" mode="aspectFit" alt="" style="width: 17px; height: 19px; margin-right: 6px" @click="toggleRightDrawerVisible" />
			<uni-drawer ref="showLeft" mode="left" :width="300" class="leftDrawer" @change="handleLeftDrawerChange">
				<scroll-view class="scrollView" scroll-y="true">
					<view class="menuItem userName" @click="toPersonalInfoPage">
						<image style="width: 18px; height: 18px" src="/static/avatar.png" mode="aspectFit"></image>
						<text>{{ userInfo?.name }}</text>
					</view>
					<view class="menuItem balance" v-if="isIb">
						<image style="width: 18px; height: 18px" src="/static/wallet.png" mode="aspectFit"></image>
						<view>
							<text class="value">{{ ibFund?.amount }}</text>
							USD
						</view>
					</view>
					<uni-collapse accordion @change="change">
						<view :class="['menuItem', isActived('/pages/home/index') ? 'active' : '']" @tap="goToTarget('/pages/home/index')">
							<image
								style="width: 18px; height: 18px"
								:src="`/static/${isActived('/pages/home/index') ? 'homeActived' : 'home'}.svg`"
								mode="aspectFit"
							></image>
							<text class="value">{{ $t('menu.home') }}</text>
						</view>

						<view v-for="(menu,index) in menuListData"  :key="menu.saleRouteKey" class="selectorWrapper" >
							<view class="menuItem selector" @click="toggleMenuOptionsVisible(index)">
								<image class="menuIcon" :src="`/static/${menu.saleRouteKey}.svg`" mode="aspectFit"></image>
								<text>{{menu.name}}</text>
							</view>
              <view ref="languageSelector" :class="['optionsWrapper', { visible: menuListData[index].optionsVisible }]">
                <view v-for="menu2 in menu.children" :key="menu2.saleRouteKey">
                  <view :class="['option' , isActived((menuLinks[menu.saleRouteKey])[menu2.saleRouteKey]) ? 'active' : '']" @tap="goToTarget((menuLinks[menu.saleRouteKey])[menu2.saleRouteKey])">
                    <text >{{menu2.name}}</text>
                  </view>
                </view>
              </view>
              <view class="menuRight" v-show="menuListData[index].optionsVisible">
                <image class="menuIcon" :src="`/static/packUp.svg`" mode="aspectFit"></image>
              </view>
              <view class="menuRight" v-show="!menuListData[index].optionsVisible">
                <image class="menuIcon" :src="`/static/unfold.svg`" mode="aspectFit"></image>
              </view>
            </view>

						<view style="border-top: 1px solid #ececec; margin-top: 8px">
							<MenuLanguageSelector />
						</view>
						<view class="menuItem" style="min-height: 24px" @click="handleLogout">
							<image style="width: 18px; height: 18px" src="/static/logout.svg" mode="aspectFit"></image>
							<text class="value">{{ $t('menu.logOut') }}</text>
						</view>
					</uni-collapse>
				</scroll-view>
			</uni-drawer>
			<uni-drawer ref="showRight" mode="right" :width="300" class="rightDrawer" @change="handleRightDrawerChange">
				<view class="rightContent">
					<scroll-view v-if="noticeList.length" :style="{ height: '100%' }" scroll-y="true">
						<view
							v-for="notice in noticeList"
							:key="notice.id"
							class="noticeItem"
							@click="
								(e) => {
									showDialog(notice);
								}
							"
						>
							<view class="noticeSubject">{{ notice.subject }}</view>
							<view class="noticeSummary">{{ notice.summary }}</view>
						</view>
					</scroll-view>
					<view v-else style="margin-top: 20px">{{ $t('notice.empty') }}</view>
				</view>
			</uni-drawer>
		</view>
		<view class="navBar" v-else>
			<image src="/static/logo.png" alt="" style="width: 70px; height: 26px; margin-left: 4px" />
			<LanguageSelector />
		</view>
		<!-- 普通弹窗 -->
		<uni-popup ref="alertDialog" :isMaskClick="false">
			<view class="detailModal">
				<uni-icons type="closeempty" size="17" class="closeIcon" @click="closeDialog"></uni-icons>
				<view class="detailContent">
					<view class="notice-content" v-html="currentNotice.content"></view>
				</view>
			</view>
		</uni-popup>
		<view></view>
	</view>
</template>

<script>
import { useUserStore } from '@/stores/user.ts';
import LanguageSelector from '@/pages/components/languageSelector/index.vue';
import MenuLanguageSelector from '@/pages/components/menuLanguageSelector/index.vue';
import { getToken } from '@/utils/const.ts';
import { queryMenuList, getNotice, setNoticeReadStatus } from '@/services/home/home';
import { logout } from '@/services/user/loginAndRegister';
import { UserLanguage } from '@/utils/const';

//获取屏幕边界到安全区域距离
export default {
	data() {
		return {
			fontFamily: 'SourceHanSans',
			type: 'center',
			msgType: 'success',
			messageText: '这是一条成功提示',
			value: '',
			show: true,
			showDl: true,
			userInfo: {},
			isIb: false,
			ibFund: {},
			currentPage: '',
			menuListData: [],
			menuLinks: {
        customer: {
          sell:'/pages/customer/sell/index',
          ib:'/pages/customer/ib/index',
          customer:'/pages/customer/customer/index',
          mt:'/pages/customer/mt/index'
        },
        apply: {
          saleFundOut:"/pages/capital/salesWithdraw/index"
        },
        audit: {
          goldIn:"/pages/audit/goldIn/index",
          goldOut:"/pages/audit/goldOut/index",
          salesGoldOut:"/pages/audit/salesGoldOut/index",
          integral:"/pages/audit/integral/index",
        },
        report: {
          report14:"/pages/report/report14/index",
          report16:"/pages/report/report16/index",
          report17:"/pages/report/report17/index",
          report20:"/pages/report/report20/index",
          report22:"/pages/report/report22/index",
          report21:"/pages/report/report21/index",
          report28:"/pages/report/report28/index",
          report27:"/pages/report/report27/index",
          report26:"/pages/report/report26/index",
          report24:"/pages/report/report24/index",
          report70:"/pages/report/report70/index",
          report81:"/pages/report/report81/index"
        },
        applyRecord: {
          mt:"/pages/applyRecord/mt/index",
          leverage:"/pages/applyRecord/leverage/index",
          userChange:"/pages/applyRecord/userChange/index",
          goldIn:"/pages/applyRecord/goldIn/index",
          goldOut:"/pages/applyRecord/goldOut/index",
          transfer:"/pages/applyRecord/transfer/index",
          fundOut:"/pages/applyRecord/fundOut/index",
          fundTransfer:"/pages/applyRecord/fundTransfer/index",
        }
			},
			noticeList: [],
			currentNotice: {},
			windowScrollY: 0,
			contentSize: 0
		};
	},
	emits: ["navLeft", "@navRight"],
	computed: {
		paddingTop: () => {
			const { safeAreaInsets } = uni.getSystemInfoSync();
			return safeAreaInsets?.top + 'px';
		},
		token: () => {
			return getToken();
		}
	},
	methods: {
    toggleMenuOptionsVisible(index) {
      this.menuListData[index].optionsVisible = !this.menuListData[index].optionsVisible;
    },
		initData() {
			const userStore = useUserStore();
			this.userInfo = Object.assign(this.userInfo, userStore.userInfo);
			this.ibFund = Object.assign(this.ibFund, userStore.ibFund);
			this.isIb = Number(userStore.userInfo.user_type) === 1;
		},
		isActived(path) {
			return path.includes(this.currentPage);
		},
		showDialog(notice = {}) {
			if (notice.content.length) {
				notice.content = `<div style="zoom:${this.contentSize};">`+notice.content+'</div>'
			}
			this.currentNotice = notice;
			this.show = false;
			this.toggleRightDrawerVisible();
			if (notice.status === '0') {
				setNoticeReadStatus({ id: notice.id });
			}
			this.showDl = true;
			this.$refs.alertDialog.open();
		},
		closeDialog() {
			this.show = true;
			this.toggleRightDrawerVisible();
			this.showDl = false;
			this.$refs.alertDialog.close();
		},
		goToTarget(target) {
			const pages = getCurrentPages();
			if (!target.endsWith(pages[pages.length - 1].route)) {
				uni.navigateTo({
					url: target
				});
				this.show = true;
				this.$refs.showLeft.close();
			}
		},
		toPersonalInfoPage() {
			this.$refs.showLeft.close();
			uni.navigateTo({ url: '/pages/user/index' });
		},
		redirectToTarget(target) {
			uni.redirectTo({
				url: target
			});
		},
		async handleLogout() {
			this.$cusModal.showModal({
				type: 'confirm',
				contentText: this.$t('modal.logoutContent'),
				closeAfterConfirm: true,
				onConfirm: async () => {
					try {
						const res = await logout();
						if (res && res.code === 0) {
							const userStore = useUserStore();
							userStore.clear();
							uni.removeStorageSync('access_token');
							uni.redirectTo({
								url: '/pages/login/index'
							});
						}
					} catch (e) {
						console.log('e===>', e);
					}
				}
			});
		},
		async getMenuListData() {
			const res = await queryMenuList();
			if (res && res.code === 0) {
        const menuList = [];
				for (var i = 0; i < res.data.length; i++) {
					const { saleRouteKey } = res.data[i]
          res.data[i].optionsVisible = false

          if (saleRouteKey == 'customer') {
            res.data[i].rank = 2
            if (res.data[i].children.length>0){
              let childrenMenuList = []
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !='')
                  childrenMenuList.push( res.data[i].children[j])
              }
              res.data[i].children = childrenMenuList
            }
            menuList.push(res.data[i])
					} else if (saleRouteKey == 'apply') {
						res.data[i].rank = 3
            if (res.data[i].children.length>0){
              let childrenMenuList = []
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !='')
                  childrenMenuList.push( res.data[i].children[j])
              }
              res.data[i].children = childrenMenuList
            }
            menuList.push(res.data[i])
					} else if (saleRouteKey == 'audit') {
						res.data[i].rank = 4
            if (res.data[i].children.length>0){
              let childrenMenuList = []
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !='')
                  childrenMenuList.push( res.data[i].children[j])
              }
              res.data[i].children = childrenMenuList
            }
            menuList.push(res.data[i])
          }else if (saleRouteKey == 'report') {
						res.data[i].rank = 5
            if (res.data[i].children.length>0){
              let childrenMenuList = []
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !='')
                  childrenMenuList.push( res.data[i].children[j])
              }
              res.data[i].children = childrenMenuList
            }
            menuList.push(res.data[i])
          }else if (saleRouteKey == 'applyRecord') {
						res.data[i].rank = 6
            if (res.data[i].children.length>0){
              let childrenMenuList = []
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !='')
                  childrenMenuList.push( res.data[i].children[j])
              }
              res.data[i].children = childrenMenuList
            }
            menuList.push(res.data[i])
          }
				}
        menuList.sort((a, b) => a.rank - b.rank)
				this.menuListData = menuList;
			}
		},
		async getNoticeList() {
			const res = await getNotice();
			if (res && res.code === 0) {
				this.noticeList = res.data;
			}
		},
		recordWindowScrollY() {
			// #ifdef H5
			this.windowScrollY = window.scrollY;
			// #endif
		},
		windowScrollByRecord() {
			// #ifdef H5
			setTimeout(() => {
				window.scroll(0, this.windowScrollY);
			}, 0);
			// #endif
		},
		handleLeftDrawerChange(e) {
			if (!e) {
				this.show = true;
				this.windowScrollByRecord();
			}
			this.$emit('navLeft', e || this.showDl)
		},
		toggleLeftDrawerVisible() {
			if (this.$refs.showLeft.visibleSync) {
				this.show = true;
				this.windowScrollByRecord();
				this.$refs.showLeft.close();
			} else {
				this.initData();
				this.show = false;
				this.recordWindowScrollY();
				this.$refs.showLeft.open();
				//如果接口出错没请求到数据，则打开侧边栏的时候再请求一次
				if (!this.menuListData.length) {
					this.getMenuListData();
				}
			}
		},
		handleRightDrawerChange(e) {
			if (!e) {
				this.show = true;
				this.windowScrollByRecord();
			}
			this.$emit('navRight', e || this.showDl)
		},
		toggleRightDrawerVisible() {
			if (this.$refs.showRight.visibleSync) {
				this.show = true;
				this.windowScrollByRecord();
				this.$refs.showRight.close();
			} else {
				this.getNoticeList();
				this.show = false;
				this.recordWindowScrollY();
				this.$refs.showRight.open();
			}
		},
		open() {
			// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
			this.$refs.popup.open('top');
		},
		toggle(type) {
			this.type = type;
			// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
			this.$refs.popup.open(type);
		},
		change(e) {
			console.log('popup_change', e);
		}
	},
	created() {
		const pages = getCurrentPages();
		this.currentPage = pages[pages.length - 1].route;
		const locale = uni.getLocale();
		if (['zh-CN', 'zh-TW'].includes(locale)) {
			this.fontFamily = 'SourceHanSans';
		} else {
			this.fontFamily = 'Arial';
		}
	},
	async mounted() {
		if (getToken()) {
			this.getMenuListData();
		}
		this.$cusModal.register(this.$refs.cusModal);
		this.contentSize =  uni.upx2px(666) / 800
	},
	components: {
		LanguageSelector,
		MenuLanguageSelector
	}
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>