<template>
	<view class="page-wrap">
		<view class="card">
			<uni-card margin="0" :is-shadow="true">
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="dataModel" 
					ref="wForm" errorType="border-bottom">
					<!-- <u-form-item label="发起时间" prop="CREATE_TIME" borderBottom>
						<u--input v-model="dataModel.CREATE_TIME" disabled disabledColor="#ffffff" placeholder="请输入发起时间" border="none" inputAlign="right">
						</u--input>
					</u-form-item> -->
					<u-form-item label="发起部门" prop="DepartmentName" borderBottom>
						<u--input v-model="dataModel.Nav_Department.NAME" disabled disabledColor="#ffffff"  placeholder="请输入发起部门" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="发起人员" prop="UserName" borderBottom>
						<u--input v-model="dataModel.Nav_User.NAME" disabled disabledColor="#ffffff" placeholder="请输入发起人员" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="变化描述" prop="DESCRIPTION" borderBottom>
						<u--input v-model="dataModel.DESCRIPTION" disabledColor="#ffffff" placeholder="请输入变化描述" border="none" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="变化类型" prop="UserNames" borderBottom>
					</u-form-item>
					<u--textarea autoHeight type="textarea" v-html="dataModel.UserNames" border="none"
						inputAlign="left">
					</u--textarea>
				</u--form>
			</uni-card>
		</view>
		<view class="sub-form">
			<view class="sub-form-wrap">
				<view class="sub-form-btns">
					<view class="sub-form-btn" @click="handleAddUser">
						<!-- <u-icon class="icon" name="plus" color="#2979ff" size="14"></u-icon> -->
						<u-icon name="plus-circle" color="#3C9CFF" style="margin-right: 2px;"></u-icon>
						<u--text type="primary" text="新增验收内容"></u--text>
					</view>
				</view>
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom"
								 ref="sForm">
					<uni-collapse :border="false" accordion>
						<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
											v-for="(item, index) in dataModel.Nav_Tasks" :key="index">
							<uni-collapse-item title-border="none" :show-arrow="false">
								<!-- <view slot="right-icon" class="row-action"></view> -->
								<!-- <view slot="value" class="row-action">
									<text @click.stop="handleOkRow">
										<u--text type="primary" text="确认"></u--text>
									</text>
									<text @click.stop="handleDelRowBefore(index)">
										<u--text type="error" text="删除"></u--text>
									</text>
								</view> -->
								<view slot="title" class="collapse-title">
									<view class="down">
										<uni-icons type="bottom"></uni-icons>
									</view>
									<view class="text">{{index + 1 + '. ' +item.Nav_Task.NAME}}</view>
									<view class="action">
										<text @click.stop="handleDelRowBefore(index)" >
											<u-icon name="trash" size="20" color="#EE6666"></u-icon>
											<!-- <u--text type="primary" text="删除"></u--text> -->
										</text>
									</view>
								</view>
								<u-form-item label="验收内容" prop="taskName" borderBottom
														 @click="handleChangeTask(item['Nav_Task'])">
									<u--input disabled disabledColor="#fff" v-model="item['Nav_Task'].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="ACCEPTANCE_OPINION_SHOW" borderBottom
								@click="handleShowSheet({title: '验收意见', name: 'ACCEPTANCE_OPINION', dataIndex: index})">
									<u--input v-model="item.ACCEPTANCE_OPINION_SHOW"
														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="NOTHROUGH_REASON" borderBottom>
									<u--input disabledColor="#fff" v-model="item.NOTHROUGH_REASON"
														border="none" inputAlign="right"></u--input>
								</u-form-item>
								
							</uni-collapse-item>
						</uni-card>
					</uni-collapse>
				</u--form>
			</view>
		</view>
		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" title="确认删除？"></u-modal>
		<query-selector :show="showPopup" :total="curTotal"  :lists="userLists" :defaultValue="currentOperateUser.NAME"
			@close="handleClosePopup" @search="handleSearchUser" @select="handleSelectedUser" />
		<u-modal :show="showDelModalIndexTask >= 0" @confirm="confirmDelTask" title="确认删除？"></u-modal>
		<query-selector :show="showPopupTask" :total="curTotalTask"  :lists="taskLists" :defaultValue="currentOperateTask.NAME"
			@close="handleClosePopupTask" @search="handleSearchTask" @select="handleSelectedTask" />
		<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>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		extendIgnoreDataRule
	} from '../../../../utils/common'
	import {
		getRequest,
		saveChangeAcceptance,
		getChangeTypeLists,
		getTaskLists
	} from '../../../../services/apply/subPages/SCPT/PTServices'
	import {
		getUserLists
	} from '../../../../services/apply/FOServices/FOServices.js'
	import config from '../../../../config/common'

	export default {
		data() {
			return {
				ID:null,
				TaskID:null,
				tableKey:0,
				curTotal: 0,
				curTotalTask: 0,
				isLoadOK :false,
				showDelModalIndex: undefined,
				userLists: [],
				showDelModalIndexTask: undefined,
				taskLists: [],
				dataModel: {
					TIME:null,
					Nav_Department:{NAME:''},
					Nav_User:{NAME: ''},
				},
				subDataModel: {
					Nav_Tasks:{
						Nav_Task:{NAME:''},
						Nav_User:{NAME:''},
						ACCEPTANCE_OPINION:5
					}
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				currentOperateUser: {},
				showPopup: false,
				currentOperateTask: {},
				showPopupTask: false,
				// rules: {
				// 	'YEAR': {
				// 		type: 'string',
				// 		required: true,
				// 		trigger: ['blur', 'change']
				// 	},
				// },
			}
		},
		onLoad(opt) {
			this.handleGetLicenseGet(opt)
		},
		methods: {
			handleGetLicenseGet(opt) {
				this.TaskID = opt.taskID ? opt.taskID : '00000000-0000-0000-0000-000000000000';
				this.ID = opt.ID ? opt.ID : guid();
				if (opt.ID !== undefined) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "")
				 extendRule(json, 'ID', 1, opt.ID)
				// TODO: id 未获取
				getRequest(json,"/PR/PRChangeAcceptance/GetEdit").then(res => {
					this.dataModel = res
					//数据组装
					let strUserName = ''
					if (res.Nav_Types && res.Nav_Types.length > 0) {
						for (let i = 0; i < res.Nav_Types.length; i++) {
							let user=res.Nav_Types[i].TYPE_ID!=null?res.Nav_Types[i].Nav_Type.NAME:'';
								strUserName += (strUserName.length > 0 ? "</br>" : "") + user;
						}
					}
					this.dataModel.UserNames = strUserName
					this.isLoadOK = true
				})
				}
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				let dataSelect = []
				if (p.name === 'ACCEPTANCE_OPINION') {
					dataSelect = [{
							NAME: '通过',
							ID: 5
						},
						{
							NAME: '不通过',
							ID: 10
						},
						{
							NAME: '不涉及',
							ID: 15
						},
					]
				}
				
				if (dataSelect.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						dataIndex:p.dataIndex,	
						formIndex: p.formIndex,
						columns: [dataSelect]
					}
				} else {
					// 暂无数据
				}
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					dataIndex: undefined,
					formIndex: undefined
				}
			},
			onConfirmPicker(e) {
				const {
					name,
					dataIndex,
					formIndex
				} = this.comPickerInfo
				if(name === "ACCEPTANCE_OPINION")
				{
					this.dataModel.Nav_Tasks[dataIndex].ACCEPTANCE_OPINION = e.value[0].ID
					this.dataModel.Nav_Tasks[dataIndex].ACCEPTANCE_OPINION_SHOW = e.value[0].NAME
				}
				
				this.comPickerInfo.showSheet = false
			},
			handleAddUser() {
				const identifyUser = JSON.parse(JSON.stringify(this.subDataModel.Nav_Tasks))
				this.dataModel.Nav_Tasks.unshift(identifyUser)
			},
			handleDelRowBefore(index) {
				this.showDelModalIndex = index
			},
			confirmDel() {
				this.dataModel.Nav_Tasks.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			cancelDel() {
				// this.dataModel.Nav_JobEventPerson.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			handleSearchUser(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				extendInclude(json, "Nav_Department")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				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.userLists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
						this.curTotal = res.TotalCount
					}
				})
			},
			handleSelectedUser(val) {
				this.showPopup = false
				this.lists = []
				const result = this.dataModel.Nav_Tasks.map((obj) => {
					const {
						Nav_User
					} = obj
					if (Nav_User.CODE === this.currentOperateUser.CODE) {
						return Object.assign({}, obj, {
							Nav_User: val,
							USER_ID:val.ID,
						})
					}
					return obj
				})
			
				this.dataModel.Nav_Tasks = result
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				this.currentOperateUser = user
				this.showPopup = true
				this.handleSearchUser('init')
			},
			handleSearchTask(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				// extendInclude(json, "Nav_Department")
				// extendRule(json, 'ENABLE_STATUS', 1, '0')
				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;
				}
			
				getTaskLists(json).then(res => {
					if (res.IsSuccessful) {
						this.taskLists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
						this.curTotalTask = res.TotalCount
					}
				})
			},
			handleSelectedTask(val) {
				this.showPopupTask = false
				this.lists = []
				const result = this.dataModel.Nav_Tasks.map((obj) => {
					const {
						Nav_Task
					} = obj
					if (Nav_Task.CODE === this.currentOperateTask.CODE) {
						return Object.assign({}, obj, {
							Nav_Task: val,
							TASK_ID:val.ID,
						})
					}
					return obj
				})
			
				this.dataModel.Nav_Tasks = result
			},
			handleClosePopupTask() {
				this.showPopupTask = false
			},
			handleChangeTask(user) {
				this.currentOperateTask = user
				this.showPopupTask = true
				this.handleSearchTask('init')
			},
			submit() {
				// const ele = this.$refs
				// ele['wForm'].validate().then(res => {
					this.dataModel.PUBLISH = "SaveAndNotify";
					if (this.TaskID != "") {
						this.dataModel.TaskID = this.TaskID;
					}
					
					this.dataModel.ID = this.ID;
					this.dataModel.ORG_ID =uni.getStorageSync('orgId')
					saveChangeAcceptance(this.dataModel).then(res => {
						uni.$showMsgFunc('操作成功!', () => {
							// if (this.tableKey == null || this.tableKey == 0) {
							// 	uni.navigateTo({
							// 		url: 'jobTaskLicenseRecord'
							// 	})
							// } else {
								uni.navigateBack()
							// }
						}, 'success', 1000)
					})
				// }).catch(err => {
				// 	uni.$showErrorInfo('请检查必填项，必填项不能为空')
				// })
			},
			uploadFilePromise(url) {
				const appInfoData = uni.getStorageSync('appInfo')
				const userId = appInfoData?.User?.ID || ''
				const orgId = uni.getStorageSync('orgId')
				const tenant = uni.getStorageSync('Tenant') || ''
				const remoteUrl = config.serviceHost('/PF/File/UploadFile')
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: remoteUrl,
						filePath: url,
						fileList: url,
						name: 'file',
						formData: {
							OrgId: orgId
						},
						header: {
							Tenant: tenant,
							userid: userId
						},
						success: (res) => {
							if (res.statusCode === 200) {
								const uploadResult = JSON.parse(res.data)
								if (uploadResult.IsSuccessful) {
									resolve(uploadResult.Data)
								}
							}
						}
					});
				})
			},
			}
	}
</script>

<style scoped>
	@import url("../../../../style/css/editTemplate.css");
	.page-wrap {
		padding: 16px 16px 166px;
	}

	.card {
		margin-bottom: 18px;
	}

	.sub-form {
		margin-bottom: 16px;
	}

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

	.upload-title {
		color: #303133;
		font-size: 15px;
		line-height: 22px;
		padding: 8px 0;
	}

	.page-wrap>>>.u-upload__button {
		margin-bottom: 0;
	}
</style>
