<template>
	<view class="ss">
		<!-- 头 -->
		<!-- <uni-nav-bar fixed="true" statusBar="true" right-icon="scan" title="首页" @clickLeft="back"
			@clickRight="HandlScanCode"></uni-nav-bar> -->

		<!-- <view class="container"> -->
			<!-- <navigation :workOrder="workOrder" ref="navigationRef"></navigation> -->
			<!-- 设备主管 -->
			<!-- <equipment v-if="roleId == 102" ref="equipmentRef"></equipment> -->
			<!-- 运维 -->
			<!-- <Mocha v-if="roleId == 157" ref="mochaRef"></Mocha> -->
			<!-- 模具舟皿 -->
			<!-- <mould v-if="roleId == 155" ref="mouldRef"></mould> -->
			<!-- 备品备件 -->
			<!-- <sparePart v-if="roleId == 150" ref="sparePartRef"></sparePart> -->

			<view class="data-middle">
				<view class="cell">
					<view class="label">
						成品库存总量
					</view>
					<view class="num">
						{{homeData.totalFinishedProducts}}
					</view>
				</view>

				<view class="cell">
					<view class="label">
						物料库存总量
					</view>
					<view class="num">
						{{homeData.totalRawMaterials}}
					</view>
				</view>

				<view class="cell" @click="toDeviceDetail">
					<view class="label">
						设备监测
					</view>
					<view class="num">
						<text style="font-size: 22rpx;">在线：</text>{{homeData.deviceOnLineCount}} 
					</view>
					<view class="num">
						<text style="font-size: 22rpx;">离线：</text><text style="color: #FFC553;">{{ homeData.deviceOffLineCount }}</text>
					</view>
				</view>

				<view class="cell">
					<view class="label">
						年度合同额(万元)
					</view>
					<view class="num">
						{{homeData.yearAmount}}
					</view>
				</view>

				<view class="cell">
					<view class="label">
						年度应收款(万元)
					</view>
					<view class="num">
						{{homeData.receivableAmount}}
					</view>
				</view>

				<view class="cell">
					<view class="label">
						年度应付款(万元)
					</view>
					<view class="num">
						{{homeData.payableAmount}}
					</view>
				</view>
				
			</view>

			<!-- 通知公告 -->
			<view class="notice-bar" v-if="noticeList.length > 0">
				<u-icon name="volume" size="30rpx" color="#ff9900"></u-icon>
				<swiper class="notice-swiper" vertical autoplay circular :interval="3000">
					<swiper-item v-for="(item, index) in noticeList" :key="index">
						<view class="notice-content" @click.stop="toNoticeDetail(item)">
							<text class="notice-text">{{ item.title }}</text>
							<text class="notice-date">{{ item.date }}</text>
						</view>
					</swiper-item>
				</swiper>
			</view>

			<manage ref="manageRef"></manage>
		<!-- </view> -->
	</view>
</template>

