<template>
	<view class="container">
		<u-navbar placeholder safeAreaInsetTop ></u-navbar>
		<view class="topBar" v-show="!isScan">
			<!-- 顶部名称和退出登录 -->
			<view class="flex justify-between align-center">
				<view class="flex justify-between">
					<view class="flex margin" style="background-color: #fff;border-radius: 12px" @click="goToUserInfo">
						<u-avatar :src="avaSrc" shape="square" size="40"></u-avatar>
					</view>
					<view class="flex flex-direction justify-start margin-top-sm">
						<view class="text-xl text-white">
							Hello,{{user.name || ""}}
						</view>
						<view class="flex margin-top-xs text-white">
							<!-- 欢迎使用智慧LPG管理端 -->
							<view class="padding-right-sm">
								组织机构:{{user.org && user.org.orgName || ""}}
							</view>
							<u-icon name="arrow-down" color="#fff" v-if="user.orgMap && user.orgMap.length"
								@click="openOrgPicker"></u-icon>
						</view>
					</view>
				</view>
				<view class="margin-lr-sm" @click="loginOut">
					<u-icon name="/static/images/home/exit.png" color="#fff" size="20"></u-icon>
				</view>
			</view>
			<!-- 消息区域 -->
			<!-- <view class="massageCss margin-top-lg flex justify-center">
				<view class="flex align-center text-white">
					<view class="">
						<u-icon name="volume" color="#fff" size="20"></u-icon>
					</view>
					<view class="margin-left-sm">
						请注意此处为消息通知处！
					</view>
				</view>
			</view> -->
			<!-- 订单区域 -->
			<view class="orderCss margin-top-lg">
				<view class="flex justify-around align-center margin-lr-xl">
					<view class="flex flex-direction align-center text-white">
						<view class="ordetTextCss">
							{{statisticsForm.jrpsdd || 0}}
						</view>
						<view class="">
							今日配送工单(单)
						</view>
					</view>
					<view class="">
						<u-line direction="col" color="#fff" length="30px"></u-line>
					</view>
					<view class="flex flex-direction align-center text-white">
						<view class="ordetTextCss">
							{{statisticsForm.jrpsqp || 0}}
						</view>
						<view class="">
							今日配送气瓶数(个)
						</view>
					</view>
				</view>
			</view>
			<!-- 轮播消息 -->
			<view class="margin">
				<u-notice-bar :text="text" direction="column" color="#fff" bgColor="#FF9A62" speed="50"
					url="/pages/componentsB/tag/tag"></u-notice-bar>
			</view>
			<!-- 应用卡片 -->
			<view class="usuallyCard margin">
				<view class="">
					<u-grid :border="false" col="4">
						<u-grid-item v-for="(baseListItem,baseListIndex) in appList" :key="baseListIndex">
							<view class="cardItemBody" @click="goToMenuPage(baseListItem)">
								<!-- <view class="cardItemCss"> -->
								<u-icon :customStyle="{padding:0+'rpx'}"
									:name="isYgOrGl==='yg'?ygIconList[baseListIndex]:glyIconList[baseListIndex]"
									:size="40"></u-icon>
								<!-- </view> -->
								<text class="grid-text text-grey" v-if="baseListItem.name!=='帮助下单'">{{baseListItem.name}}</text>
								<text class="grid-text text-grey" v-else>代客下单</text>
							</view>
						</u-grid-item>
					</u-grid>
				</view>
			</view>
			<view class="">
				<view class="margin" v-if="isYgOrGl === 'gl'">
					<dataSummaryHome></dataSummaryHome>
				</view>
				<view class="" v-else>
					<!-- 待配送订单标题 -->
					<view class="margin">
						<TitleSection bgColor="#F2533C">
							<view class="flex w100 justify-between align-center	">
								<view class="text-lg">
									待配送订单
									<!-- <text class="text-gray margin-left-xs">(99)</text> -->
								</view>
								<view class="flex align-center text-grey" @click="goToOrderPage">
									<view class="">
										查看全部订单
									</view>
									<view class="">
										<u-icon name="arrow-right" color="#8799A3" size="20"></u-icon>
									</view>
								</view>
							</view>
						</TitleSection>
					</view>
					<!-- 订单卡片 -->
					<view class="cardCss">
						<view class="margin" v-for="(item,index) in orderList" :key="index">
							<orderCard mode="home" :orderObj="item"></orderCard>
						</view>
						<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"
							v-if="!orderList.length"></u-empty>
						<u-loadmore :status="status" marginTop="20" height="10" marginBottom="10" v-else />
					</view>
				</view>
			</view>
		</view>
		<u-picker :show="orgPickerShow" :columns="orgColumns" keyName="orgName" @cancel="orgPickerShow = false"
			@close="orgPickerShow = false" closeOnClickOverlay @confirm="handleOrgPicker"></u-picker>
		<ScanCode ref="scanCode" @scanCode="getCode" @close="closeScanWindow"></ScanCode>
	</view>
</template>

