<template>
	<view>
		<uni-section>
			<view class="example">
				<uni-forms ref="form" :modelValue="formData" labelWidth="80px" :rules="rules"
					style="margin-bottom: 5px;">
					<uni-forms-item label="生产组织" required name="OrgFrameGuid">
						<uni-data-select v-model="formData.OrgFrameGuid" :localdata="workshopList"
							@change="workshopchange">
						</uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="工作中心" required name="WorkCenterGuid">
						<uni-data-select v-model="formData.WorkCenterGuid" :localdata="workcenterList"
							@change="workcenterchange">
						</uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="存放地点" required name="WarehouseGuid">
						<uni-data-select v-model="formData.WarehouseGuid" :localdata="warehouseList"
							@change="warehousechange">
						</uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="保管员" required name="StoreMan">
						<uni-easyinput v-model="formData.StoreMan" placeholder="请输入姓名" />
					</uni-forms-item>
					<uni-forms-item label="日期" required name="BillDate">
						<uni-datetime-picker type="date" :start="start" :end="end" v-model="formData.BillDate" />
					</uni-forms-item>
					<uv-pick-color ref="pickerColor" :color="color" @confirm="confirm"></uv-pick-color>
					<button @click="openColor" :style="{ 'background-color': color }">选择颜色</button>
				</uni-forms>
				<button type="primary" @click="goNext()">下一步</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import {
		getToken,
		setToken,
		removeToken,
		setServerUrl,
		setUserGuid,
		getUserGuid
	} from '@/utils/auth'
	import {
		workshopList,
		workcenterList,
		warehouseList,
		saveSystemSetting,
		getPeriodInfo
	} from '@/api/workshop.js'
	export default {
		data() {
			return {
				// color: { r: 60, g: 156, b: 255, a: 1 },
				formData: {
					StoreMan: "",
					OrgFrameGuid: "",
					LegalUnitGuid: "",
					OrgFrameName: "",
					WarehouseGuid: "",
					WarehouseName: "",
					AddressCode: "",
					WorkCenterGuid: "",
					WorkCenterName: "",
					BillDate: ""
				},
				start: '',
				end: '',
				defaultValue: '',
				rules: {
					OrgFrameGuid: {
						rules: [{
							required: true,
							errorMessage: '请选择生产组织',
						}]
					},
					WorkCenterGuid: {
						rules: [{
							required: true,
							errorMessage: '请选择工作中心',
						}]
					},
					WarehouseGuid: {
						rules: [{
							required: true,
							errorMessage: '请选择存放地点',
						}]
					},
					StoreMan: {
						rules: [{
							required: true,
							errorMessage: '请填写保管员',
						}]
					},
					BillDate: {
						rules: [{
							required: true,
							errorMessage: '请选择日期',
						}]
					}
				},
				workshopList: [],
				workcenterList: [],
				warehouseList: [],
				IsXnbh: '',
				color: ''
			};
		},
		mounted() {
			this.getLegalUnitName()
			this.formData.StoreMan = uni.getStorageSync('UserName')
			warehouseList().then(res => {
				if (res.Code == "0000") {
					for (let i in res.Result.T01) {
						let o = {
							value: res.Result.T01[i]['Guid'],
							text: res.Result.T01[i]['Name_CN'],
							AddressCode: res.Result.T01[i]['AddressCode'],
							IsAutoWarehouse: res.Result.T01[i]['IsAutoWarehouse'],
							IsXnbh: res.Result.T01[i]['IsXnbh'],
						};

						this.warehouseList.push(o);
					}
					//查询是否缓存存放地点
					let WarehouseGuid = uni.getStorageSync('WarehouseGuid')
					if (WarehouseGuid) {
						this.formData.WarehouseGuid = WarehouseGuid
						this.warehousechange(WarehouseGuid)
					}


				} else {
					uni.showToast({
						title: res.Msg,
						icon: 'none'
					})

				}
			})
			let color = uni.getStorageSync('colorcofig')
			if (color) {
				this.color = color
			}




		},

		methods: {
			openColor() {
				this.$refs.pickerColor.open();
			},
			confirm(e) {
				console.log('confirm', e)
				this.color = e.hex
			},
			getCurrentDate() {
				// 创建一个新的Date对象，即当前时间
				const currentDate = new Date();

				// 获取年、月、日
				const year = currentDate.getFullYear();
				const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
				const day = currentDate.getDate();

				// 这里可以根据需要进行处理，比如格式化成指定的字符串形式
				const formattedDate = `${year}-${month}-${day}`;

				// 返回当前日期
				return formattedDate;
			},
			compareDate(currentDate,start,end) {
			    
			    // 将日期字符串转换为Date对象
			    const currentDate1 = new Date(currentDate);
			    const start1 = new Date(start);
			    const end1 = new Date(end);
			    
			    // 使用比较运算符进行日期比较
			    if (end1 < currentDate1) {
					// this.formData.BillDate = start
					this.formData.BillDate = currentDate
			    } else if (currentDate1 < start1) {
			      this.formData.BillDate = start
			    } else {
			       this.formData.BillDate = currentDate
			    }
			  },
			getLegalUnitName() {
				let data = {
					userGuid: getUserGuid()
				}
				workshopList(data).then(res => {
					if (res.Code == "0000") {
						for (let i in res.Result.T01) {
							let o = {
								value: res.Result.T01[i]['UnitGuid'],
								text: res.Result.T01[i]['UnitName_CN'],
								LegalUnitGuid: res.Result.T01[i]['LegalUnitGuid']
							};

							this.workshopList.push(o);
						}
						//查询是否缓存生产组织
						let UnitGuid = uni.getStorageSync('OrgFrameGuid')
						if (UnitGuid) {
							this.formData.OrgFrameGuid = UnitGuid
							this.workshopchange(UnitGuid)
						}
						// if (res.success) {
						// this.workshopList = res.Result.Result.T01	
					} else {}
				})
			},
			workshopchange(e) {
				const res = this.workshopList.find((ev) => {
					return ev.value === e;
				});
				// console.log(res)
				this.formData.LegalUnitGuid = res['LegalUnitGuid']
				this.formData.OrgFrameName = res['text']
				// console.log(this.formData)
				this.workcenterList = []
				let data = {
					unitGuid: e
				}
				workcenterList(data).then(res => {
					if (res.Code == "0000") {
						for (let i in res.Result.T01) {
							let o = {
								value: res.Result.T01[i]['Guid'],
								text: res.Result.T01[i]['Name_CN']
							};

							this.workcenterList.push(o);
						}
						//查询是否缓存工作中心
						let WorkCenterGuid = uni.getStorageSync('WorkCenterGuid')
						if (WorkCenterGuid) {
							this.formData.WorkCenterGuid = WorkCenterGuid
							this.workcenterchange(WorkCenterGuid)
						}
					} else {}
				})
				let data1 = {
					LegalUnitGuid: this.formData.LegalUnitGuid
				}
				console.log('adafdasfas', data1)
				//获取账期
				getPeriodInfo(data1).then(res => {
					if (res.Code == "0000") {
						console.log(res.Result)
						this.start = res.Result[0].StartDate.replace(/\s.*$/, '')
						var date = new Date(res.Result[0].EndDate);
						date.setMonth(date.getMonth() + 1);
						
						var year = date.getFullYear();
						var month = date.getMonth() + 1;
						var day = date.getDate();
						
						var result = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
						console.log('result',result);
						const end = res.Result[0].EndDate.replace(/\s.*$/, '')
						this.end = result
						console.log('endddddd', this.end)
						console.log(this.getCurrentDate())
						// this.formData.BillDate = this.end
						this.compareDate(this.getCurrentDate(),this.start,end);
					} else {}
				})
			},
			workcenterchange(e) {
				console.log('w', this.workcenterList)
				console.log(e)
				const res = this.workcenterList.find((ev) => {
					return ev.value === e;
				});
				console.log(res)
				this.formData.WorkCenterName = res['text']
				// console.log(this.formData)

			},
			warehousechange(e) {
				const res = this.warehouseList.find((ev) => {
					return ev.value === e;
				});
				this.formData.WarehouseName = res['text']
				this.formData.AddressCode = res['AddressCode']
				this.IsAutoWarehouse = res['IsAutoWarehouse']
				this.IsXnbh = res['IsXnbh']
				console.log(this.IsAutoWarehouse)

			},
			//保存系统参数
			goNext() {
				console.log(this.formData);
				this.$refs.form.validate().then(res => {
					console.log(this.formData);
					saveSystemSetting(this.formData).then(res => {
						if (res.Code == "0000") {
							//存入缓存
							uni.setStorageSync('OrgFrameGuid', this.formData.OrgFrameGuid);
							uni.setStorageSync('WorkCenterGuid', this.formData.WorkCenterGuid);
							uni.setStorageSync('WarehouseGuid', this.formData.WarehouseGuid);
							uni.setStorageSync('AddressCode', this.formData.AddressCode);
							uni.setStorageSync('colorcofig', this.color);
							uni.navigateTo({
								//传IsAutoWarehouse值到下一页
								url: `/pages/workshop/list?IsAutoWarehouse=${this.IsAutoWarehouse}&IsXnbh=${this.IsXnbh}`,
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
						} else {
							uni.showToast({
								title: res.Msg,
								icon: 'none'
							})

						}
					})


				}).catch(err => {
					console.log(err);
				})


			},
		}
	};
</script>
<style>
	.example {
		padding: 15px;
		padding-top: 0px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>