<script>
	import navigation from './components/navigation.vue'
	import equipment from './pages/equipment/equipment.vue'
	import Mocha from './pages/Mocha/Mocha.vue'
	import mould from './pages/mould/mould.vue'
	import sparePart from './pages/sparePart/sparePart.vue'
	import ScanCode from '@/components/ScanCode.vue'
	import manage from './pages/manage/manage.vue'

	import {
		getDateNew,
		yuanToWan
	} from '@/utils/utils.js'
	import {
		postJ,
		post,
		get
	} from '@/utils/api'
	import {
		statistics
	} from '@/api/myTicket'
	import {
		getCount,
		getYearAmount,
		getPayableAmount,
		getReceivableAmount,
		getGoodsPage,
		getProduceAmount,
		// getPendingAmount,
		getHotProduct,
		getDeviceCount,
		getNoticeDocumentPage
	}
	from '@/api/home'
	export default {
		components: {
			navigation,
			equipment,
			Mocha,
			mould,
			sparePart,
			ScanCode,
			manage
		},
		onShow() {
			// NOTE: 当 homeNew 作为子组件嵌入 home.vue 时，以下 UniApp 页面级钩子不会被调用。
			// 相关逻辑已迁移到 mounted() 中执行。
		},
		onReady() {
			// NOTE: 当 homeNew 作为子组件嵌入 home.vue 时，UniApp 页面级钩子不会被调用。
			// getHomeData() 已迁移到 mounted() 中执行。
		},
		onLoad() {
		},
		onUnload() {
			this.stopTimer()
			uni.$off('scancodedate')
		},
		onHide() {
			this.stopTimer()
			uni.$off('scancodedate')
		},
		beforeDestroy() {
			this.stopTimer()
		},
		mounted() {
			this.init()
			this.getHomeData()
			setTimeout(() => {
				this.$refs.manageRef?.initCharts()
			}, 300)
			let _this = this
			uni.$off('scancodedate')
			uni.$on('scancodedate', function(data) {
				console.log(data, '-----scancodedate')
				_this.cbScancodedate(data)
			})
		},
		data() {
			return {
				noticeList: [],
				roleId: null,
				timer: null,
				qrContent: null,
				barType: null,
				// 扫码后的设备信息
				equipmentInfo: '',
				qrContent: '',
				barType: '',
				workOrder: {
					maintenanceNum: 0,
					patrolInspection: 0,
					quantityNum: 0,
					repairsNum: 0,
					total: 0
				}, // 工单统计数据
				activeIndex: 0,
				tabList: [{
					name: '热销品排行榜',
					index: 0,
				}, {
					name: '滞销品排行榜',
					index: 1,
				}],
				tableData: [],
				homeData: {
					totalFinishedProducts: '',
					totalRawMaterials: '',
					goodsCount: '',
					yearAmount: '',
					receivableAmount: '',
					payableAmount: '',
					yearProduceAmount: '',
					monthProduceAmount: '',
					pendingAmount: '',
					deviceOnLineCount: '',
					deviceOffLineCount: '',
				},
				hotProductList: [],

			}
		},
		created() {
			uni.getStorage({
				key: 'userInfo',
				success: res => {
					// console.log(res);
					this.roleId = res.data.roleId[0]
				}
			})
			this.getNoticeDocumentList()
		},

		methods: {
			// 停止定时轮询
			stopTimer() {
				console.log('stopTimer')
				this._destroyed = true
				clearTimeout(this.timer)
			},
			// 刷新 manage 子组件数据（供父组件 tab 切换时调用）
			refreshManage() {
				this.$refs.manageRef?.refreshData()
			},
			toDeviceDetail() {
				console.log('toDeviceDetail')
				uni.navigateTo({
					url: '/pages/home/components/DeviceDetail'
				})
			},
			getNoticeDocumentList() {
				getNoticeDocumentPage({
					pageNum: 1,
					size: 5,
					approvalStatus: 2
				}).then(res => {
					console.log('getNoticeDocumentPage', res)
					this.noticeList = res.list.map(item => ({
						...item,
						title: item.title || item.content,
						date: getDateNew(item.createTime)
					}))
					console.log(this.noticeList)
				})
			},
		toNoticeDetail(item) {
			console.log('toNoticeDetail', item)
			uni.navigateTo({
				url: '/pages/home/pages/manage/documentDetail?id=' + item.id
			})
		},
			init() {
				this.getStatistics()
				this.$refs.navigationRef && this.$refs.navigationRef.getCount()
				this.$refs.equipmentRef && this.$refs.equipmentRef.getData()
				this.$refs.mochaRef && this.$refs.mochaRef.getData()
				this.$refs.mouldRef &&
					(this.$refs.mouldRef.getBoatInventoryCountList(),
						this.$refs.mouldRef.getModeInventoryCountList())
				this.$refs.sparePartRef && this.$refs.sparePartRef.getData()
				if (this._destroyed) return
				this.timer = setTimeout(() => {
					console.log('init timeout')
					if (this._destroyed) return
					this.init()
				}, 12000)
			},
			// 获取工单统计数
			getStatistics() {
				statistics().then(res => {
					this.workOrder = res
				})
			},

			// 相机扫码
			HandlScanCode() {
				uni.scanCode({
					success: (res) => {
						this.Scancodedate(res.result)
					}
				})
				//_this.Scancodedate('res')
			},
			// 根据条码请求设备数据
			getData() {
				let par = {
					barType: this.barType,
					qrContent: this.qrContent
				}
				this.equipmentInfo = {}
				return postJ(this.apiUrl + '/scan/getAssetInfo', par)
					.then(res => {
						console.log(res.data)
						this.equipmentInfo = res.data
					})
					.catch(err => {
						console.log(err, 'err-----------------')
						uni.showToast({
							title: '系统错误！',
							icon: 'none',
							duration: 2000
						})
					})
			},
			// 扫码枪扫码
			cbScancodedate(data) {
				this.Scancodedate(data.code)
			},
			async Scancodedate(code) {
				this.qrContent = code.trim()
				// this.qrContent = 'w01000002100001@_@0' //code.trim()
				//this.qrContent = '005/w01000001120041/锤锤专用02-不拆包-批量/规格01//成型/成型工序@_@0'
				this.barType = this.setBarType(this.qrContent)
				await this.getData()

				if (this.equipmentInfo.assetCode) {
					if (this.equipmentInfo.assetType != 1) {
						uni.showToast({
							title: '请扫描生产设备码！',
							icon: 'none',
							duration: 2000
						})

						return
					}
					let par = {
						info: encodeURIComponent(JSON.stringify(this.equipmentInfo)),
						qrContent: this.qrContent
					}
					par = this.URLSearchParams(par)
					console.log('qrwewett')
					uni.navigateTo({
						url: '/pages/equipment_ledger/index?' + par
					})
				}
			},
			// 设置barType
			setBarType(val) {
				let index = val.indexOf('@_@')
				let result = 0
				if (index !== -1) {
					let item = val.substr(index + 3, 1)
					if (item) {
						result = Number(item)
					}
				}
				return result
			},
			// 切换排行版tab
			handleTabChange(item) {
				this.activeIndex = item.index
				this.tableData
				// console.log(item);
			},
			async getHomeData() {
				uni.showLoading({
					title: '加载中'
				})

				const res1 = await getCount()
				const res2 = await getGoodsPage()
				const res3 = await getYearAmount()
				const res4 = await getReceivableAmount()
				const res5 = await getPayableAmount()
				// 年度
				const res6 = await getProduceAmount({
					createTimeStart: getDateNew('year') + '-01',
					createTimeEnd: getDateNew('year') + '-12',
					factoryId: null
				})
				// 本月
				const res7 = await getProduceAmount({
					createTimeStart:  getDateNew('month'),
					createTimeEnd:  getDateNew('month'),
					factoryId: null
				})


				const res9 = await getHotProduct()

				const res10 = await getDeviceCount({
					size: 9999
				})

				let deviceData = res10.list.map((item) => {
					let iotList = [];
					if (item.iotPointDataList) {
					item.iotPointDataList.forEach((element) => {
						let data = item.iotModel.properties.find(
						(iotModel) => iotModel.identifier == element.identifier
						);
						if (data) {
						iotList.push({
							...element,
							dataType: data.dataType
						});
						}
					});
					}

					item['iotList'] = item.iotDashboardPoint.length
					? iotList.filter((iotListItem) =>
						item.iotDashboardPoint.find(
							(Point) =>
							Point.identifier == iotListItem.identifier &&
							Point.checked1
						)
						)
					: iotList.filter((iotListItem, index) => index < 4);
					return item;
				});

				this.homeData.deviceOnLineCount = deviceData.filter((item) => item.iotList.length > 0).length

				this.homeData.deviceOffLineCount = deviceData.filter((item) => item.iotList.length == 0).length

				this.homeData.totalFinishedProducts = res1?.totalFinishedProducts ?? 0
				this.homeData.totalRawMaterials = res1?.totalRawMaterials ?? 0
				this.homeData.goodsCount = res2?.count ?? 0
				this.homeData.yearAmount = yuanToWan(res3 ?? 0)
				this.homeData.receivableAmount = yuanToWan(res4 ?? 0)
				this.homeData.payableAmount = yuanToWan(res5 ?? 0)
				this.homeData.yearProduceAmount = res6?.reduce((pre, cur) => {
					return pre + cur?.formedNum
				}, 0) ?? 0

				this.homeData.monthProduceAmount = res7?.reduce((pre, cur) => {
					return pre + cur?.formedNum
				}, 0) ?? 0
				this.homeData.pendingAmount = res6?.reduce((pre, cur) => {
					return pre + cur?.pendingProductionCount
				}, 0) ?? 0
				this.hotProductList = res9
				this.tableData = this.hotProductList.slice(0, 4)
				uni.hideLoading()

			}

		}
	}
