<template>
	<view class="index_v">
		<u-sticky>
			<view class="head-tabs u-flex">
				<view class="head-tabs-item" @click="openPage('/pages/workFlow/flowTodo/index','approve')">
					<text class="icon-ym icon-ym-flowTodo-app u-m-r-4 icon-style" />
					<text class="u-font-24 head-tabs-name">审批中心</text>
					<u-badge type="error" :count="count" :absolute="true" :offset="offset" />
				</view>
				<view class="head-tabs-item" @click="openPage('/pages/workFlow/entrustAgent/index','entrust')">
					<text class="icon-ym icon-ym-flowDone-app u-m-r-4 icon-style" />
					<text class="u-font-24 head-tabs-name">委托代理</text>
				</view>
				<view class="head-tabs-item" @click="openPage('/pages/workFlow/schedule/index','schedule')">
					<text class="icon-ym icon-ym-flowDone-app u-m-r-4 icon-style" />
					<text class="u-font-24 head-tabs-name">日程</text>
				</view>
				<view class="head-tabs-item" @click="openPage('/pages/workFlow/document/index','document')">
					<text class="icon-ym icon-ym-flowCopy-app u-m-r-4 icon-style" />
					<text class="u-font-24 head-tabs-name">文档</text>
				</view>
			</view>
		</u-sticky>
		<CommonPane :flowList="homeData.favoritesFlowList || []" :menuList="homeData.favoritesMenuList || []"
			type="collect" @launch="launch" v-if="homeData.favoritesEnable" @openPage="openPage" @addApp="addApp"
			:showAdd="true" :flowEnabled="homeData.flowEnabled" />

		<CommonPane title="最近使用" :flowList="homeData.latelyUseFlowList || []" type="use"
			:menuList="homeData.latelyUseMenuList || []" @launch="launch" v-if="homeData.latelyUseEnable"
			@openPage="openPage" :flowEnabled="homeData.flowEnabled" />

		<CommonPane title="最近常用" :flowList="homeData.commonUseFlowList || []" type="common"
			:menuList="homeData.commonUseMenuList || []" @launch="launch" v-if="homeData.commonUseEnable"
			@openPage="openPage" :flowEnabled="homeData.flowEnabled" />
		<PasswordPopup @submit="dataFormSubmit" :passwordShow="passwordShow" :formData="baseForm"></PasswordPopup>
	</view>
