<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="PERFORM_STATUS_SHOW" borderBottom
					@click="handleShowSheet({title: '执行状况', name: 'PERFORM_STATUS', dataIndex: index})">
						<u--input v-model="dataModel.PERFORM_STATUS_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="DESCRIPTION" borderBottom>
						<u--input v-model="dataModel.DESCRIPTION" disabled disabledColor="#ffffff" placeholder="请输入变化描述" border="none" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="变化后执行任务" prop="TASK" borderBottom>
						<u--input v-model="dataModel.Nav_Task.NAME" disabled disabledColor="#ffffff" placeholder="请输入变化带来的风险" border="none" inputAlign="right">
						</u--input>
					</u-form-item>
					<!-- <u-form-item label="执行情况" prop="PERFORM_DESCRIPTION" borderBottom>
						<u--input v-model="dataModel.PERFORM_DESCRIPTION" disabled disabledColor="#ffffff" placeholder="请输入执行情况" border="none"
							inputAlign="right"></u--input>
					</u-form-item> -->
					<u-form-item label="未执行原因" prop="REASON" borderBottom>
						<u--input v-model="dataModel.REASON" disabledColor="#ffffff" placeholder="请输入未执行原因" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item class="custom-form-item" label="执行人员" prop="TaskUser" :borderBottom="false"
					@click="handleQuerySelect({title: '执行人员', name: 'TaskUser', isMultiple: true})">
						<view slot="right" class="custom-form-item-right">
							<view class="multi">
								<u--text v-for="(i, k) in dataModel.Nav_Users" :key="k" class="item" :text="i.NAME"></u--text>
							</view>
							<u-icon class="icon" name="arrow-down">
							</u-icon>
						</view>
					</u-form-item>
					<u-form-item label="变化类型" prop="TypeNames" borderBottom>
					</u-form-item>
					<u--textarea autoHeight type="textarea" v-html="dataModel.TypeNames" border="none"
						inputAlign="left">
					</u--textarea>
					<view class="upload-title">附件</view>
					<full-upload v-model="dataModel.Nav_Files"></full-upload>
				</u--form>
			</uni-card>
		</view>
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker"
			@close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<query-selector :defaultChecked ="qsCom.defaultValue" :multiple="qsCom.isMultiple" :total="curTotal" :show="qsCom.show" :lists="qsCom.lists"
			@close="onCloseQS" @search="onSearchQS" @select="onSelectedQS" />
		<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,
		saveChangeImplement
	} 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,
				isLoadOK :false,
				showDelModalIndex: undefined,
				userLists: [],
				dataModel: {
					Nav_Department:{NAME:''},
					Nav_User:{NAME:''},
					Nav_Task:{NAME:''},
				},
				subDataModel: {
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				qsCom: {
					show: false,
					lists: [],
					title: '',
					// dataIndex: undefined,
					// formIndex: undefined,
					isMultiple: false,
					defaultValue: [],
					name: ''
				},
				currentOperateUser: {},
				showPopup: false,
				// rules: {
				// 	'YEAR': {
				// 		type: 'string',
				// 		required: true,
				// 		trigger: ['blur', 'change']
				// 	},
				// },
			}
		},
		onLoad(opt) {
			this.handleGetLicenseGet(opt)
		},
		methods: {
			handleGetLicenseGet(opt) {
				this.TaskID = opt.taskID ? opt.taskID : null;
				this.ID = opt.ID ? opt.ID : null;
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "")
				 extendRule(json, 'ID', 1, opt.ID)
				// TODO: id 未获取
				getRequest(json,"/PR/PRChangeTaskImplement/GetUserEdit").then(res => {
					this.dataModel = res
					//数据组装
					let strTypeName = ''
					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:'';
								strTypeName += (strTypeName.length > 0 ? "</br>" : "") + user;
						}
					}
					this.dataModel.TypeNames = strTypeName
					this.isLoadOK = true
				})
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				let dataSelect = []
				if (p.name === 'PERFORM_STATUS') {
					dataSelect = [{
							NAME: '不需执行',
							ID: 5
						},
						{
							NAME: '已执行',
							ID: 10
						},
					]
				}
				
				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 === "PERFORM_STATUS")
				{
					this.dataModel.PERFORM_STATUS = e.value[0].ID
					this.dataModel.PERFORM_STATUS_SHOW = e.value[0].NAME
				}
				
				this.comPickerInfo.showSheet = false
			},
			async handleQuerySelect(opt) {
				let column = await this.handleGet(opt, 'init')
			
				if (column && column.length) {
					this.qsCom = {
						...this.qsCom,
						show: true,
						title: opt.title,
						name: opt.name,
						// formIndex: opt.formIndex,
						// dataIndex: opt.dataIndex,
						isMultiple: opt.isMultiple,
						lists: column
					}
				} else {
					// 暂无数据
				}
			},
			async handleGet(opt, value, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, '', "", 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 = []
				if (opt.name === 'TaskUser') {
					const raw = await getUserLists(json).then(res => {
						this.curTotal = res.TotalCount
						return res.Data
					})
					result = raw.map(item => {
						return {
							...item,
							name: item?.NAME,
							id: item?.ID
						}
					})
				}
				return result
			},
			onSelectedQS(val) {debugger
				const { name } = this.qsCom
					
					if (name === 'TaskUser') {
						const dp = val.map(item => {
							return {
								ID: guid(),
								CHANGE_TASK_IMPLEMENT_ID:this.ID || guid(),
								ORG_ID: uni.getStorageSync('orgId'),
								USER_ID: item.ID,
								NAME: item.NAME
							}
						})
						this.dataModel.Nav_Users = dp
					}
				this.qsCom.show = false
			},
			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 handleQuerySelect(opt) {
				let column = await this.handleGet(opt, 'init')
			
				if (column && column.length) {
					this.qsCom = {
						...this.qsCom,
						show: true,
						title: opt.title,
						name: opt.name,
						// formIndex: opt.formIndex,
						// dataIndex: opt.dataIndex,
						isMultiple: opt.isMultiple,
						lists: column
					}
				} else {
					// 暂无数据
				}
			},
			onCloseQS() {
				this.qsCom = {
					show: false,
					lists: [],
					title: '',
					name: '',
					formIndex: undefined,
					isMultiple: false,
					dataIndex: undefined
				}
			},
			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')
					const result = this.dataModel.Nav_Files.map((obj) => {
						// const {
						// 	IMG_FILE_ID,PRE_OPER_SCH_ID,ORG_ID
						// } = obj
							return Object.assign({}, obj, {
								IMG_FILE_ID: obj.responseText.imgFileID,
								CHANGE_TASK_IMPLEMENT_ID:this.dataModel.ID,
								ORG_ID:uni.getStorageSync('orgId')
							})
						return obj
					})
					
					this.dataModel.Nav_Files = result
					saveChangeImplement(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>
