<template>
	<view class='base-info'>
		<view class="form-user">
			<u--form labelWidth="auto" labelAlign="left" :model="dataModel" :rules="rules" ref="form" errorType="border-bottom" class='info-form'>
				<u-form-item label="姓名" prop="name" border-bottom>
					<text>{{userInfo.UserName}}</text>
				</u-form-item>
				<u-form-item label="编码" prop="code" border-bottom>
					<text>{{userInfo.UserCode}}</text>
				</u-form-item>
				<u-form-item label="手机" prop="phone" border-bottom>
					<u--input v-model="userInfo.PHONE" border="none" inputAlign="right"></u--input>
					<!-- <text>{{userInfo.PHONE}}</text> -->
				</u-form-item>
				<u-form-item label="身份证" prop="phone" border-bottom>
					<u--input v-model="userInfo.ID_CARD" border="none" inputAlign="right"></u--input>
					<!-- <text>{{userInfo.ID_CARD}}</text> -->
				</u-form-item>
				<!-- <u-form-item label="组织结构" prop="department" border-bottom>
					<text>{{userInfo.DepartmentName}}</text>
				</u-form-item> -->
				<u-form-item label="组织结构" prop="job" @click="handleChange">
					<!-- @click="handleShowSheet({title: '作业名称', name: 'stepName'})" -->
					<u--input disabledColor="#fff" v-model="(userInfo.Nav_Department||{}).NAME" disabled placeholder="请选择组织" suffixIcon="arrow-right" suffixIconStyle="font-size:12px" fontSize="14px"
						customStyle="margin:0px;display:flex;padding:3px 9px" border="none"  inputAlign="right">
					</u--input>
				
				</u-form-item>
				<!-- <u-form-item label="班组" prop="post" border-bottom>
					<text>{{userInfo.TeamName}}</text>
				</u-form-item> -->
				<!-- <u-form-item label="岗位" prop="job">
					<text>{{userInfo.PostName}}</text>
				</u-form-item> -->
				<u-form-item label="岗位" prop="job" @click="handleChangeStep">
					<!-- @click="handleShowSheet({title: '作业名称', name: 'stepName'})" -->
					<u--input disabledColor="#fff" v-model="(userInfo.Nav_Person.Nav_Post||{}).NAME" disabled placeholder="请选择岗位" suffixIcon="arrow-right" suffixIconStyle="font-size:12px" fontSize="14px"
						customStyle="margin:0px;display:flex;padding:3px 9px" border="none"  inputAlign="right">
					</u--input>
				
				</u-form-item>
				<u-form-item label="是否接收短信" >
					<u-switch v-model="userInfo.ISGETMSG"  @change="changeSwitch"></u-switch>
				</u-form-item>
				
				<!-- <u-form-item label="角色" prop="role">
					<text>{{userInfo.RoleName}}</text>
				</u-form-item> -->
			</u--form>
		</view>
		<view class="assign">
			<view class='top-label'>签名</view>
			<view class="assign-again" @click="reUpload">
				<u-button type="primary" icon="download" text="上传签名" size="small"></u-button>
				<!-- <view class="top-label-assign">上传签名</view>
				<view>
					<u-icon name="download" size="20px"></u-icon>
				</view> -->
			</view>
		</view>

		<view class="signature-img">
			<image style="width: 100%" mode="widthFix" :src="userInfo.SignaturePhoto"></image>
		</view>
		<button @click="formSubmit" type="primary" class='save-btn'>确定</button>

		<u-popup :show="show" mode="center" :customStyle="{width: '100%', height: '100%'}" @open="() => {}" @close="() => {this.show = false}">
			<view class="sign-border">
				<view class="position-float">
					<view class="container">
						<view style="width: 100%;height: 100%;">
							<view class="btn" @click="handleSignature('clear')">
								清空
							</view>
							<view class="btn" @click="handleSignature('undo')">撤消</view>
							<view class="btn" @click="handleSignature('save')">保存</view>
							<view class="btn" v-if="!userInfo.SignaturePhoto" @click="handleSignature('openSmooth')">
								压感{{openSmooth?'开':'关'}}</view>
							<view class="btn" v-else @click="handleCancel">取消</view>
						</view>
					</view>
				</view>
				<view style="display: flex;flex: 1;">
					<l-signature disableScroll backgroundColor="#fff" ref="signatureRef" :penColor="penColor" :penSize="penSize" :openSmooth="openSmooth" landscape>
						
					</l-signature>
					<view class="sign-text">签名区域</view>
				</view>

				<view class="position-float">
					<view class="container">
						<view class="absolute-align">请在横屏方向使用正楷字体签名</view>
					</view>
				</view>
			</view>


		</u-popup>
		<query-selector :show="showPopup" :total="curTotal" :lists="lists" :defaultValue="currentOperate.NAME" @close="handleClosePopup" @search="handleSearch" @select="handleSelected" />
		<query-selector :show="showPopupStep" :total="curTotalStep" :lists="stepLists" :defaultValue="currentOperateStep.NAME" @close="handleClosePopupStep" @search="handleSearchStep" @select="handleSelectedStep" />
	</view>