<script>
	import orderCard from '@/components/orderCard/orderCard.vue';
	import {
		mapState
	} from 'vuex'
	import dataSummaryHome from "@/components/dataSummaryHome/index"
	export default {
		components: {
			orderCard,
			dataSummaryHome
		},
		data() {
			return {
				avaSrc: '',
				text: ['为了您和家人的安全，请不要使用过期石油气钢瓶',
					'为了您和家人的安全，请不要使用过期石油气钢瓶',
				],
				isScan: false,
				appList: [],
				pageParams: {
					currentPage: 1,
					size: 10,
				},
				total: null,
				status: "loadmore",
				orderList: [],
				ygIconList: [
          // '/static/images/appList/ygMenu/menu1.png',
					'/static/images/appList/ygMenu/menu1.png',
					'/static/images/appList/ygMenu/menu2.png',
					'/static/images/appList/ygMenu/menu3.png',
					'/static/images/appList/ygMenu/menu4.png',
					'/static/images/appList/ygMenu/menu5.png',
					'/static/images/appList/ygMenu/menu6.png',
          '/static/images/appList/ygMenu/menu6.png',
					'/static/images/appList/ygMenu/menu7.png',
					'/static/images/appList/ygMenu/menu8.png',
				],
				glyIconList: [
					'/static/images/appList/glyMenu/menu1.png',
					'/static/images/appList/glyMenu/menu2.png',
					'/static/images/appList/glyMenu/menu3.png',
					'/static/images/appList/glyMenu/menu4.png',
					'/static/images/appList/glyMenu/menu5.png',
					'/static/images/appList/glyMenu/menu6.png',
					'/static/images/appList/glyMenu/menu7.png',
					'/static/images/appList/glyMenu/menu8.png',
					'/static/images/appList/glyMenu/menu9.png',
					'/static/images/appList/glyMenu/menu10.png',
					'/static/images/appList/glyMenu/menu11.png',
				],
				isYgOrGl: '',
				roles: "",
				statisticsForm: {
					jrpsdd: '',
					jrpsqp: ''
				},
				orgPickerShow: false,
				orgColumns: []
			}
		},
		computed: {
			...mapState(["user"]),
		},
		async onLoad() {
      console.log('打印是否触发获取这个用户是管理员还是用户',this.$store);
			// console.log("$u显示内容", uni.$u);
			console.log("user==========", this.user);
			await this.getEmployeeInfo(); //员工配送统计信息
			await this.getDetailByAccountOrId(); //查询用户角色信息
			await this.getUserDetail(); //查询组织机构信息
		},
		onPullDownRefresh() {
			this.orderList = [];
			this.getStaffOrderPage();
			setTimeout(() => {
				//结束下拉刷新
				uni.stopPullDownRefresh();
			}, 500);
		},
		onReachBottom() {
			let allTotal = this.pageParams.currentPage * this.pageParams.size
			if (allTotal < this.total) {
				//当前条数小于总条数 则增加请求页数
				this.pageParams.currentPage++;
				this.status = 'loading';
				setTimeout(() => {
					this.getStaffOrderPage()
				}, 500)
			} else {
				this.status = 'nomore'
				// console.log('已加载全部数据')
			}
		},
		methods: {
			judgeYgOrGly() {
				let adminArr = this.$config.admin.split(',');
				let staffArr = this.$config.staff.split(',');
				// console.log("管理员类型", adminArr);
				// console.log("员工类型", staffArr);
				this.roles.forEach(role => {
					if (adminArr.includes(role)) {
						this.isYgOrGl = "gl";
						return;
					}
				});

				this.roles.forEach(role => {
					if (staffArr.includes(role)) {
						this.isYgOrGl = "yg";
						this.getStaffOrderPage();
					}
				});
        uni.setStorageSync('accountType',this.isYgOrGl)
        console.log('打印accountType',this.$store);
        console.log('账号类型', this.isYgOrGl);
			},
			goToUserInfo() {
				uni.navigateTo({
					url: '/pages/userInfo/index'
				})
			},
			async getDetailByAccountOrId() {
				let that = this;
				this.$store.dispatch('GetInfo').then(res => {
					let sjh = that.$store.state.user.userInfo.fSjh || that.$store.state.user.userInfo.fsjh;
					that.$store.dispatch('GetRoles', sjh).then(res => {
						const roles = this.$store.state.user && this.$store.state.user.roles;
						console.log("用户角色", roles);
						that.roles = roles.map(item => item.code);
						// console.log("当前角色code", that.roles);
						that.getMenu();
						that.judgeYgOrGly();
					})
				})
			},
			openOrgPicker() {
				this.orgPickerShow = true;
				this.orgColumns = [...this.orgColumns];
				// console.log("orgColumns", this.orgColumns);
			},
			// 选择组织机构
			handleOrgPicker(e){
				console.log(e);
				let org = e.value[0];
				this.orgPickerShow = false;
				this.$store.dispatch('SetOrg',org).then(res => {
					uni.$u.toast(res);
				})
			},
			async getUserDetail() {
				let that = this;
				that.$store.dispatch('GetOrg').then(res => {
					this.orgColumns = [this.user.orgMap];
				})
			},
			async getMenu() {
				let query = {
					pageBean: {
						page: 1,
						pageSize: 50,
						total: 99
					},
					// querys: [{
					// 	"group": "defaultQueryGroup",
					// 	"operation": "IN",
					// 	"relation": "AND",
					// 	"property": "TYPE_ID_",
					// 	"value": "1773596886171799552"
					// }]
				}
				const result = await this.$api.menuApi.getAppModel(query);
				// console.log("roles", this.roles);
				// console.log("config", this.roles.includes(this.$config.staff));
				if (Array.isArray(this.roles)) {
					// 如果this.roles是数组
					if (this.roles.some(role => this.$config.admin.includes(role))) {
						this.appList = result.rows.filter(item => item.typeName === '管理员应用');
						return;
					} else if (this.roles.some(role => this.$config.staff.includes(role))) {
						this.appList = result.rows.filter(item => item.typeName === '员工端应用');
					}
				} else {
					// 如果this.roles不是数组
					if (this.$config.admin.includes(this.roles)) {
						this.appList = result.rows.filter(item => item.typeName === '管理员应用');
						return;
					} else if (this.$config.staff.includes(this.roles)) {
						this.appList = result.rows.filter(item => item.typeName === '员工端应用');
					}
				}

				console.log("菜单", this.appList);
			},
			goToMenuPage(item) {
				console.log('菜单item', item);
				uni.navigateTo({
					url: item.content
				})
				// if (item.sn === 5) {
				// 	// 组件模式打开
				// 	// this.isScan = true;
				// 	// this.$refs.scanCode.open();
				// 	uni.navigateTo({
				// 		url: "/pages/scan/scanCode"
				// 	})
				// } else {

				// }
			},
			async getCode(code) {
				let query = {
					qptm: code
				}
				const result = await this.$api.gasApi.getDetailByQuery(query);
				let {
					state,
					message
				} = result;
				this.$modal.closeLoading();
				if (!state) {
					uni.$u.toast(message)
					return;
				}
				uni.navigateTo({
					url: '/pages/home/appList/gasInformation/gasInformation?qptm=' + code
				})
			},
			close() {
				this.isScan = false;
				this.$refs.scanCode.close();
			},
			closeScanWindow() {
				this.isScan = false;
			},
			async getStaffOrderPage() {
				let params = {
					zt: '202',
					current: this.pageParams.currentPage,
					size: 10,
				}
				const result = await this.$api.orderApi.getStaffOrderPage(params);
				let {
					code,
					value
				} = result;
				if (code === 200) {
					let {
						current,
						records,
						size,
						total
					} = value;
					let allTotal = this.pageParams.currentPage * this.pageParams.size
					this.total = total;
					const newlist = records;
					if (this.pageParams.currentPage === 1) {
						this.orderList = newlist;
					} else {
						this.orderList.push(...newlist)
					}
					if (this.orderList.length < allTotal) {
						this.status = 'nomore'
					}
				}
				// this.orderList = code === 200 ? value.records : [];
				console.log('打印this.orderList', this.orderList)
				console.log('员工订单', JSON.parse(JSON.stringify(this.orderList)));
			},
			async getEmployeeInfo() {
				this.avaSrc = '/static/images/mine/employeeAvator.png'
				let result = await this.$api.employeeApi.getDeliveryStatisticsInfo();
				let {
					code,
					value
				} = result;
				this.statisticsForm = code === 200 ? {
					...value
				} : {
					...this.statisticsForm
				};
			},
			goToOrderPage() {
				uni.navigateTo({
					url: '/pages/home/appList/orderDelivery/orderDelivery'
				})
			},
			loginOut() {
				this.$modal.confirm('确认退出当前账号？', '提示').then(() => {
					console.log("确认");
					this.$store.dispatch('LogOut').then(() => {
						this.$tab.reLaunch('/pages/login')
					})
				}).catch(() => {
					console.log("取消");
				});
			}
		}
	}
