<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 required label="文件名称" prop="FILE_NAME" borderBottom>
						<u--input v-model="dataModel.FILE_NAME" placeholder="请输入文件名称" border="surround" inputAlign="right">
						</u--input>
					</u-form-item>

					<u-form-item label="讨论记录" prop="CONTENT" borderBottom>
					</u-form-item>
					<u--textarea v-model="dataModel.CONTENT" placeholder="请输入讨论记录" border="surround" inputAlign="left">
					</u--textarea>
					<view class="upload-title">附件</view>
					<full-upload v-model="dataModel.Nav_PreOperSchFile"></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 :border="false" accordion>
							<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
								v-for="(item, index) in dataModel.Nav_PreOperSchUser">
								<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>
										<u--input disabled disabledColor="#fff" v-model="item['Nav_User'].CODE"
											border="none" inputAlign="right"></u--input>
									</u-form-item>
									<u-form-item label="岗位" prop="job" borderBottom>
										<u--input disabled disabledColor="#fff"
											v-model="item['Nav_User']['Nav_Person']['Nav_Post'].NAME" border="none"
											inputAlign="right"></u--input>
									</u-form-item>
								</uni-collapse-item>
							</uni-card>
						</uni-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<!-- <query-selector
		  :show="showPopup"
		  :lists="userLists"
		  @close="handleClosePopup"
		  @search="handleSearchUser"
		  @select="handleSelectedUser"
		/> -->
		<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 {
		getRequest,
		getUserLists,
		savePreOperSchRecord
	} from '../../../../services/apply/FOServices/FOServices.js'
	import config from '../../../../config/common'

	export default {
		data() {
			return {
				showDelModalIndex: undefined,
				tableKey:0,
				curTotal: 0,
				isLoadOK: false,
				userLists: [],
				dataModel: {
					FILE_NAME: '',
					CONTENT: '',
					Nav_PreOperSchUser: [],
					Nav_PreOperSchFile:[]
				},
				subDataModel: {
					Nav_PreOperSchUser:{
						USER_ID:null,
						REAL_DEPARTMENT_POST_ID:null,
						Nav_User: {
							Nav_Person: {
								Nav_Post: {
									NAME: ''
								}
							},
							NAME: '',
							CODE: '',
						}
					}
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'FILE_NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				currentOperateUser: {},
				showPopup: false,
			}
		},
		onLoad(opt) {
			this.handleGetPreOperSchGet(opt)
		},
		methods: {
			handleDelRowBefore(index) {
				this.showDelModalIndex = index
			},
			confirmDel() {
				this.dataModel.Nav_PreOperSchUser.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			handleAdd() {
				const persons = JSON.parse(JSON.stringify(this.subDataModel.Nav_PreOperSchUser))
				this.dataModel.Nav_PreOperSchUser.push(persons)
				// this.dataModel.Nav_PreOperSchUser.unshift(this.subDataModel)
			},
			handleGetPreOperSchGet(opt) {
				const orgId = uni.getStorageSync('orgId')
				if (opt.ID !== undefined) {
					this.tableKey = option.tableKey
					const json = initFilter(orgId, "", "")
					extendRule(json, 'ID', 1, opt.id)
					extendInclude(json, 'Nav_PreOperSchFile.Nav_ImgFile');
					extendInclude(json, 'Nav_User');
					extendInclude(json, 'Nav_PreOperSchUser.Nav_User.Nav_Person.Nav_Post');
					// extendIgnoreDataRule(json)
					// TODO: id 未获取
					getRequest(json,"/FO/PreOperSch/Get").then(res => {
						this.dataModel = res
						this.isLoadOK = true
					})
				}
			},
			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
					}
				})
			},
			handleSelectedUser(val) {
				this.showPopup = false
				this.lists = []
				this.currentOperateUser.CODE = val.CODE
				const result = this.dataModel.Nav_PreOperSchUser.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,
							 REAL_DEPARTMENT_POST_ID:val.Nav_Person.POST_ID
						})
					}
					return obj
				})

				this.dataModel.Nav_PreOperSchUser=result
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChangeUser(user) {
				this.currentOperateUser = user
				this.showPopup = true
				this.handleSearchUser('init')
			},
			onConfirmPicker(e) {
				const {
					name,
					dataIndex,
					formIndex
				} = this.comPickerInfo
				if (formIndex === "sForm1") {
					const result = this.dataModel.Nav_PreOperSchUser.map((obj, index) => {
						if (index === dataIndex) {
							return Object.assign({}, obj, {
								// ATTEND_STATUS: e.value[0].ID,
							})
						}
						return obj
					})
					this.dataModel.Nav_PreOperSchUser = result
				} else {

				}
				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 => {
					this.dataModel.PUBLISH = "SaveAndNotify";
					this.dataModel.TaskID = this.TaskID;
					this.dataModel.ID = guid();
					this.dataModel.ORG_ID =uni.getStorageSync('orgId')
					const result = this.dataModel.Nav_PreOperSchFile.map((obj) => {
						// const {
						// 	IMG_FILE_ID,PRE_OPER_SCH_ID,ORG_ID
						// } = obj
							return Object.assign({}, obj, {
								IMG_FILE_ID: obj.responseText.imgFileID,
								PRE_OPER_SCH_ID:this.dataModel.ID,
								ORG_ID:uni.getStorageSync('orgId')
							})
						return obj
					})

					this.dataModel.Nav_PreOperSchFile = result
					savePreOperSchRecord(this.dataModel).then(res => {
						uni.$showMsgFunc('操作成功!', () => {
							// if (this.tableKey == null || this.tableKey == 0) {
							// 	uni.navigateTo({
							// 		url: 'preOperSchRecord'
							// 	})
							// } 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>