</template>

<script>
	import {
		getUserListOlds,
		saveUser,
		getUserPostLists,
		getDepartmentLists
	} from '../../../services/safe'
	import {
		guid,
		initFilter,
		extendRule,
		extendInclude,initFilterGroup,extendGroupRule,extendFilterGroup
	} from '../../../utils/common'
	import config from '../../../config/common'

	export default {
		data() {
			return {
				curTotalStep: 0,
				stepLists: [],
				currentOperateStep: {},
				showPopupStep: false,
				curTotal: 0,
				lists: [],
				currentOperate: {},
				showPopup: false,
				show: false,
				sourceUrl: config.uni_app_web_source_url,
				userInfo: {
					Nav_Person:{
						NAME:'',
						Nav_Post:{
							NAME:''
						}
					},
				},
				// title: '',
				penColor: '#333',
				penSize: 5,
				openSmooth: true,
				dataModel: {},
				rules: {},
			}
		},
		onLoad() {
			const orgId = uni.getStorageSync('orgId')
			const appInfoData = uni.getStorageSync('appInfo')
			const userId = appInfoData?.User?.ID || ''
			let json = initFilter(orgId)
			extendRule(json, 'ID', 1, userId);
			extendInclude(json, 'Nav_ApproveRole');
			extendInclude(json, 'Nav_ProdutionUnit');
			extendInclude(json, 'Nav_BelongRoles.Nav_BelongRole');
			extendInclude(json, 'Nav_Department');
			extendInclude(json, 'Nav_Person.Nav_Post');
			extendInclude(json, 'Nav_Person.Nav_TeamPersons.Nav_Team');
			extendInclude(json, 'Nav_UserPhotoFiles.Nav_ImgFile');
			extendInclude(json, 'Nav_UserSignFiles.Nav_ImgFile');
			getUserListOlds(json).then(res => {
				if (res.IsSuccessful) {
					const result = res.Data[0] || {}
					let roles = result.Nav_BelongRoles
					let roleNames = ''
					let roleCodes = ''
					for (let i = 0; i < roles.length; i++) {
						if (roles[i].Nav_BelongRole) {
							if (roleCodes.indexOf(roles[i].Nav_BelongRole.CODE) == -1) {
								roleCodes += (roleCodes.length > 0 ? "," : "") + roles[i].Nav_BelongRole.CODE;
								roleNames += (roleNames.length > 0 ? "," : "") + roles[i].Nav_BelongRole.NAME;
							}
						}
					}
					this.userInfo = {
						...result,
						UserName: appInfoData?.User?.NAME,
						UserCode: appInfoData?.User?.CODE,
						DepartmentName: result.Nav_Department?.NAME,
						TeamName: result.Nav_Person?.Nav_TeamPersons[0]?.Nav_Team?.NAME,
						PostName: result.Nav_Person?.Nav_Post?.NAME,
						SignaturePhoto: result.Nav_UserSignFiles && this.sourceUrl + result.Nav_UserSignFiles[
							0]?.Nav_ImgFile?.FILE_PATH,
						RoleName: roleNames,
						// // #ifdef H5
						// SignaturePhoto: result.Nav_UserSignFiles && result.Nav_UserSignFiles[0]?.Nav_ImgFile?.FILE_PATH,
						// // #endif
						// // #ifndef H5
						// SignaturePhoto: result.Nav_UserSignFiles && result.Nav_UserSignFiles[0]?.Nav_ImgFile?.FILE_PATH,
						// // #endif
					}
				}
			})
		},
		methods: {
			changeSwitch(e){
				this.userInfo.ISGETMSG = e
			},
			formSubmit() {
				saveUser(this.userInfo).then(res => {
					uni.$showMsgFunc('操作成功!', () => {
						uni.navigateBack()
					}, 'success', 1000)
				})
				// uni.navigateBack()
			},
			reUpload() {
				this.show = true
			},
			handleCancel() {
				this.show = false
			},
			handleClosePopup() {
				this.showPopup = false
				this.showPopupStep = false
				// this.showPopupCertificate = false
			},
			handleClosePopupStep() {
				this.showPopup = false
				this.showPopupStep = false
				// this.showPopupCertificate = false
			},
			handleChangeStep() {
				this.currentOperateStep = {}
				this.showPopupStep = true
				this.handleSearchStep('init')
			},
			handleSearchStep(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;
				}
				getUserPostLists(json).then(res => {
					if (res.IsSuccessful) {
						this.stepLists = res.Data.map(i => {
							return {
								...i,
								id: i.ID,
								name: i.NAME,
							}
						})
						this.curTotalStep = res.TotalCount
					}
				})
			},
			handleSelectedStep(val) {
				this.showPopupStep = false
				this.currentOperateStep = val
				this.userInfo.Nav_Person.Nav_Post = val
				this.userInfo.Nav_Person.POST_ID = val.ID
			},
			handleChange() {
				this.currentOperate = {}
				this.showPopup = true
				this.handleSearch('init')
			},
			handleSearch(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.lists = res.Data.map(i => {
							return {
								...i,
								id: i.ID,
								name: i.NAME,
							}
						})
						this.curTotal = res.TotalCount
					}
				})
			},
			handleSelected(val) {
				this.showPopup = false
				this.currentOperate = val
				this.userInfo.Nav_Department = val
				this.userInfo.DEPARTMENT_ID = val.ID
			},
			
			handleSignature(type) {
				if (type === 'openSmooth') {
					this.openSmooth = !this.openSmooth
					return
				}
				if (type === 'save') {
					this.$refs.signatureRef.canvasToTempFilePath({
						success: async (res) => {
							// 是否为空画板 无签名
							if (!res.isEmpty) {
								// 生成图片的临时路径
								// H5 生成的是base64
								uni.showLoading({
									title: '正在上传图片...'
								})
								const result = await this.uploadFilePromise(res.tempFilePath)
								// #ifdef H5
								this.userInfo.SignaturePhoto = res.tempFilePath
								// #endif
								// #ifndef H5
								this.userInfo.SignaturePhoto = this.sourceUrl + result.imgFilePath;
		
								// #endif
								this.show = false
							}
						}
					})
					return
				}
				if (this.$refs.signatureRef) {
					this.$refs.signatureRef[type]()
				}
			},
			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/UploadFileEditSign')
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: remoteUrl,
						filePath: url,
						fileList: url,
						name: 'file',
						formData: {
							OrgId: orgId,
							userID: userId
						},
						header: {
							Tenant: tenant,
							userid: userId
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.hideLoading()
								const uploadResult = JSON.parse(res.data)
								if (uploadResult.IsSuccessful) {
									let temp=[]
									let fileTemp = 
										 {
											USER_ID:this.userInfo.ID,
											IMG_FILE_ID: uploadResult.Data?.imgFileID,
											IS_DELETED:false,
											ORG_ID:this.userInfo.ORG_ID
										}
									temp.push(fileTemp)	
									this.userInfo.Nav_UserSignFiles = temp
									this.userInfo.FILE_PATH = uploadResult.Data?.imgFilePath
									resolve(uploadResult.Data)
								} else {
									reject(uploadResult.ErrorMessage)
								}
							}
						}
					});
				})
			}
		}
	}