</script>

<style>
	page {
		background-color: #f0f0f0;
	}
</style>

<style lang="scss" scoped>
	// /deep/.uni-page-wrapper{
	// 	background-color: pink;
	// }

	/deep/.uni-table {
		min-width: auto !important;
		border-radius: 0;
	}

	page {
		background-color: #f0f0f0;
	}

	.container {
		background-color: $page-bg;
		padding: 20rpx;

		.data-middle {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.cell {
				display: flex;
				width: 32%;
				padding: 16rpx 0;
				margin-bottom: 16rpx;
				flex-direction: column;
				background-color: #169232;
				justify-content: center;
				align-items: center;
				border-radius: 8rpx;
				color: #fff;
				min-height: 164rpx;
				.num {
					font-size: 30rpx;
				}

				.label {
					font-size: 24rpx;
					margin-bottom: 10rpx;
				}
			}

		}

		/* 通知公告 */
		.notice-bar {
			display: flex;
			align-items: center;
			padding: 18rpx 20rpx;
			background: #fff;
			margin-bottom: 16rpx;

			.notice-swiper {
				flex: 1;
				height: 40rpx;
				margin-left: 12rpx;

				swiper-item {
				height: 40rpx;
				display: flex;
				align-items: center;
				}

				.notice-content {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				}

				.notice-text {
				font-size: 24rpx;
				color: #333;
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				}

				.notice-date {
				font-size: 22rpx;
				color: #999;
				margin-left: 16rpx;
				flex-shrink: 0;
				}
			}
		}

		.data-rank {
			width: 100%;
			padding: 10rpx 20rpx 0 20rpx;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 20rpx 20rpx 0 0rpx;

			.tab-top {
				display: flex;
				margin-bottom: 20rpx;

				.tab-item {
					margin-right: 20rpx;

					.active {
						border-bottom: 2px solid rgb(22, 146, 50);
					}
				}
			}


			.table-title {
				width: 100%;
				display: flex;
				color: #333;
				flex-wrap: nowrap;
				justify-content: space-between;

				.code {
					width: 40%;
					word-break: normal
				}

				.name {
					width: 40%;
					word-break: normal
				}

				.total {
					width: 15%;
					word-break: normal
				}

			}

			.table-content {
				font-size: 28rpx;
				display: flex;
				padding: 10rpx 0;
				width: 100%;
				color: #333;
				flex-wrap: nowrap;
				justify-content: space-between;
				border-bottom: 1px solid #eee;


				.code {
					display: flex;
					width: 40%;

					.index {
						width: 20rpx;
						margin-right: 20rpx;
					}

					.value {
						word-break: break-all;
						flex: 1;
					}
				}

				.name {
					width: 40%;
					white-space: nowarp;
					over-flow: hidden;
					text-overflow: ellipsip;
					word-break: break-all;
				}

				.total {
					text-align: center;
					width: 15%;
					white-space: nowarp;
					over-flow: hidden;
					text-overflow: ellipsip;
					word-break: break-all;
				}
			}

		}

		.data-rank .table-content:last-child {
			border-bottom: none;
		}

		.data-bottom {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.cell {
				display: flex;
				width: 30%;
				padding: 20rpx 0;
				margin-bottom: 20rpx;
				flex-direction: column;
				background-color: #fff;
				justify-content: center;
				align-items: center;
				border-radius: 10rpx;
				color: #000;

				.num {
					font-size: 28rpx;
				}

				.label {

					font-size: 20rpx;
				}
			}
		}

	}
</style>