<template>
	<view class="ss">
		<!-- 头 -->
		<uni-nav-bar fixed="true" statusBar="true" right-icon="scan" title="首页" @clickLeft="back"
			@clickRight="HandlScanCode"></uni-nav-bar>
		<!-- <uni-nav-bar fixed="true" statusBar="true" title="工作台"></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="num">
						{{homeData.totalFinishedProducts}}
					</view>
					<view class="label">
						成品库存总量
					</view>
				</view>

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

				<view class="cell">
					<view class="num">
						{{homeData.goodsCount}}
					</view>
					<view class="label">
						商品列表
					</view>
				</view>

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

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

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

			<view class="data-rank">
				<view class="tab-top">
					<view class="tab-item" v-for="(item,index) in tabList" :key="index">
						<view :class="{active: activeIndex == item.index}" @click="handleTabChange(item)">
							{{item.name}}
						</view>
					</view>
				</view>


				<!-- <uni-table class="table" ref="table" emptyText="暂无更多数据">
					<uni-tr class="table-title">
						<uni-th align="center" width="100">产品编码</uni-th>
						<uni-th align="center">名称</uni-th>
						<uni-th align="center" width="100">销量</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in tableData" :key="index">
						<uni-td>{{index+1}}.{{item.productCode}}</uni-td>
						<uni-td>{{item.productName}}</uni-td>
						<uni-td align="center">{{item.totalSaleCount}}</uni-td>
					</uni-tr>
				</uni-table> -->

				<view class="table-title" style="text-align: center;">
					<view class="code">产品编码</view>
					<view class="name">名称</view>
					<view class="total">销量</view>
				</view>
				<view class="table-content" v-for="(item,index) in tableData">
					<view class="code">
						<view class="index">{{index+1}}.</view>
						<view class="value">{{item.productCode}}</view>

					</view>
					<view class="name">{{item.productName}}</view>
					<view class="total">{{item.totalSaleCount}}</view>
				</view>



			</view>





			<view class="data-bottom">
				<view class="cell">
					<view class="num">
						{{this.homeData.yearProduceAmount}}
					</view>
					<view class="label">
						年度生产总量
					</view>
				</view>

				<view class="cell">
					<view class="num">
						{{this.homeData.monthProduceAmount}}
					</view>
					<view class="label">
						月生产总量
					</view>
				</view>

				<view class="cell">
					<view class="num">
						{{homeData.pendingAmount}}
					</view>
					<view class="label">
						待生产总量
					</view>
				</view>

			</view>



		</view>





		<!-- <ScanCode ref="ScanCode" :model="'uni'"></ScanCode> -->
	</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 {
		getDateNew
	} 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
	}
	from '@/api/home'
	export default {
		components: {
			navigation,
			equipment,
			Mocha,
			mould,
			sparePart,
			ScanCode
		},
		onShow() {
			this.init()
			let _this = this
			uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
			uni.$on('scancodedate', function(data) {
				console.log(data, '-----scancodedate')
				_this.cbScancodedate(data)
			})
			this.getStatistics()
			// this.Scancodedate()
		},
		onLoad() {
			this.getHomeData()
			this.getStatistics()
		},
		onUnload() {
			uni.$off('scancodedate')
		},
		onHide() {
			uni.$off('scancodedate')
		},
		data() {
			return {
				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: ''
				},
				hotProductList: [],

			}
		},
		created() {
			uni.getStorage({
				key: 'userInfo',
				success: res => {
					console.log(res);
					this.roleId = res.data.roleId[0]
				}
			})
		},
		methods: {
			init() {
				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()
				this.timer = setTimeout(() => {
					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: '加载中'
				})

				let params = {
					startDate: '',
					endDate: '',
					factoriesId: 0
				}
				let nowYear = getDateNew('year') + '-01-01'
				let nowMonth = getDateNew('month') + '-01'
				let now = getDateNew()
				console.log(now, nowYear, nowMonth);
				params.endDate = now





				const res1 = await getCount()
				const res2 = await getGoodsPage()
				const res3 = await getYearAmount()
				const res4 = await getReceivableAmount()
				const res5 = await getPayableAmount()
				const res6 = await getProduceAmount({
					...params,
					startDate: nowYear
				})
				const res7 = await getProduceAmount({
					...params,
					startDate: nowMonth
				})


				const res9 = await getHotProduct()


				this.homeData.totalFinishedProducts = res1?.totalFinishedProducts ?? 0
				this.homeData.totalRawMaterials = res1?.totalRawMaterials ?? 0
				this.homeData.goodsCount = res2?.count ?? 0
				this.homeData.yearAmount = (res3 / 10000).toFixed(2)
				this.homeData.receivableAmount = res4 ?? 0
				this.homeData.payableAmount = 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: 30%;
				padding: 20rpx 0;
				margin-bottom: 20rpx;
				flex-direction: column;
				background-color: rgb(22, 146, 50);
				justify-content: center;
				align-items: center;
				border-radius: 10rpx;
				color: #fff;

				.num {
					font-size: 40rpx;
				}

				.label {
					font-size: 20rpx;
				}
			}

		}

		.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: 40rpx;
				}

				.label {

					font-size: 20rpx;
				}
			}
		}

	}
</style>