</template>
<script>
	import {
		getFlowTodoCount
	} from "@/api/workFlow/flowEngine";
	import {
		getHomeData
	} from "@/api/index/index";
	import {
		useUserStore
	} from '@/store/modules/user'
	import {
		useChatStore
	} from '@/store/modules/chat'
	import {
		updatePassword,
		updatePasswordMessage
	} from '@/api/common.js'
	import chat from '@/libs/chat'
	import CommonPane from '@/components/CommonPane'
	import PasswordPopup from './components/PasswordPopup'
	import {
		useLocale
	} from '@/locale/useLocale';
	const chatStore = useChatStore()
	export default {
		components: {
			CommonPane,
			PasswordPopup
		},
		data() {
			return {
				homeData: [],
				count: 0,
				offset: [20, -10],
				menuList: [],
				passwordShow: false,
				baseForm: {
					passwordStrengthLimit: 0,
					passwordLengthMin: false,
					passwordLengthMinNumber: 0,
					containsNumbers: false,
					includeLowercaseLetters: false,
					includeUppercaseLetters: false,
					containsCharacters: false,
					mandatoryModificationOfInitialPassword: 0,
				},
				userInfo: {}
			};
		},
		onLoad() {
			const chatStore = useChatStore()
			// if (!chatStore.getSocket) chat && chat.initSocket()
			const userStore = useUserStore()
			userStore.getCurrentUser().then(() => {
				this.getSystemName()
			}).catch(() => {
				setTimeout(() => {
					userStore.resetToken()
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}, 500)
				}, 1000)
			})
			const {
				changeLocale
			} = useLocale();
			changeLocale(uni.getLocale())
		},
		onShow(e) {
			this.init()
		},
		computed: {
			baseURL() {
				return this.define.baseURL;
			},
			token() {
				return uni.getStorageSync('token')
			},
			report() {
				return this.define.report;
			},
			pcURL() {
				return this.define.pcURL;
			}
		},
		methods: {
			init() {
				this.getHomeData()
				this.getFlowCount()
				this.getSystemConfig()
			},
			// 获取系统配置
			getSystemConfig() {
				updatePasswordMessage();
				this.userInfo = uni.getStorageSync('userInfo') || {}
				const config = uni.getStorageSync('sysConfigInfo') || {};
				this.$nextTick(() => {
					this.baseForm.passwordStrengthLimit = config.passwordStrengthLimit
					this.baseForm.passwordLengthMin = config.passwordLengthMin
					this.baseForm.passwordLengthMinNumber = config.passwordLengthMinNumber
					this.baseForm.containsNumbers = config.containsNumbers
					this.baseForm.includeLowercaseLetters = config.includeLowercaseLetters
					this.baseForm.containsCharacters = config.containsCharacters
					this.baseForm.mandatoryModificationOfInitialPassword = config
						.mandatoryModificationOfInitialPassword
					if (this.userInfo.changePasswordDate == null && config
						.mandatoryModificationOfInitialPassword == 1)
						this.passwordShow = true;
				})
			},
			dataFormSubmit(query) {
				updatePassword(query).then((res) => {
					const userStore = useUserStore()
					userStore.logout().then(() => {
						uni.reLaunch({
							url: "/pages/login/index",
						});
					});
				})
			},
			//获取并设置应用名称
			getSystemName() {
				const userInfo = uni.getStorageSync("userInfo");
				this.menuList = uni.getStorageSync("menuList");
				uni.setNavigationBarTitle({
					title: userInfo.systemName
				})
			},
			launch(item) {
				if (item.tabType == 'flow') return this.JumpFlow(item)
				if (item.tabType == 'menu') return this.JumpApply(item)
			},
			JumpApply(item) {
				if (item.type == 1) {
					getChildList(item.id).then(res => {
						this.listChild = res.data || []
						this.handleProperty(this.listChild)
						this.$nextTick(() => {
							uni.navigateTo({
								url: "/pages/apply/catalog/index?config=" +
									this.jnpf.base64.encode(JSON.stringify(this.listChild[0])),
								fail: (err) => {
									this.$u.toast("暂无此页面");
								},
							});
						})
					})
					return;
				}
				let url = ''
				// 2-页面 11-回传表单
				if (item.type == 2 || item.type == 11) {
					if (!item.pageAddress) {
						this.$u.toast("暂无此页面");
						return;
					}
					url = item.pageAddress + "?menuId=" + item.id + "&fullName=" + item.fullName
				}
				//  3-在线表单 9-流程
				if (item.type == 3 || item.type == 9) {
					if (!item.moduleId) {
						this.$u.toast("暂无此页面");
						return;
					}
					url = "/pages/apply/dynamicModel/index?config=" + this.jnpf.base64.encode(JSON.stringify(item))
				}
				// 外链
				if (item.type == 7) {
					if (!item.pageAddress) {
						this.$u.toast("暂无此页面");
						return;
					}
					url = "/pages/apply/externalLink/index?url=" + encodeURIComponent(item.pageAddress) + "&fullName=" +
						item.fullName + "&type=" + item.type
				}
				// 报表(原)
				if (item.type == 5) {
					if (!item.moduleId) {
						this.$u.toast("暂无此页面");
						return;
					}
					userInfo = uni.getStorageSync('userInfo') || {}
					const appCode = userInfo.systemCode
					const urlPre = encodeURIComponent(
						`${this.report}/preview.html?id=${item.moduleId}&token=${this.token}&appCode=${appCode}&page=1&from=menu`
					)
					url = "/pages/apply/externalLink/index?url=" + urlPre + "&fullName=" + item.fullName + "&type=" +
						item.type
				}
				// 报表
				if (item.type == 10) {
					if (!item.moduleId) {
						this.$u.toast("暂无此页面");
						return;
					}
					const urlPre = encodeURIComponent(
						`${this.pcURL}/reportPreview?id=${item.moduleId}&token=${this.token}&from=app`
					);
					url = "/pages/apply/externalLink/index?url=" + urlPre + "&fullName=" + item.fullName + "&type=" +
						item.type
				}
				// 门户
				if (item.type == 8) {
					if (!item.moduleId) {
						this.$u.toast("暂无此页面");
						return;
					}
					url = "/pages/portal/scanPortal/index?id=" + item.moduleId + "&portalType=1&fullName=" +
						item.fullName
				}
				if (!url) return;
				uni.navigateTo({
					url,
					fail: () => {
						this.$u.toast("暂无此页面");
					},
				});
			},
			handleProperty(list) {
				const loop = (par) => {
					par.map(o => {
						if (o?.propertyJson) {
							let propertyJson = JSON.parse(o.propertyJson);
							this.$set(o, "iconBackground", propertyJson.iconBackgroundColor || "");
							this.$set(o, "moduleId", propertyJson.moduleId || "");
						}
						if (o?.children && o?.children?.length) loop(o.children)
					})
				}
				loop(list)
			},
			JumpFlow(item) {
				const config = {
					id: "",
					flowId: item.id,
					opType: "-1",
					isFlow: 1
				};
				uni.navigateTo({
					url: "/pages/workFlow/flowBefore/index?config=" +
						this.jnpf.base64.encode(JSON.stringify(config))
				});
			},
			//获取审批中心待办条数
			getFlowCount() {
				getFlowTodoCount().then((res) => {
					this.count = res.data.flowTodo || 0;
				})
			},
			getHomeData() {
				getHomeData().then((res) => {
					for (let i = 0; i < res.data.length; i++) {
						const e = res.data[i];
						this.homeData[`${e.code}Enable`] = e.enable;
						this.homeData['flowEnabled'] = e.flowEnabled
						this.handleProperty(e.appList)
						if (['commonUse', 'favorites', 'latelyUse'].includes(e.code)) {
							this.homeData[`${e.code}MenuList`] = e.appList || [];
							this.homeData[`${e.code}FlowList`] = e.flowList || [];
						}
					}
				}).catch(() => {});
			},
			//更多按钮
			openPage(path, type) {
				if (type === 'approve') {
					let workFlowList = this.menuList.filter(o => o.enCode === 'workFlow')
					if (!workFlowList[0]?.children?.length) return this.$u.toast('暂无权限')
				}
				if (!path) return;
				uni.navigateTo({
					url: path,
				});
			},
			//添加按钮
			addApp(path) {
				if (!path) return;
				uni.navigateTo({
					url: path,
				});
			},
		}
	}
</script>

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

	.index_v {
		.head-tabs {
			background-color: #fff;
			width: 100%;
			height: 120rpx;
			justify-content: space-between;
			padding: 0 20rpx;

			.head-tabs-item {
				display: flex;
				justify-content: center;
				font-size: 28rpx;
				color: #303133;
				flex-shrink: 0;
				position: relative;
				align-items: center;
				height: 120rpx;

				.icon-style {
					font-size: 42rpx;
					color: #666666;
				}

				.head-tabs-name {
					color: #303133;
					font-family: PingFang SC;
					margin-left: 6rpx;
				}
			}
		}
	}
</style>