</script>
<style lang="scss">
.container{
  ::v-deep.u-navbar__content{
    background-color: #ff650e !important;
    border-bottom: 1px solid #ff650e !important;
  }
  ::v-deep.u-navbar__content__left{
    display: none!important;
  }
  ::v-deep.u-navbar--fixed{
    position: absolute;
  }
}
</style>

<style lang="scss" scoped>
.container{
  ::v-deep.u-navbar__content{
    background-color: #ff650e !important;
    border-bottom: 1px solid #ff650e !important;
  }
  ::v-deep.u-navbar__content__left{
    display: none!important;
  }
  ::v-deep.u-navbar--fixed{
    position: absolute;
  }
}
	.topBar {
		background: url('@/static/background/bg.png') no-repeat;
		background-size: cover;
		height: 328px;

		.ordetTextCss {
			font-size: 26px;
		}
	}

	.u-notice-bar {
		// margin:0 10px 10px 10px;
		border-radius: 10px;
		// margin: 10px;
	}

	.cardItemBody {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin: 20px 0px;

		.grid-text {
			margin-top: 8px;
		}
	}

	.cardItemCss {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 42px;
		height: 42px;
		background: #FCE6E6;
		border-radius: 15px;
	}

	.cardCss {
		padding-bottom: 10px;
	}
</style>