<template>
	<view class="page-wrap">
		<view class="date-select">
			<view class="previous-day" @click="handleChangeDay(-1)">
				<u-icon name="arrow-left-double"></u-icon>
				<text>前一天</text>
			</view>
			<uni-datetime-picker class="date-picker" type="date" :clear-icon="false" v-model="single"
				@maskClick="maskClick" @change="onChangeTime" />
			<view class="next-day" @click="handleChangeDay(1)">
				<text>后一天</text>
				<u-icon name="arrow-right-double"></u-icon>
			</view>
		</view>
		<view class="card" v-for="(item, key) in workShopScheduling" :key="key">
			<uni-card :is-shadow="false" margin="0">
				<view slot="title">
					<view class="custom-card-title">
						<text class="text">{{item[0].DEPARTMENT_NAME}}</text>
					</view>
				</view>
				<view v-for="(sub, index) in item" :key="index" class="class-list">
					<view class="class-info">
						<view class="class-name">{{sub.Nav_Team.NAME}}: </view>
						<view class="subDep">{{sub.Nav_Class.NAME}}</view>
					</view>
					<view class="users-icon" @click="showUsers(sub,sub.ID,sub.Nav_Team.NAME)">
						<uni-icons type="staff-filled" color="#007aff" size="24" />
					</view>
				</view>
			</uni-card>
		</view>
		<u-modal :show="showModal" :title="currTeam ? currTeam + '人员' : '班组人员'" @confirm="onConfirm" style="width: 1em;" confirm-text="确认" showCancelButton="true" cancelText="关闭" @cancel="onCancelConfirm()">
			<scroll-view scroll-y="true" class="user-list-wrap">
				<view class="user-list" v-for="(item, key) in userLists" :key="key">
					<view>
						<u-form-item v-if="showDelete"  label="" prop="personName" @click="handleChangeUser(item['Nav_Person'])">
							<u--input disabled disabledColor="#fff" v-model="item['Nav_Person'].NAME" placeholder="请选择人员姓名" suffixIcon="arrow-right" suffixIconStyle="font-size:14px" fontSize="14px"
								 border="none">
							</u--input>
							</u-icon>
						</u-form-item>
						<u-form-item v-if="!showDelete">{{item.Nav_Person.NAME}}|{{item.Nav_Person.CODE}}({{item.Nav_Person.Nav_Post?item.Nav_Person.Nav_Post.NAME:''}})</u-form-item>
						
						<u-icon @click="delUser(item)" style="float: right;" name="trash" color="#ff4d4f"
							v-if="showDelete" size="21"></u-icon>
					</view>
				</view>
				<u-button v-if="showDelete" type="primary" @click="handleAddUser(userLists[0])" color="#3d4b70" :plain="true" style="margin-right: 5px;">添加人员</u-button>
			
				<!-- <view style="display: flex;align-items: center;justify-content: center;border-top: #e7e6e4 1px solid;" @click="handleAddUser">
					<view style="display: flex;align-items: center;justify-content: center;">
						<view style="font-size: 16px;color: #3d4b70;font-weight: bold;padding: 15px 0px;" v-if="this.userLists.length == 1">添加人员信息</view>
						<view style="font-size: 16px;color: #3d4b70;font-weight: bold;padding: 15px 0px;" v-if="this.userLists.length !== 1">继续添加人员信息</view>
					</view>
				</view> -->
			</scroll-view>
		</u-modal>
		<query-selector :show="showPopup" :total="curTotal" :lists="userListTemps" :defaultValue="currentOperateUser.NAME" @close="handleClosePopup" @search="handleSearchUser" @select="handleSelectedUser" />
		<u-modal :show="delUserItem!=undefined" @confirm="confirmDel" @cancel="cancelDel" showCancelButton
			title="确认删除？"></u-modal>
	</view>
				
</template>

