<template>
	<view class="container">
		<view class="status-bar"></view>
		<t-emp />

		<uni-row class="dataStatics">
			<uni-col :span="24">
				<u-subsection :list="list" mode="button" :current="current" @change="handleChangeTab" />
				<uni-card class="statCard proStatics" margin="0" padding="8px 0" :border="true" v-show="current === 0">
					<uni-section title="生产统计" type="circle" titleFontSize="18px" titleColor="#1e5799">
						<uni-row>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="today.repNum" bold separator="," use-easing />
								<text class="statLabel">当日报工</text>
							</uni-col>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="month.repNum" bold separator="," use-easing />
								<text class="statLabel">当月报工</text>
							</uni-col>
						</uni-row>
					</uni-section>
				</uni-card>

				<uni-card class="statCard quaStatics" margin="0" padding="8px 0" :border="true" v-show="current === 1">
					<uni-section title="质量统计" type="circle" titleFontSize="18px" titleColor="#1e5799">
						<template v-slot:right class="card-actions-item">
							<text class="card-actions-item-text" @click="toDetail('quality')">查看明细</text>
							<uni-icons type="right"></uni-icons>
						</template>
						<uni-row>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="today.failedNum" bold separator="," use-easing />
								<text class="statLabel">当日不合格</text>
							</uni-col>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="month.failedNum" bold separator="," use-easing />
								<text class="statLabel">当月不合格</text>
							</uni-col>
						</uni-row>
					</uni-section>
				</uni-card>

				<uni-card class="statCard salStatics" margin="0" padding="8px 0" :border="true" v-show="current === 2">
					<uni-section title="工资统计" type="circle" titleFontSize="18px" titleColor="#1e5799">
						<template v-slot:right class="card-actions-item">
							<text class="card-actions-item-text" @click="toDetail('salary')">查看明细</text>
							<uni-icons type="right"></uni-icons>
						</template>
						<uni-row>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="today.salary" bold separator="," use-easing />
								<text class="statLabel">当日工资</text>
							</uni-col>
							<uni-col :span="12" class="staticNumber">
								<u-count-to :endVal="month.salary" bold separator="," use-easing />
								<text class="statLabel">当月工资</text>
							</uni-col>
						</uni-row>
					</uni-section>
				</uni-card>
			</uni-col>
		</uni-row>

		<uni-row class="jobInfo" :gutter="20">
			<uni-col :span="24">
				<uni-card class="eqpInfo" margin="0" padding="8px 0" :border="true">
					<uni-section title="所在设备" type="line" titleFontSize="20px" titleColor="#1e5799">
						<view class="eqpName">{{ eqpName }}</view>
						<view class="card-actions">
							<view class="card-actions-item" @click="eqpCheckIn">
								<uni-icons type="icon-qiandao" size="14" color="#9d9d9d" custom-prefix="iconfont"></uni-icons>
								<text class="card-actions-item-text">签到</text>
							</view>
							<view class="card-actions-item" @click="eqpCheckOut">
								<uni-icons type="icon-qiantui" size="14" color="#9d9d9d" custom-prefix="iconfont"></uni-icons>
								<text class="card-actions-item-text">签退</text>
							</view>
						</view>
					</uni-section>
				</uni-card>
			</uni-col>
			<uni-col :span="24">
				<uni-card class="staInfo" margin="0" padding="8px 0" :border="true">
					<uni-section title="所在工位" type="line" titleFontSize="20px" titleColor="#1e5799">
						<view class="staName">{{ stationTitle }}</view>
						<view class="card-actions">
							<view class="card-actions-item" @click="staCheckIn">
								<uni-icons type="icon-qiandao" size="14" color="#9d9d9d" custom-prefix="iconfont"></uni-icons>
								<text class="card-actions-item-text">签到</text>
							</view>
							<view class="card-actions-item" @click="staCheckOut">
								<uni-icons type="icon-qiantui" size="14" color="#9d9d9d" custom-prefix="iconfont"></uni-icons>
								<text class="card-actions-item-text">签退</text>
							</view>
						</view>
					</uni-section>
				</uni-card>
			</uni-col>
		</uni-row>
	</view>
</template>

<script>
import { listEmpEqpHistory } from '@/api/basic/empEqpHistory.js';
import { listEmployee } from '@/api/mes/jobIn.js';
import { getInfo } from '@/api/login.js';
import { getDepartment } from '@/api/basic/department.js';
import { listReport } from '@/api/mes/pwoDraw.js';
import { listStationEmpHistory } from '@/api/basic/empStaHistory.js';
import { getBeijingTime } from '@/utils/judge.ts';

