<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 required label="活动日期：" prop="ACTIVITY_TIME" borderBottom @click="showCheckDate = true;">
					<u--input required v-model="model.ACTIVITY_TIME" disabled disabledColor="#fff" placeholder="请选择活动日期" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12"></u-icon>
				</u-form-item>
				<u-form-item required label="活动主题：" prop="TITLE" borderBottom>
					<u--input required v-model="model.TITLE" placeholder="请输入活动主题" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item required label="活动地点：" prop="ADDRESS" borderBottom>
					<u--input required v-model="model.ADDRESS" placeholder="请输入活动地点" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item required label="主持人：" prop="Nav_MainUser.NAME" @click="handleChangeMainUser(model.Nav_MainUser)" borderBottom>
					<u--input required disabledColor="#fff" v-model="model.Nav_MainUser.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="Nav_User.NAME" @click="handleChangeMonitor(model.Nav_User)" borderBottom>
					<u--input required disabledColor="#fff" v-model="model.Nav_User.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 required label="活动时长(小时)：" prop="DURATION" borderBottom>
					<u--input required type="number" v-model="model.DURATION" placeholder="请输入活动时长" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item required label="活动内容：">
				</u-form-item>
				<u-form-item label="" prop="ACTIVITY_CONTENT">
					<u--textarea required v-model="model.ACTIVITY_CONTENT" placeholder="请输入活动内容" border="surround"></u--textarea>
				</u-form-item>
				<view class="upload-title">附件</view>
				<full-upload v-model="model.Nav_TeamActivityFile" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>
			</u--form>
			<u-datetime-picker :show="showCheckDate" mode="date" v-model="activityTime" @confirm="handleCheckDate" @close="showCheckDate = false;" @cancel="showCheckDate = false;"></u-datetime-picker>
			<!-- </uni-card> -->
		</view>
		<u-sticky offset-top="20">
			<view class="sub-form" style="padding-bottom: 100px;">
				<view class="sub-form-wrap">
					<view class="sub-form-btns">
						<!-- v-if='tableKey==1' -->
						<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" class="card" v-if="model.Nav_TeamActivityUser.length!==0">
						<!-- <u-collapse :border="false" accordion> -->
						<view v-if="!item.IS_DELETED" v-for="(item, index) in model.Nav_TeamActivityUser.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-icon" class="row-action"></view> -->
								<view slot="right" class="row-action">
									<view class="action" @click.stop style="display: flex;flex-direction: row;">
										参与：<u-switch v-model="item.ATTEND_STATUS" :activeValue="1" :inactiveValue="0" inactiveColor="rgb(230, 230, 230)" size="20" space="4" @change="changeswitch(item)"></u-switch>
										<u-icon @click="handleDelRowBefore(index, item)" class="icon" name="trash" color="#ff4d4f" size="21" style="margin-left: 10px;"></u-icon>
									</view>
								</view>
								<!-- <u-form-item label="人员姓名" prop="Nav_User.NAME" borderBottom
										@click="handleChangeUser(item)">
										<u--input disabled disabledColor="#fff" v-model="item['Nav_User'].NAME"
											placeholder="请选择人员姓名" border="none" inputAlign="right" fontSize="14px"></u--input>
										<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12"></u-icon>
									</u-form-item>
									<u-form-item label="出席状态：" prop="ATTEND_STATUS_SHOW" borderBottom
										@click="handleChange(item)">
										<u--input v-model="item.ATTEND_STATUS_SHOW" placeholder="出席状态" border="none"
											inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
										<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
										</u-icon>
									</u-form-item> -->
							</u-form-item>
						</view>
						<!-- </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" />
		<query-selector :show="showPopupMainUser" :total="curTotalMainUser" :lists="mainUserLists" :defaultValue="currentOperateMainUser.NAME" @close="handleClosePopupMainUser" @search="handleSearchMainUser"
			@select="handleSelectedMainUser" />
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<view style="padding: 10px 16px;display: flex;flex-direction: row;" class="bottom-button">
			<u-button type="default" @click="submit('Save')" :plain="true" color="#3d4b70" style="margin-right: 5px;">保存</u-button>
			<!-- <u-button type="primary" @click="submit" v-if='tableKey==1||isAdd==1' color="#3d4b70">提交</u-button> -->
			<u-button type="default" @click="submit('SaveAndNotify')" v-if='tableKey==1||isAdd==1' color="#3d4b70" style="margin-left: 5px;">提交</u-button>
		</view>
	</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: ['TEAM_ACTIVITY_ID'],
				listPropValUpload: [],
				curTotalMonitor: 0,
				monitorLists: [],
				currentOperateMonitor: {},
				showPopupMonitor: false,
				curTotalMainUser: 0,
				mainUserLists: [],
				currentOperateMainUser: {},
				showPopupMainUser: false,
				model: {
					TITLE: "",
					ADDRESS: "",
					DURATION: "",
					ACTIVITY_CONTENT: "",
					ACTIVITY_TIME: '',
					ORG_ID: "",
					NOTE_AKER_ID: "",
					TEAM_ID: "",
					Nav_TeamActivityUser: [],
					Nav_TeamActivityFile: [],
					Nav_User: {
						NAME: ''
					},
					NOTE_AKER_ID: null,
					Nav_MainUser: {
						NAME: ''
					},
					USER_ID: null,
				},
				activityTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'TITLE': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'ADDRESS': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'DURATION': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'ACTIVITY_CONTENT': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
				},
				currentOperateUser: {},
				showCheckDate: false,
				showPopup: false,
				tableKey: '0',
				TaskID: '',
				isLoadOK: false,
				showDelModalIndex: undefined,
				isAdd: 0,
				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.model.ACTIVITY_TIME = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd');
				this.loadTeamUsers();
			}
		},
		methods: {
			changeswitch(item) {
				if (item.ATTEND_STATUS == 1) {
					item.ATTEND_STATUS_SHOW = "参与"
				} else {
					item.ATTEND_STATUS_SHOW = "请假"
					item.ATTEND_STATUS = 2
				}
			},
			handleAdd() {
				this.model.Nav_TeamActivityUser.unshift({
					ID: guid(),
					TEAM_ACTIVITY_ID: this.model.ID,
					ORG_ID: this.ORG_ID,
					Nav_User: {
						NAME: "",
						CODE: "",
					},
					USER_ID: "",
					IS_DELETED: false,
					ATTEND_STATUS_SHOW: "参与",
					ATTEND_STATUS: 1
				})
			},
			handleDelRowBefore(index, item) {
				if (item.USER_ID == "") {
					this.model.Nav_TeamActivityUser.splice(index, 1)
				} else {
					this.showDelModalIndex = index
				}
			},
			cancelDel() {
				this.showDelModalIndex = undefined
			},
			confirmDel() {
				this.model.Nav_TeamActivityUser.filter(i => !i.IS_DELETED)[this.showDelModalIndex].IS_DELETED = true;
				//this.model.Nav_TeamActivityUser.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)
				extendInclude(json, "Nav_Department")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				if (orgId === '8b3c41aa-51b1-7ce9-1879-248a038c1b5c') {
					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);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}

				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
					}
				})
			},
			handleSelectedMonitor(val) {
				this.showPopupMonitor = false
				this.currentOperateMonitor = val
				this.model.Nav_User = val
				this.model.NOTE_AKER_ID = val.ID
			},
			handleClosePopupMonitor() {
				this.showPopupMonitor = false
			},
			handleChangeMainUser(user) {
				this.currentOperateMainUser = user
				this.showPopupMainUser = true
				this.handleSearchMainUser('init')
			},
			handleSearchMainUser(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				extendInclude(json, "Nav_Department")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				if (orgId === '8b3c41aa-51b1-7ce9-1879-248a038c1b5c') {
					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);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}

				getUserLists(json).then(res => {
					if (res.IsSuccessful) {
						this.mainUserLists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
						this.curTotalMainUser = res.TotalCount
					}
				})
			},
			handleSelectedMainUser(val) {
				this.showPopupMainUser = false
				this.currentOperateMainUser = val
				this.model.Nav_MainUser = val
				this.model.USER_ID = val.ID
			},
			handleClosePopupMainUser() {
				this.showPopupMainUser = false
			},

			loadTeamUsers() {
				let personid = uni.getStorageSync('appInfo').User.PERSON_ID;
				const json = initFilter(this.ORG_ID, "", "")
				extendRule(json, 'CHARGE_PERSON_ID', 1, personid);
				extendRule(json, 'ENABLE_STATUS', 1, 0);
				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.TEAM_ACTIVITY_ID = this.model.ID;
								objPerson.USER_ID = item.Nav_Person?.Nav_User?.ID;
								objPerson.ATTEND_STATUS = 1;
								objPerson.ATTEND_STATUS_SHOW = "参与";
								objPerson.SIGN_IN_STATUS = 0;
								objPerson.ORG_ID = this.ORG_ID;
								person.push(objPerson);
								rowNo++;
							})
						}
						this.model.Nav_TeamActivityUser = person;
					}
				})
			},
			loadData() {
				const json = initFilter(this.ORG_ID, "", "")
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendInclude(json, "Nav_TeamActivityFile.Nav_ImgFile")
				extendInclude(json, "Nav_Taem")
				extendInclude(json, "Nav_User")
				extendInclude(json, "Nav_MainUser")
				extendInclude(json, "Nav_TeamActivityUser")
				extendInclude(json, "Nav_TeamActivityUser.Nav_User")
				extendInclude(json, "Nav_TeamActivityUser.Nav_User.Nav_Person.Nav_Post")
				extendRule(json, 'ID', 1, this.model.ID)

				getRequest(json, "/FO/TeamActivity/Get").then(res => {
					this.model = res;
					if (res.USER_ID == null) {
						// res.USER_ID = uni.getStorageSync('appInfo').User.ID;
						res.Nav_MainUser = {};
					}
					this.model.Nav_TeamActivityUser.forEach(item => {
						if (item.ATTEND_STATUS == 1) {
							item.ATTEND_STATUS_SHOW = "参与"
						} else {
							item.ATTEND_STATUS_SHOW = "请假"
						}
					})
					this.model.ACTIVITY_TIME = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd');
				})
			},
			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")
				}

			},
			handleChange(item) {
				this.currentOperate = item;
				this.comPickerInfo.showSheet = true;
				let column = []
				column = [{
						NAME: '参与',
						ID: 1
					},
					{
						NAME: '请假',
						ID: 2
					}
				]
				this.comPickerInfo = {
					showSheet: true,
					columns: [column]
				}

			},
			onConfirmPicker(e) {
				this.currentOperate.ATTEND_STATUS = e.value[0].ID
				this.currentOperate.ATTEND_STATUS_SHOW = e.value[0].NAME
				this.comPickerInfo.showSheet = false
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
				}
			},
			handleCheckDate(e) {
				this.showCheckDate = false
				this.model.ACTIVITY_TIME = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
			},
			submit(type) {
				if (this.model.TITLE == "") {
					uni.$showMsgFunc('请填写活动主题!', () => {}, 'error', 1000)
					return;
				}
				if (this.model.ADDRESS == "") {
					uni.$showMsgFunc('请填写活动地点!', () => {}, 'error', 1000)
					return;
				}
				if (this.model.DURATION == "") {
					uni.$showMsgFunc('请填写活动时长!', () => {}, 'error', 1000)
					return;
				}
				if (this.model.ACTIVITY_CONTENT == "") {
					uni.$showMsgFunc('请填写活动内容!', () => {}, 'error', 1000)
					return;
				}
				if (this.model.Nav_TeamActivityFile.length == 0) {
					uni.$showMsgFunc('请上传附件!', () => {}, 'error', 1000)
					return;
				}
				if (this.TaskID != "") {
					this.model.TaskID = this.TaskID;
				}
				if (this.model.ORG_ID == "") {
					this.model.ORG_ID = this.ORG_ID;
				}
				if (this.model.NOTE_AKER_ID == "") {
					this.model.NOTE_AKER_ID = uni.getStorageSync('appInfo').User.ID;
				}
				if (this.model.USER_ID == "") {
					this.model.USER_ID = uni.getStorageSync('appInfo').User.ID;
				}

				this.model.Nav_TeamActivityUser.forEach(item => {
					item.Nav_User = null;
				});
				this.model.Nav_TeamActivityFile.forEach(item => {
					if (item.TEAM_ACTIVITY_ID == undefined) {
						item.TEAM_ACTIVITY_ID = this.model.ID;
					}
				});
				if (type == 'SaveAndNotify') {
					this.model.OpType = 0;
				} else {
					this.model.OpType = 1;
				}
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					getRequest(this.model, "/FO/FOTeamActivity/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; */
	}

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

	.card {
		margin: 20px 16px 20px 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;
	}

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

	.sub-form-btn {
		display: flex;
		flex-direction: row;
		margin: 0px 16px;
	}

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

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

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

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

	.sub-form>>>.u-form-item__body {
		padding: 15px 0px;
	}
</style>