<script>
	import {
		getScheduleData,
		getWorkShopData,
	} from '../../../../services/apply/FMServices/FMServices'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendRule,
		initFilter,
		initFilterGroup,
		guid,
	} from '../../../../utils/common'
	import {
		getRequest,
		getPersonLists,
	} from '../../../../services/apply/FOServices/FOServices';
	import request from '../../../../utils/request';
	export default {
		data() {
			return {
				showModal: false,
				currTeam: {},
				single: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				workShops: [],
				workShopScheduling: [],
				userLists: [],
				delUserItem: undefined,
				currUserPersonId: uni.getStorageSync('appInfo').User.PERSON_ID,
				showDelete: false,
				currentOperateUser: {},
				showPopup: false,
				curTotal: 0,
				userListTemps: [],
				currScheduling:{
					Nav_DepartmentSchedulingDetail:{}
				}
			}
		},
		onLoad() {
			this.loadWorkShopData()
		},
		methods: {
			delUser(item) {
				this.delUserItem = item;
			},
			cancelDel() {
				this.delUserItem = undefined
			},
			confirmDel() {
				let SchedulingId = this.delUserItem.DEPARTMENT_SCHEDULING_ID;
				request.get("/FM/DepartmentSchedulingDetail/Delete?id=" + this.delUserItem.ID).then(res => {
					if (res) {
						this.showUsers(this.currScheduling,SchedulingId)
						this.delUserItem = undefined;
					}
				})
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				this.currentOperateUser = user
				this.showPopup = true
				this.handleSearchUser('init')
			},
			handleSearchUser(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				extendInclude(json, "Nav_Post")
				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;
				}
			
				getPersonLists(json).then(res => {
					if (res.IsSuccessful) {
						this.userListTemps = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
						this.curTotal = res.TotalCount
					}
				})
			},
			handleSelectedUser(val) {
				// let numc = 0;
				// this.userLists.map((item) => {
				// 	if (item.PERSON_ID == val.ID) {
				// 		numc = numc + 1
				// 		return
				// 	}
				// })
				// if (numc >= 1) {
				// 	this.showPopup = false
				// 	uni.$showErrorInfo('不能选择相同的人员')
				// 	return
				// }
				this.showPopup = false
				this.currentOperateUser.CODE = val.CODE
				this.lists = []
				const result = this.userLists.map((obj) => {
					const {
						Nav_Person
					} = obj
					if (Nav_Person.CODE === this.currentOperateUser.CODE) {
						return Object.assign({}, obj, {
							Nav_Person: val,
							PERSON_ID: val.ID,
						})
					}
					return obj
				})
				this.userLists = result
			},
			loadWorkShopData() {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", 0)
				json.Level = -1
				json.Limit = 100
				getWorkShopData(json).then(res => {
					this.workShops = res || []
					this.loadScheduleData(res)
				})
			},
			loadScheduleData(deps) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NUM", 0)
				extendRule(json, 'DATE_TIME', 1, this.single)
				const tempGroup = initFilterGroup(false)
				deps.forEach(i => {
					extendGroupRule(tempGroup, 'DEPARTMENT_ID', 1, i.Node.ID)
				})
				extendFilterGroup(json, tempGroup)
				extendInclude(json, "Nav_Class")
				extendInclude(json, "Nav_Class.Nav_ClassDetail")
				extendInclude(json, 'Nav_DepartmentSchedulingDetail')
				extendInclude(json, 'Nav_Team.Nav_ChargePerson')
				json.Limit = 100
				getScheduleData(json).then(res => {
					res.forEach(r => {
						deps.forEach(d => {
							if (r.DEPARTMENT_ID === d.Node.ID) {
								r.DEPARTMENT_NAME = d.Node.NAME
							}
						})
					})
					const groupData = this.depGroup(res || [], e => e.DEPARTMENT_ID)
					this.workShopScheduling = groupData
				})
			},
			depGroup(arr, fn) {
				const obj = {};
				arr.forEach(item => {
					const key = JSON.stringify(fn(item));
					obj[key] = obj[key] || [];
					obj[key].push(item)
				});
				return Object.keys(obj).map(k => {
					return obj[k];
				})
			},
			handleAddUser(item) {
				let temp= [];
				temp.PERSON_ID=null
				temp.Nav_Person={}
				temp.CREATER_ID=uni.getStorageSync('appInfo').User?.ID
				temp.CREATE_TIME=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
				temp.MODIFIER_ID=uni.getStorageSync('appInfo').User?.ID
				temp.MODIFY_TIME=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
				temp.ID=guid()
				temp.DEPARTMENT_SCHEDULING_ID=item.DEPARTMENT_SCHEDULING_ID
				temp.ENTITY_ORG_TPYE=item.ENTITY_ORG_TPYE
				temp.FLOW_ID=item.FLOW_ID
				temp.FLOW_SEND_STATUS=item.FLOW_SEND_STATUS
				temp.FLOW_STATUS=item.FLOW_STATUS
				temp.FORM_ID=item.FORM_ID
				temp.IS_DELETED=item.IS_DELETED
				temp.Nav_DepartmentScheduling=item.Nav_DepartmentScheduling
				temp.ORG_ID=item.ORG_ID
				temp.TaskID=item.TaskID
				this.userLists.push(temp)
			},
			showUsers(item,ID, NAME) {
				this.currScheduling = item
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "Nav_Person.NAME")
				if (NAME != undefined) {
					this.currTeam = NAME
				}
				extendInclude(json, "Nav_Person.Nav_Post")
				extendInclude(json, "Nav_DepartmentScheduling.Nav_Team")
				extendRule(json, 'DEPARTMENT_SCHEDULING_ID', 1, ID)
				getRequest(json, "/FM/DepartmentSchedulingDetail/OrderEntities").then(res => {
					if (res && res.length) {
						if (res[0].Nav_DepartmentScheduling.Nav_Team.CHARGE_PERSON_ID == this.currUserPersonId) {
							this.showDelete = true;
						} else {
							this.showDelete = false;
						}
						this.showModal = true
						this.userLists = res || []
					}
				})
			},
			onChangeTime(e) {
				this.single = e
				this.loadWorkShopData()
			},
			handleChangeDay(day) {
				const stamp = new Date(this.single).getTime() + 24 * 60 * 60 * 1000 * day
				this.single = uni.$u.timeFormat(stamp)
				this.loadWorkShopData()
			},
			onCancelConfirm(){
				this.showModal = false
				this.currTeam = {}
				this.userLists = []
			},
			onConfirm() {
				// this.showModal = false
				// this.currTeam = {}
				// this.userLists = []
				
				this.currScheduling.Nav_DepartmentSchedulingDetail = this.userLists
				// let SchedulingId = this.delUserItem?.DEPARTMENT_SCHEDULING_ID;
				getRequest(this.currScheduling,"/FM/DepartmentScheduling/FullUpdateDetail").then(res => {
					if (res) {
						// this.showUsers(SchedulingId)
						// this.delUserItem = undefined;
						this.showModal = false
						this.currTeam = {}
						this.userLists = []
					}
				})
			}
		}
	}
