<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="ACTIVITY_TIME" borderBottom @click="showCheckDate = true;">
						<u--input v-model="model.ACTIVITY_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="TITLE" borderBottom>
						<u--input v-model="model.TITLE" placeholder="请输入活动主题" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="活动地点：" prop="ADDRESS" borderBottom>
						<u--input v-model="model.ADDRESS" placeholder="请输入活动地点" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="活动时长(小时)：" prop="DURATION" borderBottom>
						<u--input type="number" v-model="model.DURATION" placeholder="请输入活动时长" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="活动内容：" borderBottom>
					</u-form-item>
					<u-form-item label="" prop="ACTIVITY_CONTENT">
						<u--textarea 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">
				<view class="sub-form-wrap">
					<view class="sub-form-btns">
						<view class="sub-form-btn" @click="handleAdd" v-if='tableKey==1'>
							<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-if="!item.IS_DELETED"
								v-for="(item, index) in model.Nav_TeamActivityUser.filter(i => !i.IS_DELETED)">
								<u-collapse-item
									:title="(index + 1) + '. ' + item.Nav_User.NAME+' | '+item.Nav_User.CODE">
									<view slot="right-icon" class="row-action"></view>
									<view slot="value" 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 label="人员姓名" prop="Nav_User.NAME" borderBottom
										@click="handleChangeUser(item['Nav_User'])">
										<u--input disabled disabledColor="#fff" v-model="item['Nav_User'].NAME"
											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="ATTEND_STATUS_SHOW" borderBottom
										@click="handleChange(item)">
										<u--input v-model="item.ATTEND_STATUS_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-collapse-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" v-if='tableKey==1||isAdd==1'>提交</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: [],
				model: {
					TITLE: '',
					ACTIVITY_TIME: '',
					ORG_ID: "",
					NOTE_AKER_ID: "",
					TEAM_ID: "",
					Nav_TeamActivityUser: [],
					Nav_TeamActivityFile: [],
				},
				activityTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'TITLE': {
						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: {
			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
			},
			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.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.Nav_File")
				extendInclude(json, "Nav_Taem")
				extendInclude(json, "Nav_User")
				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;
					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.NAME = val.NAME;
				this.currentOperateUser.CODE = val.CODE;
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				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() {
				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.TEAM_ID == "") {
					this.model.TEAM_ID = uni.getStorageSync('appInfo').User.Team.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;
					}
				});
				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;
	}
</style>