<template>
	<view class="todo-page">
		<view class="card">
			<view class="background"></view>
			<!-- <uni-card margin="0" :is-shadow="true"> -->
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules" ref="wForm" errorType="border-bottom" class="demo-ruleForm">
				<u-form-item label="班次：" prop="Nav_Class.NAME" @click="handleChangeMonitor('Nav_Class')" borderBottom>
					<u--input disabledColor="#fff" v-model="(model.Nav_Class||{}).NAME" disabled placeholder="请选择班次" suffixIcon="arrow-down" suffixIconStyle="font-size:12px" fontSize="14px"
						customStyle="margin:0px;display:flex;padding:3px 0px" border="none" inputAlign="right">
					</u--input>
				</u-form-item>
				<u-form-item label="上班时间" prop="CHECKDATETIME" borderBottom >
					<u--input disabled disabledColor="#fff" v-model="model.START_TIME"  border="none" inputAlign="right" fontSize="14px"></u--input>
					
				</u-form-item>
				<u-form-item label="下班时间" prop="ENDTIME" borderBottom >
					<u--input disabled disabledColor="#fff" v-model="model.END_TIME"  border="none" inputAlign="right" fontSize="14px"></u--input>
					
				</u-form-item>
				<u-form-item label="主持人：" prop="Nav_User.NAME" @click="handleChangeMonitor('Nav_User')" borderBottom>
					<u--input disabledColor="#fff" v-model="(model.Nav_User||{}).NAME" disabled placeholder="请选择主持人" suffixIcon="arrow-right" suffixIconStyle="font-size:12px" fontSize="14px"
						customStyle="margin:0px;display:flex;padding:3px 0px" border="none" inputAlign="right">
					</u--input>
				</u-form-item>
				<u-form-item required label="当班工作内容：" prop="JOB_CONTENT" borderBottom>
				</u-form-item>
				<u--textarea required v-model="model.JOB_CONTENT" placeholder="请输入当班工作内容" border="surround"></u--textarea>
				<u-form-item required label="注意事项及防护措施：" prop="PROTECT_MEASURE" borderBottom>
				</u-form-item>
				<u--textarea required v-model="model.PROTECT_MEASURE" placeholder="请输入注意事项及防护措施" border="surround"></u--textarea>
				<u-form-item label="其他内容：" prop="OTHER_CONTENT" borderBottom>
				</u-form-item>
				<u--textarea v-model="model.OTHER_CONTENT" placeholder="请输入其他内容" border="surround"></u--textarea>
				<view class="upload-title">附件：</view>
				<full-upload v-model="model.Nav_Files" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>
				<u-form-item label="参会人员" @click="handleShowUserSelector">
					<u-icon name="man-add" size="24" color="#3d9cff" slot="right"></u-icon>
				</u-form-item>
				<view class="tag-view" v-if="model.Nav_Users">
					<view  v-for="(i, k) in model.Nav_Users.filter(i => !i.IS_DELETED)">
						<u-tag plain class="tag"  :key="k" :inverted="true" :text="i.Nav_User.NAME" type="primary" />
					</view>
					
				</view>
			</u--form>
			<!-- </uni-card> -->
		</view>
		<!-- <u-sticky offset-top="20">
			<view class="sub-form" style="margin:20px 16px 20px 16px;padding-bottom: 100px;">
				<view class="sub-form-wrap">
					<view class="sub-form-btns">
						<view class="sub-form-btn" @click="handleAdd">
							<u-icon class="icon" name="plus-circle" color="#3c9cff" size="21"></u-icon>
							<u--text type="primary" text="新增人员"></u--text>
						</view>
					</view>
					<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom" ref="sForm">
						<u-collapse :border="false" accordion>
							<uni-card margin="0" spacing="0" :is-shadow="false" v-for="(item, index) in model.Nav_Users.filter(i => !i.IS_DELETED)">
								<u-form-item :label="(index+1)+'. '+item['Nav_User'].NAME+' - '+item['Nav_User'].CODE" prop="Nav_User.NAME" @click="handleChangeUser(item)">
									<view slot="right" class="row-action">
										<view class="action" @click.stop>
											<u-icon @click="handleDelRowBefore(index, item)" class="icon" name="trash" color="#ff4d4f" size="21"></u-icon>
										</view>
									</view>
								</u-form-item>
							</uni-card>
						</u-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky> -->
		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cancelDel" showCancelButton title="确认删除？"></u-modal>
		<query-selector :show="showPopup" :lists="userLists" :defaultValue="currentOperateUser.NAME" @close="handleClosePopup" @search="handleSearchUser" @select="handleSelectedUser" />
		<query-selector :show="showPopupMonitor" :total="curTotalMonitor" :lists="monitorLists" :defaultValue="currentOperateMonitor.NAME" @close="handleClosePopupMonitor" @search="handleSearchMonitor"
			@select="handleSelectedMonitor" />
			<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector" @select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
			</people-selector>
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<!-- <view class="bottom-button">
			<button type="primary" @click="submit('Save')" style="width: 45%;float: left;">保存</button>
			<button type="primary" @click="submit('SaveAndNotify')" style="width: 45%;">提交</button>
		</view> -->

		<view style="padding: 10px 16px;display: flex;flex-direction: row;" class="bottom-button">
			<button  @click="submit('Save')" :plain="true"
				style="margin-right: 5px;background-color: #fff;color: #3d4b70;width: 50%;height: 40px;display: flex;align-items: center;justify-content: center;font-size: 14px;">保存</button>
			<button  @click="submit('SaveAndNotify')"
				style="margin-left: 5px;background-color: #3d4b70;color: #fff;width: 50%;height: 40px;display: flex;align-items: center;justify-content: center;font-size: 14px;">提交</button>
		</view>
		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" v-model='dateTimePickerInfo.defaultDateTime' @confirm="handleCheckDate" @close="dateTimePickerInfo.showCheckDate = false"
			@cancel="dateTimePickerInfo.showCheckDate = false" :mode="dateTimePickerInfo.mode"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'
	import {
		getRequest,
		getTeamUsers
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		getUserLists,
		getClassLists,
	} from '../../../../services/safe';

	import config from '../../../../config/common'

	export default {
		data() {
			return {
				userLists: [],
				listPropUpload: ['PRE_SHIFT_MEETING_RECORD_ID'],
				listPropValUpload: [],
				curTotalMonitor: 0,
				monitorLists: [],
				currentOperateMonitor: {},
				showPopupMonitor: false,
				model: {
					JOB_CONTENT: "",
					PROTECT_MEASURE: "",
					Nav_Users: [],
					ORG_ID: "",
					Nav_Files: [],
					Nav_User: {
						NAME: ''
					},
					USER_ID: null,
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'JOB_CONTENT': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'PROTECT_MEASURE': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				currentOperateUser: {},
				showPopup: false,
				tableKey: '0',
				TaskID: '',
				isLoadOK: false,
				showDelModalIndex: undefined,
				peopleSelectOption: {
					showSelector: false,
					value: null,
					defaultChecked: []
				},
				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					value: '',
					name: '',
					mode: ''
				},
				isAdd: 0,
				START_TIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
				END_TIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
				ORG_ID: uni.getStorageSync('orgId')
			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.tableKey = option.tableKey ? option.tableKey : '0';
			if (option.isAdd != 1) {
				this.loadData();
			} else {
				this.isAdd = 1;
			
				this.model.ID = guid();
				this.loadTeamUsers();
			}
		},
		methods: {
			handleSelectorPeople(e) {
				const {
					index: key
				} = this.peopleSelectOption
				this.model.Nav_Users= e.map(i => {
					return {
						USER_ID: i.USER_ID,
						IS_DELETED: i.IS_DELETED,
						PRE_SHIFT_MEETING_RECORD_ID: this.model.ID,
						NAME: i.NAME,
						Nav_User: {
							NAME: i.NAME,
							ID: i.USER_ID
						}
					}
				})
			},
			handleShowUserSelector() {
				this.peopleSelectOption = {
					showSelector: true,
					value: this.model.Nav_Users,
					defaultChecked: this.model.Nav_Users?.map(i => {
						return {
							...i,
							NAME: i.Nav_User.NAME,
							USER_ID: i.USER_ID,
						}
					})
				}
			},
			handleAdd() {
				this.model.Nav_Users.unshift({
					PRE_SHIFT_MEETING_RECORD_ID: this.model.ID,
					ID: guid(),
					ORG_ID: this.ORG_ID,
					Nav_User: {
						NAME: "",
						CODE: ""
					},
					USER_ID: "",
					IS_DELETED: false,
					DEAL_STATUS: 0,
				})
			},
			showCheckDate(dataIndex) {
				// let date = new Date()
				// this.dateTimePickerInfo.showCheckDate = true
				this.dateTimePickerInfo = {
					showCheckDate: true,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					dataIndex: dataIndex,
					mode: dataIndex == 3 ? 'date' : 'datetime'
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {

				if (this.dateTimePickerInfo.dataIndex == 1) {
					this.model.START_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				} else if (this.dateTimePickerInfo.dataIndex == 2) {
					this.model.END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
				this.dateTimePickerInfo.showCheckDate = false

			},
			handleDelRowBefore(index, item) {
				if (item.USER_ID == "") {
					this.model.Nav_Users.splice(index, 1)
				} else {
					this.showDelModalIndex = index
				}
			},
			cancelDel() {
				this.showDelModalIndex = undefined
			},
			confirmDel() {
				this.model.Nav_Users.filter(i => !i.IS_DELETED)[this.showDelModalIndex].IS_DELETED = true;
				//this.model.Nav_Users.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			handleChangeMonitor(user) {
				this.currentOperateMonitor = user
				this.showPopupMonitor = true
				this.handleSearchMonitor('init')
			},
			handleSearchMonitor(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)

				extendRule(json, 'ENABLE_STATUS', 1, '0')
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}
				if (
					this.currentOperateMonitor == 'Nav_User'
				) {
					extendInclude(json, "Nav_Department")
					if (orgId === '8b3c41aa-51b1-7ce9-1879-248a038c1b5c') {
						extendRule(json, 'DEPARTMENT_ID', 1, uni.getStorageSync('appInfo')?.User?.DEPARTMENT_ID)
					}
					getUserLists(json).then(res => {
						if (res.IsSuccessful) {
							this.monitorLists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
									code: i.CODE
								}
							})
							this.curTotalMonitor = res.TotalCount
						}
					})
				} else if (this.currentOperateMonitor == 'Nav_Class') {
					extendInclude(json, 'Nav_ClassDetail');
					getClassLists(json).then(res => {
						if (res.IsSuccessful) {
							this.monitorLists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
									code: i.CODE
								}
							})
							this.curTotalMonitor = res.TotalCount
						}
					})
				}

			},
			handleSelectedMonitor(val) {
				this.showPopupMonitor = false

				if (this.currentOperateMonitor == 'Nav_User') {
					this.model.Nav_User = val
					this.model.USER_ID = val.ID
				} else if (this.currentOperateMonitor == 'Nav_Class') {
					this.model.Nav_Class = val
					this.model.CLASS_ID = val.ID
					let DATE_TIME = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd')
					let start = uni.$u.timeFormat(val.Nav_ClassDetail[0].STARTTIME, 'hh:MM:ss')
					let end = uni.$u.timeFormat(val.Nav_ClassDetail[0].ENDTIME, 'hh:MM:ss')
					this.model.START_TIME = DATE_TIME + ' ' + start
					this.model.END_TIME = DATE_TIME + ' ' + end
					this.checkTime()

				}
				this.currentOperateMonitor = val

			},
			formatDate(timestamp) {
				const date = new Date(timestamp);
				// 补0：确保个位数是 01/02 而非 1/2
				const pad = n => n.toString().padStart(2, '0');
				const year = date.getFullYear();
				const month = pad(date.getMonth() + 1); // 月份从0开始，需+1
				const day = pad(date.getDate());
				const hour = pad(date.getHours());
				const minute = pad(date.getMinutes());
				const second = pad(date.getSeconds());
				return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
			},
			checkTime() {
				const timestamp1 = new Date(this.model.START_TIME).getTime();
				const timestamp2 = new Date(this.model.END_TIME).getTime();

				// 判断：后面的时间 是否 小于 前面的时间
				const isTime2LtTime1 = timestamp2 < timestamp1;
				const endDate = new Date(this.model.END_TIME);
				if (isTime2LtTime1) {

					endDate.setDate(endDate.getDate() + 1); // 关键API：日期+1，时分秒不变
					this.model.END_TIME = this.formatDate(endDate.getTime());
				}
			},
			handleClosePopupMonitor() {
				this.showPopupMonitor = false
			},
			loadTeamUsers() {
				let personid = uni.getStorageSync('appInfo').User.PERSON_ID;
				const json = initFilter(this.ORG_ID, "", "")
				extendRule(json, 'CHARGE_PERSON_ID', 1, personid);
				extendInclude(json, 'Nav_TeamPersons.Nav_Person.Nav_User');
				getTeamUsers(json).then(res => {
					if (res && res.length > 0) {
						let teamPersons = res[0].Nav_TeamPersons;
						let person = [];
						let rowNo = 1;
						if (teamPersons && teamPersons.length > 0) {
							teamPersons.forEach(item => {
								let objPerson = {
									Nav_User: {},
									NAME: '',
									CODE: '',
								}
								objPerson.Nav_User.NAME = item.Nav_Person.NAME;
								objPerson.Nav_User.CODE = item.Nav_Person.CODE;
								objPerson.ID = guid();
								objPerson.PRE_SHIFT_MEETING_RECORD_ID = this.model.ID;
								objPerson.USER_ID = item.Nav_Person?.Nav_User?.ID;
								objPerson.DEAL_STATUS = 0;
								objPerson.ORG_ID = this.ORG_ID;
								person.push(objPerson);
								rowNo++;
							})
						}
						this.model.Nav_Users = person;
					}
				})
			},
			loadData() {
				const json = initFilter(this.ORG_ID, "", "")
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendInclude(json, "Nav_Class")
				extendInclude(json, "Nav_Department")
				extendInclude(json, "Nav_Team")
				extendInclude(json, "Nav_User")
				extendInclude(json, "Nav_Files.Nav_ImgFile")
				extendInclude(json, "Nav_Users.Nav_User.Nav_Person")
				// TODO: id 未获取
				extendRule(json, 'ID', 1, this.model.ID)
				getRequest(json, "/FO/PreShiftMeetingRecord/Get").then(res => {
					this.model = res
					this.checkTime()
				})
			},
			handleSearchUser(val) {
				const json = initFilter(this.ORG_ID, "", "NAME")
				extendInclude(json, "Nav_Person.Nav_Post")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				// extendRule(json, 'DEPARTMENT_ID', 1, uni.getStorageSync('appInfo').User.DEPARTMENT_ID)
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				getUserLists(json).then(res => {
					if (res.IsSuccessful) {
						this.userLists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
					}
				})
			},
			handleSelectedUser(val) {
				this.showPopup = false
				this.lists = []
				this.currentOperateUser.USER_ID = val.ID;
				this.currentOperateUser.Nav_User.NAME = val.NAME;
				this.currentOperateUser.Nav_User.CODE = val.CODE;
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				if (user.Nav_User.NAME == '') {
					this.currentOperateUser = user;
					this.showPopup = true;
					this.handleSearchUser('init');
				}

			},
			onConfirmPicker(e) {
				const {
					name,
					dataIndex,
					formIndex
				} = this.comPickerInfo
				if (formIndex === "sForm1") {
					const result = this.model.Nav_Users.map((obj, index) => {
						return obj
					})
					this.model.Nav_Users = result
				} else {

				}
				this.comPickerInfo.showSheet = false
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					dataIndex: undefined,
					formIndex: undefined
				}
			},
			submit(type) {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					this.modelEdit = JSON.parse(JSON.stringify(this.model))
					const startTime = new Date(this.modelEdit.START_TIME).getTime();
					const endTime = new Date(this.modelEdit.END_TIME).getTime();
					if (endTime <= startTime) {
						uni.$showErrorInfo('下班时间必须大于上班时间');
						return; // 终止提交流程
					}
					this.modelEdit.RATE = type;
					if (this.TaskID != "") {
						this.modelEdit.TaskID = this.TaskID;
					}
					if (this.modelEdit.ORG_ID == "") {
						this.modelEdit.ORG_ID = this.ORG_ID;
					}
					if (this.modelEdit.USER_ID == "") {
						this.modelEdit.USER_ID = uni.getStorageSync('appInfo').User.ID;
					}
					this.modelEdit.Nav_Users.forEach(item => {
						item.Nav_User = null;
					});
					this.modelEdit.Nav_Files.forEach(item => {
						if (item.PRE_SHIFT_MEETING_RECORD_ID == undefined) {
							item.PRE_SHIFT_MEETING_RECORD_ID = this.modelEdit.ID;
						}
						if (item.ORG_ID == undefined) {
							item.ORG_ID = this.modelEdit.ORG_ID;
						}
					});
					delete this.modelEdit.Nav_Class
					getRequest(this.modelEdit, "/FO/FOPreShiftMeetingRecord/FullUpdate").then(res => {
						if (res) {
							uni.$showMsgFunc('操作成功!', () => {
								uni.navigateBack()
							}, 'success', 1000)
						}
					})
				}).catch(err => {
					uni.$showErrorInfo('请检查必填项，必填项不能为空')
				})
			},
			handleCheckDate1(e) {
				this.showCheckDate1 = false;
				this.model.START_TIME = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
			},
			handleCheckDate2(e) {
				this.showCheckDate2 = false;
				this.model.END_TIME = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
			},
		}
	}
