<template>
	<view class="todo-page">
		<view class="card">
			<uni-card margin="0" :is-shadow="true">
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules"
					ref="wForm" errorType="border-bottom">
					<u-form-item label="开始时间：" prop="START_TIME" borderBottom @click="showCheckDate1 = true;"
						v-if="isAdd==1">
						<u--input v-model="model.START_TIME" disabled disabledColor="#fff" placeholder="请选择开始时间"
							border="none" inputAlign="right"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item label="结束时间：" prop="END_TIME" borderBottom @click="showCheckDate2 = true;"
						v-if="isAdd==1">
						<u--input v-model="model.END_TIME" disabled disabledColor="#fff" placeholder="请选择结束时间"
							border="none" inputAlign="right"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</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 label="注意事项及防护措施：" prop="PROTECT_MEASURE" borderBottom>
					</u-form-item>
					<u--textarea 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>
			</uni-card>
		</view>
		<u-sticky offset-top="20">
			<view class="sub-form">
				<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 style="margin-bottom: 16px;" 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" />
		<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">提交</button>
		</view>
		<u-datetime-picker :show="showCheckDate1" mode="datetime" v-model=START_TIME @confirm="handleCheckDate1"
			@close="showCheckDate1 = false;" @cancel="showCheckDate1 = false;"></u-datetime-picker>
		<u-datetime-picker :show="showCheckDate2" mode="datetime" v-model=END_TIME @confirm="handleCheckDate2"
			@close="showCheckDate2 = false;" @cancel="showCheckDate2 = false;"></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
	} from '../../../../services/safe';

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

	export default {
		data() {
			return {
				userLists: [],
				listPropUpload: ['PRE_SHIFT_MEETING_RECORD_ID'],
				listPropValUpload: [],
				model: {
					JOB_CONTENT: "",
					Nav_Users: [],
					ORG_ID: "",
					Nav_Files: [],
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'JOB_CONTENT': {
						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,
				showCheckDate1: false,
				showCheckDate2: false,
				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.START_TIME = uni.$u.timeFormat(Date(), 'yyyy-mm-dd hh:MM:ss');
				this.model.END_TIME = uni.$u.timeFormat(Date(), 'yyyy-mm-dd hh:MM:ss');
				this.model.ID = guid();
				this.loadTeamUsers();
			}
		},
		methods: {
			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,
				})
			},
			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
			},
			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.Nav_File")
				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
				})
			},
			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) {
				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() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					this.model.RATE = "SaveAndNotify";
					if (this.TaskID != "") {
						this.model.TaskID = this.TaskID;
					}
					if (this.model.ORG_ID == "") {
						this.model.ORG_ID = this.ORG_ID;
					}
					this.model.Nav_Users.forEach(item => {
						item.Nav_User = null;
					});
					this.model.Nav_Files.forEach(item => {
						if (item.PRE_SHIFT_MEETING_RECORD_ID == undefined) {
							item.PRE_SHIFT_MEETING_RECORD_ID = this.model.ID;
						}
						if (item.ORG_ID == undefined) {
							item.ORG_ID = this.model.ORG_ID;
						}
					});
					getRequest(this.model, "/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;
	}
</style>