</script>

<style scoped>
	.page-wrap {
		padding: 16px 16px 66px;
	}

	.date-picker {
		/*margin-bottom: 16px;*/
	}

	.date-select {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16px;
	}

	.date-select .previous-day,
	.date-select .next-day {
		display: flex;
		font-size: 14px;
		width: 78px;
	}

	.date-select .next-day {
		justify-content: flex-end;
	}

	.date-select .previous-day text {
		margin-left: 4px;
	}

	.date-select .next-day text {
		margin-right: 4px;
	}

	.card {
		margin-bottom: 18px;
	}

	.custom-card-title {
		display: flex;
		border-bottom: 1px #EBEEF5 solid;
		flex-direction: row;
		align-items: center;
		padding: 10px;
		overflow: hidden;
		justify-content: space-between;
	}

	.custom-card-title .text {
		font-size: 18px;
		font-weight: bold;
	}

	.class-list {
		display: flex;
		margin-bottom: 12px;
		align-items: center;
		justify-content: space-between;
	}

	.class-info {
		display: flex;
		flex: 1;
	}

	.users-icon {
		width: 30px;
		text-align: right;
	}

	.class-info .name {
		flex: 1
	}

	.class-name {
		font-weight: 500;
		font-size: 16px;
		margin-right: 8px;
	}

	.user-list-wrap {
		max-height: 300px;
	}

	.user-list {
		margin-bottom: 15px;
	}
</style>