<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">
					<u-form-item label="文件编号" prop="CODE" borderBottom>
						<u--input v-model="dataModel.CODE" disabled  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="文件名称" prop="NAME" borderBottom>
						<u--input v-model="dataModel.NAME"  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="发布人" prop="userName" borderBottom>
						<u--input v-model="dataModel.Nav_User.NAME" disabled  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="发布部门" prop="departmentName" borderBottom>
						<u--input v-model="dataModel.Nav_User.Nav_Department.NAME" disabled  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="发布时间" prop="PUBLISH_DATE" borderBottom>
						<u--input v-model="dataModel.PUBLISH_DATE" disabled  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="文件密级" prop="SecretLevel" borderBottom
					@click="handleShowSheet({title: '文件密级', name: 'SecretLevel', dataIndex: index})">
						<u--input v-model="dataModel.SecretLevel_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="EDITION" borderBottom>
						<u--input v-model="dataModel.EDITION"  border="none" disabledColor="#ffffff"
							inputAlign="right"></u--input>
					</u-form-item>
				</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_Area">
								<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_Department.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_Department'])">
										<u--input disabled disabledColor="#fff" v-model="item['Nav_Department'].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>
										<u--input disabled disabledColor="#fff" v-model="item['Nav_Department'].CODE"
											border="none" inputAlign="right"></u--input>
									</u-form-item>
									<!-- <u-form-item>
										<button type="primary" style="height: 100%;background-color: darkorange;width: 60%;font-size:12px"
											@click="handleDelRowBefore(index)">删除</button>
									</u-form-item> -->
								</uni-collapse-item>
							</uni-card>
						</uni-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<u-sticky offset-top="20">
			<view class="sub-form">
				<uni-collapse :border="false" accordion>
					<uni-card margin="0" spacing="0" padding="0" :is-shadow="true">
						<uni-collapse-item title="任务名称">
							<view class="sub-form-wrap" style="height: 500px; overflow: auto">
								<u--form labelPosition="left" labelWidth="auto" labelAlign="center"
									:model="subDataModel" ref="sForm2" errorType="border-bottom">
									<u-swipe-action>
										<u-swipe-action-item style="margin-bottom: 16px;" :options="options"
											v-for="(item, index) in dataModel.Details">
											<uni-card margin="0" spacing="0" :is-shadow="false"
												style="margin-bottom: 10px;">
												<u-form-item label="作业名称" prop="stepName" borderBottom>
													<u--input disabled disabledColor="#fff" v-model="item.Nav_OperationStep.NAME"
																		border="none" inputAlign="right"></u--input>
													
												</u-form-item>
												<u-form-item label="作业周期" prop="CYCLE_TYPE" borderBottom>
													<u--input disabled disabledColor="#fff" v-model="item.CYCLE_TYPE_SHOW"
																		border="none" inputAlign="right"></u--input>
													
												</u-form-item>
												<u-form-item label="作业前确认" prop="SafeConfirmsStr" borderBottom>
												</u-form-item>
													<u--textarea v-model="item.SafeConfirmsStr"
																	border="none" inputAlign="right"></u--textarea>
												<u-form-item label="作业流程及措施" prop="SafeMeasuresStr" borderBottom>
												</u-form-item>
												<u--textarea v-model="item.SafeMeasuresStr"
																	border="none" inputAlign="right"></u--textarea>
												<u-form-item label="作业后处理措施" prop="DealMeasuresStr" borderBottom>
												</u-form-item>
													<u--textarea v-model="item.DealMeasuresStr"
																	border="none" inputAlign="right"></u--textarea>
												<u-form-item label="作业许可类别" prop="WorkPermitType" borderBottom>
													<u--input disabled disabledColor="#fff" v-model="item['Nav_WorkPermitType'].NAME"
																		border="none" inputAlign="right"></u--input>
													
												</u-form-item>
												<u-form-item label="审批层级" prop="AUDIT_LEVEL" borderBottom>
													<u--input disabled disabledColor="#fff" v-model="item.AUDIT_LEVEL_SHOW"
																		border="none" inputAlign="right"></u--input>
													
												</u-form-item>
												<u-form-item label="附件" prop="files" borderBottom>
												</u-form-item>
												<u-link v-for="itemChild in item.files" :href="itemChild.url" :text="itemChild.name">
												</u-link>
											</uni-card>
										</u-swipe-action-item>
									</u-swipe-action>
								</u--form>
							</view>
						</uni-collapse-item>
					</uni-card>
				</uni-collapse>
			</view>
		</u-sticky>
		
		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" 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" />
		<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 {
		getFilePublishGet,
		getWorkPermitTypeLists,
		saveFilePublishRecord
	} from '../../../../services/apply/HMServices/HMServices.js'
	import {
		getDepartmentLists,
	} 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: {
					CODE:'',
					NAME:'',
					Nav_User: {
						NAME: '',
						Nav_Department: {
							NAME: '',
						},
					},
					SecretLevel_SHOW:'',
					// Nav_Area:{
					// 	Nav_Department: {
					// 		NAME: '',
					// 		CODE: '',
					// 	},
					// },
				},
				subDataModel: {
					Nav_Area:{
						Nav_Department: {
							NAME: '',
							CODE: '',
						},
					},
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				currentOperateUser: {},
				showPopup: false,
				rules: {
					'CODE': {
						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 未获取
				getFilePublishGet(json).then(res => {
					this.dataModel = res.Data
					let strDetail = []
					if (res.Data.Nav_License_Details && res.Data.Nav_License_Details.length > 0) {
						for (let i = 0; i < res.Data.Nav_License_Details.length; i++) {
							if (res.Data.Nav_License_Details[i].CYCLE_TYPE == 0) {
								res.Data.Nav_License_Details[i].CYCLE_TYPE_SHOW = "需求作业"
							} else {
								res.Data.Nav_License_Details[i].CYCLE_TYPE_SHOW="每日作业"
							}
							if (res.Data.Nav_License_Details[i].AUDIT_LEVEL == 0) {
								res.Data.Nav_License_Details[i].AUDIT_LEVEL_SHOW = "无审批层级"
							} else if(res.Data.Nav_License_Details[i].AUDIT_LEVEL == 1){
								res.Data.Nav_License_Details[i].AUDIT_LEVEL_SHOW="一级审批"
							}else if(res.Data.Nav_License_Details[i].AUDIT_LEVEL == 2){
								res.Data.Nav_License_Details[i].AUDIT_LEVEL_SHOW="二级审批"
							}else if(res.Data.Nav_License_Details[i].AUDIT_LEVEL == 3){
								res.Data.Nav_License_Details[i].AUDIT_LEVEL_SHOW="三级审批"
							}else if(res.Data.Nav_License_Details[i].AUDIT_LEVEL == 4){
								res.Data.Nav_License_Details[i].AUDIT_LEVEL_SHOW="四级审批"
							}
							
							if(res.Data.Nav_License_Details[i].WORK_PERMIT_TYPE_ID ===null)
							{
								res.Data.Nav_License_Details[i].Nav_WorkPermitType={CODE:'',NAME:''}
							}
							let strconfirmFiles = [{
								url: '',
								name:''
							}]
							let details=res.Data.Nav_License_Details[i];
							if (details.Nav_Files && details.Nav_Files.length > 0) {
								for (let j = 0; j < details.Nav_Files.length; j++) {
								strconfirmFiles.push({
								url: config.uni_app_web_local_api_url+ details.Nav_Files[j].Nav_ImgFile.Nav_File.FILE_PATH,
								name:details.Nav_Files[j].Nav_ImgFile.FILE_NAME
								})
								details.files = strconfirmFiles
								}
							}
							strDetail.push(res.Data.Nav_License_Details[i]);
						}
					}
					if (res.Data.Nav_Crucial_Details && res.Data.Nav_Crucial_Details.length > 0) {
						for (let i = 0; i < res.Data.Nav_Crucial_Details.length; i++) {
							if (res.Data.Nav_Crucial_Details[i].CYCLE_TYPE == 0) {
								res.Data.Nav_Crucial_Details[i].CYCLE_TYPE_SHOW = "需求作业"
							} else {
								res.Data.Nav_Crucial_Details[i].CYCLE_TYPE_SHOW="每日作业"
							}
							if (res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL == 0) {
								res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL_SHOW = "无审批层级"
							} else if(res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL == 1){
								res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL_SHOW="一级审批"
							}else if(res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL == 2){
								res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL_SHOW="二级审批"
							}else if(res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL == 3){
								res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL_SHOW="三级审批"
							}else if(res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL == 4){
								res.Data.Nav_Crucial_Details[i].AUDIT_LEVEL_SHOW="四级审批"
							}
							
							if(res.Data.Nav_Crucial_Details[i].WORK_PERMIT_TYPE_ID ===null)
							{
								res.Data.Nav_Crucial_Details[i].Nav_WorkPermitType={CODE:'',NAME:''}
							}
							let strconfirmFiles = [{
								url: '',
								name:''
							}]
							let details=res.Data.Nav_Crucial_Details[i];
							if (details.Nav_Files && details.Nav_Files.length > 0) {
								for (let j = 0; j < details.Nav_Files.length; j++) {
								strconfirmFiles.push({
								url: config.uni_app_web_local_api_url+ details.Nav_Files[j].Nav_ImgFile.Nav_File.FILE_PATH,
								name:details.Nav_Files[j].Nav_ImgFile.FILE_NAME
								})
								details.files = strconfirmFiles
								}
							}
							strDetail.push(res.Data.Nav_Crucial_Details[i]);
						}
					}
					if (res.Data.Nav_Ordinary_Details && res.Data.Nav_Ordinary_Details.length > 0) {
						for (let i = 0; i < res.Data.Nav_Ordinary_Details.length; i++) {
							if (res.Data.Nav_Ordinary_Details[i].CYCLE_TYPE == 0) {
								res.Data.Nav_Ordinary_Details[i].CYCLE_TYPE_SHOW = "需求作业"
							} else {
								res.Data.Nav_Ordinary_Details[i].CYCLE_TYPE_SHOW="每日作业"
							}
							if (res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL == 0) {
								res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL_SHOW = "无审批层级"
							} else if(res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL == 1){
								res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL_SHOW="一级审批"
							}else if(res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL == 2){
								res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL_SHOW="二级审批"
							}else if(res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL == 3){
								res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL_SHOW="三级审批"
							}else if(res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL == 4){
								res.Data.Nav_Ordinary_Details[i].AUDIT_LEVEL_SHOW="四级审批"
							}
							
							if(res.Data.Nav_Ordinary_Details[i].WORK_PERMIT_TYPE_ID ===null)
							{
								res.Data.Nav_Ordinary_Details[i].Nav_WorkPermitType={CODE:'',NAME:''}
							}
							let strconfirmFiles = [{
								url: '',
								name:''
							}]
							let details=res.Data.Nav_Ordinary_Details[i];
							if (details.Nav_Files && details.Nav_Files.length > 0) {
								for (let j = 0; j < details.Nav_Files.length; j++) {
								strconfirmFiles.push({
								url: config.uni_app_web_local_api_url+ details.Nav_Files[j].Nav_ImgFile.Nav_File.FILE_PATH,
								name:details.Nav_Files[j].Nav_ImgFile.FILE_NAME
								})
								details.files = strconfirmFiles
								}
							}
							strDetail.push(res.Data.Nav_Ordinary_Details[i]);
						}
					}
					// this.dataModel.UserNames = strUserName
					// this.dataModel.UserFiles = strUserFiles
					this.dataModel.Details = strDetail
					this.isLoadOK = true
				})
			},
			handleDelRowBefore(index) {
				this.showDelModalIndex = index
			},
			confirmDel() {
				this.dataModel.Nav_Area.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			handleAdd() {
				const identifyUser = JSON.parse(JSON.stringify(this.subDataModel.Nav_Area))
				this.dataModel.Nav_Area.unshift(identifyUser)
			},
			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;
				}
			
				getDepartmentLists(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_Area.map((obj) => {
					const {
						Nav_Department,DEPARTMENT_ID,
					} = obj
					if (Nav_Department.CODE === this.currentOperateUser.CODE) {
						return Object.assign({}, obj, {
							Nav_Department: val,
							DEPARTMENT_ID:val.ID,
						})
					}
					return obj
				})
				
				this.dataModel.Nav_Area=result
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				this.currentOperateUser = user
				this.showPopup = true
				this.handleSearchUser('init')
			},
			//下拉数据加载
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				let dataSelect = []
				if (p.name === 'SecretLevel') {
					dataSelect = [{
							NAME: '普通',
							ID: 0
						},
						{
							NAME: '机密',
							ID: 1
						},
						{
							NAME: '绝密',
							ID: 2
						}
					]
				}
				
				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 === "SecretLevel")
				{
					this.dataModel.SecretLevel = e.value[0].ID
					this.dataModel.SecretLevel_SHOW = e.value[0].NAME
				}
				this.comPickerInfo.showSheet = false
			},
			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')
					saveFilePublishRecord(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>