export default {
	data() {
		return {
			userId: null,
			empCode: null,
			empName: this.$store.state.employee.empName,
			eqpId: null,
			eqpCode: null,
			eqpName: '/',
			deptId: null,
			deptName: this.$store.state.employee.deptName,
			stationTitle: '/',
			today: {
				repNum: 0,
				failedNum: 0,
				salary: 0,
				reportInfo: [],
				jobs: []
			},
			month: {
				repNum: 0,
				failedNum: 0,
				salary: 0,
				reportInfo: [],
				jobs: []
			},
			timeRange: [],
			list: ['生产统计', '质量统计', '工资统计'],
			current: 0
		};
	},
	methods: {
		eqpCheckIn() {
			this.$tab.navigateTo(`/pages/basic/empEqpStart?userId=${this.userId}&empCode=${this.empCode}&empName=${this.empName}`);
		},
		eqpCheckOut() {
			this.$tab.navigateTo(`/pages/basic/empEqpEnd?userId=${this.userId}&empCode=${this.empCode}&empName=${this.empName}`);
		},
		staCheckIn() {
			this.$tab.navigateTo(`/pages/basic/empStaStart?userId=${this.userId}&empCode=${this.empCode}&empName=${this.empName}`);
		},
		staCheckOut() {
			this.$tab.navigateTo(`/pages/basic/empStaEnd?userId=${this.userId}&empCode=${this.empCode}&empName=${this.empName}`);
		},
		getEqpAndSta() {
			// 查询人员上机历史
			listEmpEqpHistory({
				empName: this.empName,
				empCode: this.empCode
			}).then((res) => {
				this.eqpCode = null;
				this.eqpName = '/';

				if (res.rows.length > 0) {
					const item = res.rows.find((item) => !item.endTime);
					if (item) {
						this.eqpCode = item.equipmentCode;
						this.eqpName = item.equipmentTitle;
					}
				}
			});

			// 查询工位签到历史
			listStationEmpHistory({
				empName: this.empName
			}).then((res) => {
				const filteredData = res.rows.filter((item) => item.endTime == null);
				console.log(filteredData);
				if (filteredData.length > 0) {
					this.stationTitle = filteredData[0].stationTitle;
				} else {
					this.stationTitle = '/';
				}
			});
		},
		async getUserInfo() {
			// 根据账号获取员工姓名和账号ID
			await getInfo()
				.then((res) => {
					this.empName = res.user.nickName;
					this.userId = res.user.userId;
				})
				.catch(() => {
					uni.showToast({
						title: '当前账号无对应人员资料',
						icon: 'none'
					});
				});
			// 根据昵称获取对应员工编号
			await listEmployee({
				empName: this.empName
			})
				.then((res) => {
					this.empCode = res.rows[0].empCode;
					this.deptId = res.rows[0].deptId;

					// 根据部门id查询部门名称
					getDepartment(this.deptId)
						.then((res) => {
							this.deptName = res.data.departmentTitle;
						})
						.catch(() => {
							uni.showToast({
								title: '未查询到所属部门',
								icon: 'none'
							});
						});
				})
				.catch(() => {
					uni.showToast({
						title: '当前账号无对应人员资料',
						icon: 'none'
					});
				});
		},
		getTodayRange() {
			const now = new Date();
			// 获取日期
			const year = String(now.getFullYear());
			const month = String(now.getMonth() + 1).padStart(2, '0');
			const date = String(now.getDate()).padStart(2, '0');
			const nextDate = String(now.getDate() + 1).padStart(2, '0');
			this.timeRange = [];
			this.timeRange.push(`${year}-${month}-${date} 00:00:00`);
			this.timeRange.push(`${year}-${month}-${nextDate} 00:00:00`);
		},
		getMonthRange() {
			const now = new Date();
			// 获取日期
			const year = String(now.getFullYear());
			const month = String(now.getMonth() + 1).padStart(2, '0');
			const nextMonth = String(now.getMonth() + 2).padStart(2, '0');
			this.timeRange = [];
			this.timeRange.push(`${year}-${month}-01 00:00:00`);
			this.timeRange.push(`${year}-${nextMonth}-01 00:00:00`);
		},
		async getTodayInfo() {
			this.getTodayRange();
			await listReport({
				'timeRange[0]': this.timeRange[0],
				'timeRange[1]': this.timeRange[1],
				createByName: this.empName
			})
				.then((res) => {
					if (res.rows.length !== 0) {
						for (var i in res.rows) {
							this.today.reportInfo.push({
								repNum: res.rows[i].reportNumber,
								type: res.rows[i].type,
								pwoJobCode: res.rows[i].pwoJobCode,
								ptNoTar: res.rows[i].ptNoTar,
								failedNum: 0
								// 数据未添加完毕，子页面还需要：工序、工序数量、计价单价
							});
						}
					}
				})
				.catch(() => {
					uni.showToast({
						title: '获取日报工信息失败',
						icon: 'none'
					});
				});
			for (const item of this.today.reportInfo) {
				// 当日报工数
				this.today.repNum += item.repNum;
				// 当日质量问题
				if (item.type !== '合格品') {
					this.today.failedNum++;
				}
			}
			this.today.reportInfo.failedNum = this.today.failedNum;
		},
		async getMonthInfo() {
			this.getMonthRange();
			await listReport({
				createByName: this.empName,
				'timeRange[0]': this.timeRange[0],
				'timeRange[1]': this.timeRange[1]
			})
				.then((res) => {
					if (res.rows.length > 0) {
						for (var i in res.rows) {
							this.month.reportInfo.push({
								repNum: res.rows[i].reportNumber,
								type: res.rows[i].type,
								pwoJobCode: res.rows[i].pwoJobCode,
								ptNoTar: res.rows[i].ptNoTar,
								failedNum: 0
								// 数据未添加完毕，子页面还需要：工序、工序数量、计价单价
							});
						}
					}
				})
				.catch(() => {
					uni.showToast({
						title: '获取月报工信息失败',
						icon: 'none'
					});
				});
			for (const item of this.month.reportInfo) {
				// 当月报工数
				this.month.repNum += item.repNum;
				// 当月质量问题
				if (item.type !== '合格品') {
					this.month.failedNum++;
				}
				// 月工资
			}
			this.month.reportInfo.failedNum = this.month.failedNum;
		},
		// 计算薪资
		calSal() {},
		// 跳转到明细页面
		toDetail(type) {
			this.$modal.msg('功能开发中...');
			return;

			const params = {
				today: {
					repNum: this.today.repNum,
					failedNum: this.today.failedNum,
					salary: this.today.salary
				},
				month: {
					repNum: this.month.repNum,
					failedNum: this.month.failedNum,
					salary: this.month.salary
				}
			};

			uni.navigateTo({
				url: `/pages/detail/${type}Detail?data=${encodeURIComponent(JSON.stringify(params))}`
			});
		},
		handleChangeTab(tab) {
			this.current = tab;
		}
	},
	async onShow() {
		// await this.getUserInfo();
		await this.getEqpAndSta();
		await this.getTodayInfo();
		await this.getMonthInfo();
	}
};
</script>