</script>

<style scoped>
	@import url("../../../../style/css/editTemplate.css");

	.todo-page {
		/* padding: 16px 16px 70px; */
	}

	.background {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #edf1fd;
		z-index: -1;
	}

	.card {
		margin: 20px 16px 140px 16px;
		/* border: 1px solid #EBEEF5; */
		padding: 20px 30px 40px 30px;
		/* box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px; */
		background-color: #ffffff;
		border-radius: 10px;
	}

	.upload-title {
		font-size: 14px;
		color: #8e8b9c;
		line-height: 22px;
		padding: 8px 0px;
	}

	.demo-ruleForm>>>.u-form-item__body__left__content__label {
		font-size: 14px;
		color: #8e8b9c;
		/* justify-content: flex-start; */
	}

	.demo-ruleForm>>>.u-form-item__body__left__content__ {
		left: -11px;
		top: 0px
	}

	.demo-ruleForm>>>.u-textarea__field {
		font-size: 14px;
	}

	.demo-ruleForm>>>.u-cell__title-text {
		font-size: 14px;
	}

	.sub-form>>>.u-form-item__body__left__content__label {
		font-size: 14px;
	}

	.sub-form>>>.uni-card--border {
		border: none;
	}

	.sub-form>>>.uni-card {
		border-radius: 0;
	}

	.buttons {
		margin-top: 10px;
		display: flex;
		justify-content: space-between;
	}

	.buttons .first-btn {
		margin-right: 20px;
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 10px 16px;
		box-sizing: border-box;
		background: #edf1fd;
		z-index: 999;
	}
</style>