<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 required label="培训名称：" prop="NAME" borderBottom>
						<u--input v-model="model.NAME" border="none" slot="right" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训类型：" prop="Nav_TrainType.NAME" borderBottom
						@click="handleChange('Nav_TrainType','')">
						<u--input v-if="model.Nav_TrainType" v-model="model.Nav_TrainType.NAME" placeholder="培训类型"
							border="none" inputAlign="right" disabled disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down">
						</u-icon>
					</u-form-item>
					<u-form-item label="培训级别：" prop="LEVEL" borderBottom
						@click="handleShowSheet({title: '层级', name: 'LEVEL'})">
						<u--input :value="model.LEVEL_SHOW" placeholder="请选择层级" border="none" inputAlign="right"
							disabled disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item label="开始时间" required prop="TRAIN_START_TIME" @click="showCheckDate({ name: 'TRAIN_START_TIME'})">
						<u--input disabledColor="#fff" v-model="model.TRAIN_START_TIME" disabled placeholder="请选择开始时间"
							suffixIcon="arrow-down" suffixIconStyle="font-size:14px" fontSize="14px"
							customStyle="margin:0px;display:flex;padding:3px 9px">
						</u--input>
					</u-form-item>
					<u-form-item label="结束时间" required prop="TRAIN_END_TIME" @click="showCheckDate({name: 'TRAIN_END_TIME'})">
						<u--input disabledColor="#fff" v-model="model.TRAIN_END_TIME" disabled placeholder="请选择结束时间"
							suffixIcon="arrow-down" suffixIconStyle="font-size:14px" fontSize="14px"
							customStyle="margin:0px;display:flex;padding:3px 9px">
						</u--input>
					</u-form-item>
					<u-form-item label="培训地点：" prop="TRAIN_ADDR" borderBottom>
						<u--input v-model="model.TRAIN_ADDR" border="none" slot="right" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训学时：" prop="HOURS" borderBottom>
						<u--input v-model="model.HOURS" type="number" border="none" slot="right"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训老师：" prop="TRAIN_TEACHER" borderBottom>
						<u--input v-model="model.TRAIN_TEACHER" border="none" slot="right"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训形式：" prop="TRAIN_MODEL" borderBottom
						@click="handleShowSheet({title: '培训形式', name: 'TRAIN_MODEL'})">
						<u--input :value="model.TRAIN_MODEL_SHOW" placeholder="请选择培训形式" border="none" inputAlign="right"
							disabled disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item label="考核方式：" prop="Nav_TrainCheckType.NAME" borderBottom
						@click="handleChange('Nav_TrainCheckType','')">
						<u--input v-if="model.Nav_TrainCheckType" v-model="model.Nav_TrainCheckType.NAME"
							placeholder="考核方式" border="none" inputAlign="right" disabled
							disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down">
						</u-icon>
					</u-form-item>
					<u-form-item required class="custom-form-item" label="培训内容：" prop="DetailPost" :borderBottom="false"
						@click="handleQuerySelect({ formIndex: 'Nav_TrainContentList', isMultiple: true})">
						<view slot="right" class="custom-form-item-right">
							<view class="multi">
								<u--text v-for="(i, k) in model.Nav_TrainContentList" :key="k" class="item"
									:text="k + 1 + '. ' + i.Nav_Point.NAME"></u--text>
							</view>
							<u-icon class="icon" name="arrow-down">
							</u-icon>
						</view>
					</u-form-item>
					<u-form-item label="培训安排及要求：" prop="TRAIN_PLAN" borderBottom>
					</u-form-item>
					<u--textarea required v-model="model.TRAIN_PLAN" border="surround"></u--textarea>
					<u-form-item label="是否需要培训效果评估：" prop="NEED_EVALUATION" borderBottom
						@click="handleShowSheet({title: '是否需要培训效果评估', name: 'NEED_EVALUATION'})">
						<u--input :value="model.NEED_EVALUATION_SHOW" placeholder="请选择" border="none" inputAlign="right"
							disabled disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item label="是否触发培训记录：" prop="CREATE_NOTIFY_RECORD" borderBottom>
						<u-switch v-model="model.CREATE_NOTIFY_RECORD" @change="changeSwitch" border="none" slot="right"
							inputAlign="right"></u-switch>
					</u-form-item>
					<u-form-item label="记录人员：" prop="Nav_RecordUser.NAME" borderBottom
						@click="handleChange('Nav_RecordUser','')">
						<u--input v-if="model.Nav_RecordUser" v-model="model.Nav_RecordUser.NAME" placeholder="记录人员"
							border="none" inputAlign="right" disabled disabledColor="#fff"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down">
						</u-icon>
					</u-form-item>
					<view class="upload-title">附件：</view>
					<full-upload v-model="model.Nav_Files" :isShowBtn='true' :listProp='listPropUpload'
						:listPropVal='listPropValUpload'></full-upload>
					<u-form-item label="培训人员：">
						<u-icon name="man-add" @click="handleShowUserSelector()" size="24" color="#3d9cff"
							slot="right"></u-icon>
					</u-form-item>
					<view v-show="!!model.Nav_TrainUserList.length" class="tag-view">
						<uni-tag class="tag" v-for="(i, k) in model.Nav_TrainUserList.filter(i => !i.IS_DELETED)"
							:key="k" :inverted="true" :text="i.NAME" type="primary" />
					</view>
				</u--form>
			</uni-card>
		</view>
		<query-selector :show="showPopup" :lists="Lists" @close="handleClosePopup" @search="handleSearch"
			@select="handleSelected" />
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" :defaultIndex="[0]"
			@close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<view class="bottom-button">
		</view>
		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" mode="datetime"
			v-model='dateTimePickerInfo.defaultDateTime' :formatter="formatter" @confirm="handleCheckDate"
			@close="dateTimePickerInfo.showCheckDate = false;"
			@cancel="dateTimePickerInfo.showCheckDate = false;"></u-datetime-picker>
		<query-selector :multiple="qsCom.isMultiple" :total="curTotal" :show="qsCom.show" :lists="qsCom.lists"
			@close="onCloseQS" @search="onSearchQS" @select="onSelectedQS" />
		<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector"
			@select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
		</people-selector>
		<view class="bottom-button">
			<button type="primary" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	export default {
		data() {
			return {
				Lists: [],
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				model: {
					Nav_TrainUserList: [],
					ORG_ID: "",
					Nav_Files: [],
					NEED_EVALUATION_SHOW: "否",
					NEED_EVALUATION: "0",
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				showPopup: false,
				tableKey: '0',
				TaskID: '',
				isLoadOK: false,
				isAdd: 0,
				CheckDate1: false,
				CheckDate2: false,
				ORG_ID: uni.getStorageSync('orgId'),
				curTotal: 0,
				qsCom: {
					show: false,
					lists: [],
					formIndex: undefined,
					isMultiple: false,
				},
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					defaultChecked: []
				},
				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
					value: '',
					name: ''
				},
				formatter: null,
			}
		},
		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();
			}
		},
		methods: {
			changeSwitch(e) {
				this.model.CREATE_NOTIFY_RECORD = e;
			},
			//时间start
			//显示时间控件
			showCheckDate(p) {
				if (p.name === 'TRAIN_START_TIME') {
					if (this.model.TRAIN_START_TIME == null) {
						this.model.TRAIN_START_TIME = uni.$u.timeFormat(new Date(),
							'yyyy-mm-dd hh:MM')
					}
					this.dateTimePickerInfo = {
						showCheckDate: true,
						dataIndex: p.dataIndex,
						defaultDateTime: this.model.TRAIN_START_TIME,
						name: p.name
					}
				} else if (p.name === 'TRAIN_END_TIME') {
					if (this.model.TRAIN_END_TIME == null) {
						this.model.TRAIN_END_TIME = uni.$u.timeFormat(new Date(),
							'yyyy-mm-dd hh:MM')
					}
					this.dateTimePickerInfo = {
						showCheckDate: true,
						dataIndex: p.dataIndex,
						defaultDateTime: this.model.TRAIN_END_TIME,
						name: p.name
					}
				}
			},
			handleCheckDate(e) {
				const {
					name,
					dataIndex
				} = this.dateTimePickerInfo
				if (name === 'TRAIN_START_TIME') {
					this.model.TRAIN_START_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM')
				}
				if (name === 'TRAIN_END_TIME') {
					this.model.TRAIN_END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM')
				}
				this.dateTimePickerInfo.showCheckDate = false
			},
			//时间end
			//单选start
			handleChange(title, item) {
				this.currentOperate = item;
				this.currSearchType = title;
				this.showPopup = true;
				this.handleSearch('init');
			},
			handleSearch(val) {
				const json = initFilter(this.ORG_ID, "", "NAME")
				json.Limit = 20
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				if (this.currSearchType == "Nav_TrainType") {
					getRequest(json, "/SE/TrainTypeEnum/OrderPaged").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_TrainCheckType") {
					getRequest(json, "/SE/TrainCheckTypeEnum/OrderPaged").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_RecordUser") {
					getRequest(json, "/FM/FMUser/OrderPagedUseful").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				}
			},
			handleSelected(val) {
				this.showPopup = false;
				this.Lists = [];
				if (this.currSearchType == 'Nav_TrainType') {
					this.model.Nav_TrainType = val;
					this.model.TRAIN_TYPE = val.ID;
				} else if (this.currSearchType == 'Nav_TrainCheckType') {
					this.model.Nav_TrainCheckType = val;
					this.model.CHECK_TYPE_ID = val.ID;
				} else if (this.currSearchType == 'Nav_RecordUser') {
					this.model.Nav_RecordUser = val;
					this.model.RECORD_USER_ID = val.ID;
				}
			},
			handleClosePopup() {
				this.showPopup = false
			},
			//单选end
			//多选start
			async handleQuerySelect(opt) {
				let column = await this.handleGet(opt, 'init')
				if (column && column.length) {
					this.qsCom = {
						show: true,
						name: opt.NAME,
						formIndex: opt.formIndex,
						isMultiple: opt.isMultiple,
						lists: column
					}
				}
			},
			async onSearchQS(val, pi) {
				const result = await this.handleGet(this.qsCom, val, pi)
				this.qsCom.lists = result.map(i => {
					return {
						...i,
						name: i.NAME,
						NAME: i.NAME,
						id: i.ID
					}
				})
			},
			async handleGet(opt, value, pageIndex) {
				const json = initFilter(this.ORG_ID, '', "", 0, pageIndex || 1)
				if (value !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, value)
					extendFilterGroup(json, tempGroup);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}
				let result = []
				const raw = await getRequest(json, "/SE/TestEnumPoint/OrderPaged").then(res => {
					this.curTotal = res.TotalCount
					return res
				})
				result = raw.map(item => {
					return {
						...item,
						name: item?.NAME,
						POINT_ID: item?.ID
					}
				})
				return result
			},
			onSelectedQS(val) {
				const {
					formIndex,
				} = this.qsCom
				this.model.Nav_TrainContentList = [];
				val.forEach(item => {
					let obj = {
						POINT_ID: item.ID,
						Nav_Point: {
							NAME: item.NAME
						},
						ID: guid(),
						NOTIFY_ID: this.model.ID,
						ORG_ID: this.ORG_ID,
					}
					this.model.Nav_TrainContentList.push(obj);
				})
				this.qsCom.show = false
			},
			onCloseQS() {
				this.qsCom = {
					show: false,
					lists: [],
					formIndex: undefined,
					isMultiple: false,
					dataIndex: undefined
				}
			},
			//多选end
			//人员多选start
			handleShowUserSelector() {
				this.peopleSelectOption = {
					showSelector: true,
					value: this.model,
					defaultChecked: this.model.Nav_TrainUserList.map(i => {
						return {
							...i,
							NAME: i.Nav_User.NAME,
							USER_ID: i.Nav_User.ID,
						}
					})
				}
			},
			handleSelectorPeople(e) {
				this.model.Nav_TrainUserList = e.map(i => {
					return {
						USER_ID: i.USER_ID,
						ID: i.ID || guid(),
						NOTIFY_ID: this.model.ID,
						ORG_ID: this.ORG_ID,
						IS_DELETED: i.IS_DELETED,
						NAME: i.NAME,
						Nav_User: {
							NAME: i.NAME,
							ID: i.USER_ID
						}
					}
				})
			},
			//人员多选end
			loadData() {
				const json = initFilter(this.ORG_ID, "", "")
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendInclude(json, "Nav_TrainContentList.Nav_Point")
				extendInclude(json, "Nav_LaunchDepartment")
				extendInclude(json, "Nav_TrainType")
				extendInclude(json, "Nav_TrainCheckType")
				extendInclude(json, "Nav_RecordUser")
				extendInclude(json, "Nav_TrainContentList")
				extendInclude(json, "Nav_TrainUserList.Nav_User.Nav_Person")
				extendInclude(json, "Nav_Files.Nav_ImgFile.Nav_File")
				// TODO: id 未获取
				extendRule(json, 'ID', 1, this.model.ID)
				getRequest(json, "/SE/TrainNotify/Get").then(res => {
					this.model = res
					this.model.LEVEL_SHOW = this.transLevel(this.model.LEVEL)
				})
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					dataIndex: undefined,
					formIndex: undefined
				}
			},
			async handleShowSheet(p, index) {
				let column = []
				this.levelIndex = index;
				if (p.name === 'LEVEL') {
					column = [{
							NAME: '部门',
							ID: 0
						},
						{
							NAME: '车间',
							ID: 1
						},
						{
							NAME: '班组',
							ID: 2
						},
						{
							NAME: '公司',
							ID: 3
						}
					]
				} else if (p.name === 'TRAIN_MODEL') {
					column = [{
							NAME: '讲授法',
							ID: "_1_"
						},
						{
							NAME: '视听法',
							ID: "_2_"
						},
						{
							NAME: '研讨法',
							ID: "_3_"
						},
						{
							NAME: '演示法',
							ID: "_4_"
						}
					]
				} else if (p.name === 'NEED_EVALUATION') {
					column = [{
							NAME: '否',
							ID: 0
						},
						{
							NAME: '是',
							ID: 1
						},
					]
				}
				if (column.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						formIndex: p.formIndex,
						columns: [column]
					}
				} else {
					// 暂无数据
				}
			},
			onConfirmPicker(e) {
				const {
					name,
					formIndex
				} = this.comPickerInfo
				this.model[name] = e.value[0].ID
				this.model[name + '_SHOW'] = e.value[0].NAME
				this.comPickerInfo.showSheet = false
			},
			transLevel(level) {
				if (level == 0) {
					return '部门 ';
				}
				if (level == 1) {
					return '车间 ';
				}
				if (level == 2) {
					return '班组 ';
				}
				if (level == 3) {
					return '公司 ';
				}
			},
			submit() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					this.model.PUBLISH = "SaveAndNotify";
					if (this.TaskID != "") {
						this.model.TaskID = this.TaskID;
					}
					if (this.model.ORG_ID == "") {
						this.model.ORG_ID = this.ORG_ID;
					}
					this.model.Nav_TrainUserList.forEach(item => {
						item.Nav_User = null;
					});
					this.model.TRAIN_START_TIME = uni.$u.timeFormat(this.model.TRAIN_START_TIME, 'yyyy-mm-dd hh:MM:ss');
					this.model.TRAIN_END_TIME = uni.$u.timeFormat(this.model.TRAIN_END_TIME, 'yyyy-mm-dd hh:MM:ss');
					this.model.Nav_TrainType = null;
					this.model.Nav_TrainCheckType = null;
					this.model.Nav_RecordUser = null;
					this.model.Nav_Files.forEach(item => {
						if (item.NOTIFY_ID == undefined) {
							item.NOTIFY_ID = this.model.ID;
						}
						if (item.ORG_ID == undefined) {
							item.ORG_ID = this.model.ORG_ID;
						}
					});
					getRequest(this.model, "/SE/SETrainNotify/FullUpdate").then(res => {
						if (res) {
							uni.$showMsgFunc('操作成功!', () => {
								uni.navigateBack()
							}, 'success', 1000)
						}
					})
				}).catch(err => {
					uni.$showErrorInfo('请检查必填项，必填项不能为空')
				})
			},

		}
	}
</script>

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

	.todo-page {
		padding: 16px 16px 70px;
	}
</style>