<style scoped lang="scss">
.status-bar {
	height: var(--status-bar-height);
	width: 100%;
}

.container {
	width: 100%;
	padding: 6px 12px;
	box-sizing: border-box;
	// display: flex;
	flex-direction: column;
	overflow: hidden;
	/* #ifdef H5 */
	height: calc(100vh - 44px);
	/* #endif */
	/* #ifndef H5 */
	height: 100vh;
	/* #endif */
}

.jobInfo {
	margin: 0 !important;
	
	.uni-col {
		padding: 0 !important;
	}

	.uni-col + .uni-col {
		margin-top: 15px;
	}

	.eqpInfo,
	.staInfo {
		border-radius: 12px !important;

		.eqpName,
		.staName {
			font-size: 22px !important;
			text-align: center;
			margin: 15px 0;
			font-weight: 500;
			color: #444;
			min-height: 30px;
			line-height: 1.4;
		}

		.card-actions {
			border-top: 1px #d9d9d9 solid;
			display: flex;
			justify-content: space-around;
			gap: 10px;
			padding-top: 10px;

			.card-actions-item {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				flex: 1;
			}
			.card-actions-item + .card-actions-item {
				border-left: 2px solid #d9d9d9;
			}
			.card-actions-item-text {
				font-size: 14px;
				color: #666;
				margin-left: 5px;
			}
		}
	}
}

.dataStatics {
	background: transparent !important;
	box-shadow: none !important;
	margin: 10px 0 15px !important;

	.statCard {
		border-radius: 0 0 12px 12px !important;
		background: #fff !important;
		height: 100%;
		display: flex;
		flex-direction: column;
		margin: 0 5px;

		.staticNumber {
			display: flex;
			flex-direction: column;
			align-items: center;

			.u-count-num {
				font-size: 40px !important;
				margin: 10px 0;
			}
		}

		.detailBtn {
			background: #409eff;
			color: white;
			border: none;
			height: 45px;
			font-size: 18px;
			border-radius: 8px;
			margin-top: 15px;
			line-height: 45px;
			transition: background 0.3s;

			&:active {
				background: #3a8ee6;
			}
		}
	}
}

.u-subsection--button {
	padding-left: 0 !important;
	padding-right: 0 !important;
}

/* 全局uni-section标题加粗 */
::v-deep .uni-section__content-title {
	font-weight: bold !important;
}

::v-deep .uni-section-header__slot-right {
	display: flex;
}
</style>
