<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" :rules="rules"
					ref="wForm" errorType="border-bottom" :borderBottom="false" :border="false">
					<u-form-item label="审核意见：" prop="CONTEXT" borderBottom v-if="dataModel.IS_PUBLISH==9">
					</u-form-item>
					<u--textarea v-html="dataModel.CONTEXT" border="surround" v-if="dataModel.IS_PUBLISH==9"
						disabled></u--textarea>
					<u-form-item label="发起人" prop="createUser" borderBottom required>
							<u--text :text="dataModel.Nav_CreateUser.NAME" align="right"></u--text>
					</u-form-item>
					<view class="upload-title">附件</view>
					<full-upload v-model="dataModel.Nav_Files"></full-upload>
				</u--form>
			</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">
							<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="sForm1">
						<uni-collapse accordion>
							<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
								v-for="(item, index) in dataModel.Nav_IdentifyUser">
								<uni-collapse-item title-border="none" :show-arrow="false" :border="false" :open="true">
									<view slot="title" class="custom-collapse-title">
										<view class="down">
											<uni-icons type="bottom"></uni-icons>
										</view>
										<view class="text">{{index + 1 + '. ' +item.Nav_User.NAME}}</view>
										<view class="action" @click.stop>
											<u-icon @click="handleDelRowBefore(index)" class="icon" name="trash" color="#ff4d4f" size="21"></u-icon>
										</view>
									</view>
									<u-form-item label="人员姓名" prop="personName" 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="personNo" :borderBottom="false">
										<u--input disabled disabledColor="#fff" v-model="item['Nav_User'].CODE"
											border="none" inputAlign="right"></u--input>
									</u-form-item>
								</uni-collapse-item>
							</uni-card>
						</uni-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<view class="sub-form">
			<view class="sub-form-wrap">
				<view class="sub-form-btns">
					<view class="sub-form-btn" @click="handleAddStep">
						<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="sForm2">
					<uni-collapse accordion>
						<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
											v-for="(item, index) in dataModel.Nav_Details">
							<uni-collapse-item title-border="none" :show-arrow="false" :border="false" :open="true">
								<view slot="title" class="custom-collapse-title">
									<view class="down">
										<uni-icons type="bottom"></uni-icons>
									</view>
									<view class="text">{{index + 1 + '. ' +item.Nav_OperationStep.NAME}}</view>
									<view class="action" @click.stop>
										<u-icon @click="handleDelRowBeforeStep(index)" class="icon" name="trash" color="#ff4d4f" size="21"></u-icon>
									</view>
								</view>
								<u-form-item label="作业名称" prop="StepName" borderBottom
								 @click="handleQuerySelect({title: '作业名称', name: 'Nav_OperationStep', formIndex: 'Nav_Details', dataIndex: index})">
									<u--input disabled disabledColor="#fff" v-model="item['Nav_OperationStep'].NAME"
														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="CYCLE_TYPE_SHOW" borderBottom
								@click="handleShowSheet({title: '作业周期', name: 'CYCLE_TYPE',index})">
									<u--input disabled disabledColor="#fff" v-model="item.CYCLE_TYPE_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 class="custom-form-item" label="岗位" prop="DetailPost" :borderBottom="false"
								@click="handleQuerySelect({title: '岗位', name: 'DetailPost', formIndex: 'Nav_Details', dataIndex: index, isMultiple: true})">
									<view slot="right" class="custom-form-item-right">
										<view class="multi">
											<u--text v-for="(i, k) in item.Nav_DetailPost" :key="k" class="item" :text="k + 1 + '. ' + i.POST_NAME"></u--text>
										</view>
										<u-icon class="icon" name="arrow-down">
										</u-icon>
									</view>
								</u-form-item>
							</uni-collapse-item>
						</uni-card>
					</uni-collapse>
				</u--form>
			</view>
		</view>

		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" showCancelButton @cancel="showDelModalIndex = undefined" title="确认删除？"></u-modal>
		<u-modal :show="showDelModalIndexStep >= 0" @confirm="confirmDelStep" showCancelButton @cancel="showDelModalIndexStep = undefined" title="确认删除？"></u-modal>
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker"
			@close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<query-selector :show="showPopup" :total="curTotal" :lists="userLists" :defaultValue="currentOperateUser.NAME"
			@close="handleClosePopup" @search="handleSearchUser" @select="handleSelectedUser" />
		<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 {
		getIdentifyGet,
		getIdentitySign,
		getOperationStep,
		saveIdentifyRecord,
		getDetailPostLists,
	} from '../../../../services/apply/HMServices/HMServices.js'
	import {
		getUserLists,
	} from '../../../../services/apply/FOServices/FOServices.js'
	import config from '../../../../config/common'

	export default {
		data() {
			return {
				ID:null,
				showDelModalIndex: undefined,
				showDelModalIndexStep: undefined,
				tableKey:0,
				isLoadOK :false,
				curTotal: 0,
				userLists: [],
				stepLists:[],
				dataModel: {
					// CODE: uni.getStorageSync('appInfo')?.User?.NAME || '' ,
					Nav_IdentifyUser:[],
					Nav_Details:[],
					Nav_CreateUser:{
						NAME:uni.getStorageSync('appInfo')?.User?.NAME || ''
					}
				},
				subDataModel: {
					Nav_IdentifyUser:{
						Nav_User: {
							NAME: '',
							CODE: '',
						},
					},
					Nav_Details:{
						CYCLE_TYPE:0,
						CYCLE_TYPE_SHOW:"需求作业",
						Nav_OperationStep:{NAME:''},
						Nav_DetailPost: []
					}
				},
				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: ''
				},
				rules: {
					'Nav_CreateUser.NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
				},
				currentOperateUser: {},
				showPopup: false,
				currentOperateStep: {},
				showPopupStep: false,
			}
		},
		onLoad(opt) {
			this.handleGetIdentityGet(opt)
		},
		methods: {
			handleGetIdentityGet(opt) {
				if (opt.ID !== undefined) {
					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)
					getIdentifyGet(json).then(res => {
						this.dataModel = res.Data
						// //数据组装
						// let strUserFiles = [{
						// 	url: '',
						// 	name:''
						// }]
						// if (res.Data.Nav_Files && res.Data.Nav_Files.length > 0) {
						// 	for (let i = 0; i < res.Data.Nav_Files.length; i++) {
						// 		strUserFiles.push({
						// 			url: config.uni_app_web_local_api_url+res.Data.Nav_Files[i].Nav_ImgFile.FILE_PATH,
						// 			name:res.Data.Nav_Files[i].Nav_ImgFile.FILE_NAME
						// 		})
						// 	}
						// }
						// //数据组装
						// let strUserName = ''
						// if (res.Data.Nav_IdentifyUser && res.Data.Nav_IdentifyUser.length > 0) {
						// 	for (let i = 0; i < res.Data.Nav_IdentifyUser.length; i++) {
						// 		if (res.Data.Nav_IdentifyUser[i].DEAL_STATUS == 0) {
						// 			strUserName += (strUserName.length > 0 ? "&nbsp;&nbsp;" : "") + "<text style='color:red'>" +
						// 				res.Data.Nav_IdentifyUser[i].Nav_User.NAME + "</text>";
						// 		} else {
						// 			let user=res.Data.Nav_IdentifyUser[i].USER_ID!=null?res.Data.Nav_IdentifyUser[i].Nav_User.NAME:'';
						// 			strUserName += (strUserName.length > 0 ? "&nbsp;&nbsp;" : "") + user;
						// 		}

						// 	}
						// }
						if (res.Data.Nav_Details && res.Data.Nav_Details.length > 0) {
							for (let i = 0; i < res.Data.Nav_Details.length; i++) {
								if (res.Data.Nav_Details[i].CYCLE_TYPE == 0) {
									res.Data.Nav_Details[i].CYCLE_TYPE = 0
									res.Data.Nav_Details[i].CYCLE_TYPE_SHOW ="需求作业"
								} else {
									res.Data.Nav_Details[i].CYCLE_TYPE=10
									res.Data.Nav_Details[i].CYCLE_TYPE_SHOW ="每日作业"
								}
								if(res.Data.Nav_Details[i].Nav_DetailPost)
								{
									res.Data.Nav_Details[i].Nav_DetailPost.map(t=>{
										t.POST_NAME = t.Nav_Post?.NAME
									})
								}
							}
						}
						// this.dataModel.UserNames = strUserName
						// this.dataModel.UserFiles = strUserFiles
						this.isLoadOK = true
					})
				}

			},
			handleDelRowBefore(index) {
				this.showDelModalIndex = index
			},
			handleDelRowBeforeStep(index) {
				this.showDelModalIndexStep = index
			},
			confirmDel() {
				this.dataModel.Nav_IdentifyUser.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			confirmDelStep() {
				this.dataModel.Nav_Details.splice(this.showDelModalIndexStep, 1)
				this.showDelModalIndexStep = undefined
			},
			handleAdd() {
				const identifyUser = JSON.parse(JSON.stringify(this.subDataModel.Nav_IdentifyUser))
				this.dataModel.Nav_IdentifyUser.unshift(identifyUser)
			},
			handleAddStep() {
				const details = JSON.parse(JSON.stringify(this.subDataModel.Nav_Details))
				this.dataModel.Nav_Details.unshift(details)
			},
			handleSearchUser(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				extendInclude(json, "Nav_Person.Nav_Post")
				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
					}
				})
			},
			handleSearchStep(val) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME")
				const tempGroup = initFilterGroup(false);
				extendGroupRule(tempGroup, 'NAME', 9, val)
				extendFilterGroup(json, tempGroup);

				getOperationStep(json).then(res => {
					if (res.IsSuccessful) {
						this.stepLists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
								code: i.CODE
							}
						})
					}
				})
			},
			handleSelectedUser(val) {
				this.showPopup = false
				this.lists = []
				this.currentOperateUser.CODE = val.CODE
				const result = this.dataModel.Nav_IdentifyUser.map((obj) => {
					const {
						Nav_User,USER_ID,REAL_DEPARTMENT_POST_ID
					} = obj
					if (Nav_User.CODE === this.currentOperateUser.CODE) {
						return Object.assign({}, obj, {
							Nav_User: val,
							USER_ID:val.ID,
						})
					}
					return obj
				})

				this.dataModel.Nav_IdentifyUser=result
			},
			handleClosePopup() {
				this.showPopup = false
			},
			onCloseQS() {
				this.qsCom = {
					show: false,
					lists: [],
					title: '',
					name: '',
					formIndex: undefined,
					isMultiple: false,
					dataIndex: undefined
				}
			},
			handleChangeUser(user) {
				this.currentOperateUser = user
				this.showPopup = true
				this.handleSearchUser('init')
			},
			async handleShowSheet(p) {
				let column = []
				if (p.name === 'CYCLE_TYPE')
					{
						column = [{
								NAME: '需求作业',
								ID: 0
							},
							{
								NAME: '每日作业',
								ID: 10
							}
						]
					}
				if (p.name === 'DetailPost')
					{
						column = await getDetailPostLists(json).then(res => {
							return res
						})
					}
				if (column.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						dataIndex:p.index,
						formIndex: p.formIndex,
						columns: [column]
					}
				} else {
					// 暂无数据
				}
			},
			onSelectedQS(val) {
				const { name, formIndex, dataIndex } = this.qsCom
				if (formIndex) {
					// this.subForms[formIndex][name] = val.NAME
					if (!this.dataModel[formIndex]) {
						this.dataModel[formIndex] = []
					}
					if (!this.dataModel[formIndex][dataIndex]) {
						this.dataModel[formIndex][dataIndex] = {}
					}
					// this.dataModel[formIndex][dataIndex][name] = val.ID
					// this.dataModel[formIndex][dataIndex][name + '_name'] = val.NAME
					if (name === 'DetailPost') {
						const dp = val.map(item => {
							return {
								ID: guid(),
								JOBTASK_IDENTIFY_ID:this.dataModel.ID || guid(),
								ORG_ID: uni.getStorageSync('orgId'),
								POST_ID: item.ID,
								POST_NAME: item.NAME
							}
						})
						this.dataModel[formIndex][dataIndex].Nav_DetailPost = dp
						// this.dataModel[formIndex][dataIndex].Nav_DetailPost = {
						// 	Nav_Post: val
						// }
					}
					if (name === 'Nav_OperationStep') {
						this.dataModel[formIndex][dataIndex].Nav_OperationStep = val
						this.dataModel[formIndex][dataIndex].OPERATION_STEP_ID = val.ID
					}
				} else {
					this.dataModel[name] = val.ID
					this.dataModel[name + '_name'] = val.NAME
				}
				this.qsCom.show = false
				// this.qsCom.defaultValue = val
			},
			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 {
					// 暂无数据
				}
			},
			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 === 'DetailPost') {
					const raw = await getDetailPostLists(json).then(res => {
						this.curTotal = res.TotalCount
						return res.Data
					})
					result = raw.map(item => {
						return {
							...item,
							name: item?.NAME,
							id: item?.ID
						}
					})
				}
				if (opt.name === 'Nav_OperationStep') {
					json.Sort = "NAME"
					// const tempGroup = initFilterGroup(false);
					// extendGroupRule(tempGroup, 'NAME', 9, value)
					// extendFilterGroup(json, tempGroup);
					const raw = await getOperationStep(json).then(res => {
						this.curTotal = res.TotalCount
						return res.Data
					})
					result = raw.map(item => {
						return {
							...item,
							name: item?.NAME,
							id: item?.ID
						}
					})
				}
				return result
			},
			onConfirmPicker(e) {
				const {
					name,
					dataIndex,
					formIndex
				} = this.comPickerInfo
				if (formIndex === "sForm1") {
					const result = this.dataModel.Nav_IdentifyUser.map((obj, index) => {
						if (index === dataIndex) {
							return Object.assign({}, obj, {
								// ATTEND_STATUS: e.value[0].ID,
							})
						}
						return obj
					})
					this.dataModel.Nav_IdentifyUser = result
				} else {

				}
				if(name === 'CYCLE_TYPE')
				{
					this.dataModel.Nav_Details[dataIndex].CYCLE_TYPE = e.value[0].ID
					this.dataModel.Nav_Details[dataIndex].CYCLE_TYPE_SHOW = e.value[0].NAME
				}
				this.comPickerInfo.showSheet = false
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					dataIndex: undefined,
					formIndex: undefined
				}
			},
			handleDelAction({ name }) {
				uni.showModal({
					title: '是否删除数据？',
					success: (res) => {
						if (res.confirm) {

						}
					}
				})
			},
			submit() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					// if(this.dataModel.CODE === uni.getStorageSync('appInfo')?.User?.NAME)
					// {
					// 	entity.CODE = ""
					// }
					this.dataModel.PUBLISH = "SaveAndNotify";
					if (this.TaskID&&this.TaskID !== null) {
						this.dataModel.TaskID = this.TaskID;
					}
					else
					{this.dataModel.TaskID = '00000000-0000-0000-0000-000000000000';}
					this.dataModel.ID = this.ID ? this.ID : guid();
					this.dataModel.ORG_ID =uni.getStorageSync('orgId')
					if(this.dataModel.Nav_Files)
					{
						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,
									JOBTASK_IDENTIFY_ID:this.dataModel.ID,
									ORG_ID:uni.getStorageSync('orgId')
								})
							return obj
						})
						this.dataModel.Nav_Files = result
					}
					const resultDeal = this.dataModel.Nav_Details.map((obj, index) => {

						// if (obj.IS_CONFIRM === "是") {
						// 	return Object.assign({}, obj, {
						// 		IS_CONFIRM: true,
						// 		Nav_Files:navFiles
						// 	})
						// }
						// else
						// {
							return Object.assign({}, obj, {
								CYCLE_TYPE: obj.CYCLE_TYPE,
								OPERATION_STEP_ID: obj.OPERATION_STEP_ID,
								Nav_OperationStep:obj.Nav_OperationStep,
								Nav_DetailPost:obj.Nav_DetailPost
							})
						// }
						return obj
					})
					this.dataModel.Nav_Details = resultDeal
					saveIdentifyRecord(this.dataModel).then(res => {
						uni.$showMsgFunc('操作成功!', () => {
							// if (this.tableKey == null || this.tableKey == 0) {
							// 	uni.navigateTo({
							// 		url: 'jobTaskIdentityRecord'
							// 	})
							// } 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>