</script>

<style scoped>
	.base-info {
		/* padding: 16px; */
		width: 100%;
		height: 100vh;
		position: relative;
		box-sizing: border-box;
	}

	.form-user {
		margin: 16px;
		/* border: #e5e5e5 1px solid; */
		padding: 10px 16px;
		box-shadow: #e5e5e5 0px 0px 10px 1px;
		border-radius: 10px;
	}

	.form-user>>>.u-form-item__body__left__content__label {
		font-size: 14px;
		color: #808080;
	}

	.form-user>>>.u-form-item__body__right__content__slot {
		display: flex;
		justify-content: flex-end;
	}

	.save-btn {
		margin: 20px 26px 0px 26px;
	}

	.assign {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		margin: 10px 26px;
		align-items: center;
	}

	.assign-again {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.top-label {
		font-size: 14px;
		/* padding: 10px 0; */
		line-height: 21px;
		/* text-align: center; */
		color: #303133;
	}

	.top-label-assign {
		font-size: 14px;
		/* padding: 10px 0; */
		line-height: 21px;
		/* color: #fff; */
		/* font-weight: bold; */
		margin-right: 3px;
		/* text-align: center; */
		/* color: #808080; */
	}

	.signature-img {
		border: 1px solid #e5e5e5;
		margin: 0px 16px;
	}

	.action {
		display: flex;
		width: 100%;
		height: 100%;
	}

	.btn {
		width: 100%;
		height: 25%;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		/* padding: 10px 0; */
		font-size: 16px;
		color: #f1a532;
		border-radius: 5px;
		border-right: 1px solid #fff;
		border-bottom: 2px solid #fff;
		writing-mode: vertical-rl;
		text-orientation: sideways;
	}

	.btn:first-child {
		border-left: 1px solid #e5e5e5;
	}

	.position-float {
		width: 40px;
		height: 100%;
	}

	.container {
		/* display: flex; */
		width: 100%;
		height: 100%;
		background-color: #fdf6ec;
	}

	.absolute-align {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		writing-mode: vertical-rl;
		text-orientation: sideways;
		font-size: 14px;
		color: #f1a532;
	}

	.position-float {
		/* width: 40px; */
		flex: 0 0 40px;
		height: 100%;
	}

	.container {
		/* display: flex; */
		width: 100%;
		height: 100%;
		background-color: #fdf6ec;
	}

	.sign-border {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		flex: auto;
	}
	.sign-border>>>.lime-signature {
		width: 100% !important;
		height: calc(100% - 40px) !important;
		margin: 20px 20px 0px 20px;
		border: #e5e5e5 2px dashed;
		background-color: #f4f4f5 !important;
	}
	.sign-text {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		writing-mode: vertical-rl;
		text-orientation: sideways;
		color: #909399;
		font-size: 16px;
	}
</style>