<template>
	<view class='base-info'>
		<u--form
			labelPosition="left"
			labelWidth="auto"
			labelAlign="center"
			: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="left"></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="left"></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="post"
				border-bottom
			>
				<text>{{userInfo.TeamName}}</text>
			</u-form-item>
			<u-form-item
				label="岗位:"
				prop="job"
				border-bottom
			>
				<text>{{userInfo.PostName}}</text>
			</u-form-item>
			<!-- <u-form-item label="角色" prop="role">
				<text>{{userInfo.RoleName}}</text>
			</u-form-item> -->
			<view class='top-label'>签名</view>
			<view class="signature-img">
				<image @click="reUpload" style="width: 100%" mode="widthFix" :src="userInfo.SignaturePhoto"></image>
			</view>
			<button @click="formSubmit" type="primary" class='save-btn'>确定</button>
		</u--form>
		<u-popup
			:show="show"
			mode="center"
			:customStyle="{width: '100%', height: '100%'}"
			:closeable="true"
			@open="() => {}"
			@close="() => {this.show = false}">
			<view style="width: 100% ;height: 100%; border: 1px solid #ddd;">
				<l-signature
					disableScroll
					backgroundColor="#fff"
					ref="signatureRef"
					:penColor="penColor"
					:penSize="penSize"
					:openSmooth="openSmooth"
					landscape
				></l-signature>
			</view>
			<view class="action">
				<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>
		</u-popup>
	</view>
</template>

<script>
  import { getUserLists,saveUser } from '../../../services/safe'
	import {
		initFilter,
		extendRule,
		extendInclude
	} from '../../../utils/common'
	import config from '../../../config/common'

	export default {
    data() {
      return {
				show: false,
				sourceUrl: config.uni_app_web_source_url,
				userInfo: {},
				// 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');
			extendInclude(json, 'Nav_Department');
			extendInclude(json, 'Nav_Person.Nav_Post');
			extendInclude(json, 'Nav_Person.Nav_TeamPersons.Nav_Team');
			extendInclude(json, 'Nav_UserSignFiles.Nav_ImgFile.Nav_File');
			getUserLists(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?.Nav_File?.FILE_PATH,
						RoleName: roleNames,
						// // #ifdef H5
						// SignaturePhoto: result.Nav_UserSignFiles && result.Nav_UserSignFiles[0]?.Nav_ImgFile?.Nav_File?.FILE_PATH,
						// // #endif
						// // #ifndef H5
						// SignaturePhoto: result.Nav_UserSignFiles && result.Nav_UserSignFiles[0]?.Nav_ImgFile?.Nav_File?.FILE_PATH,
						// // #endif
					}
				}
			})
    },
    methods: {
			formSubmit() {
				// saveUser(this.userInfo).then(res => {
				// 	uni.$showMsgFunc('操作成功!', () => {
				// 		uni.navigateBack()
				// 	}, 'success', 1000)
				// })
				uni.navigateBack()
			},
			reUpload() {
				this.show = true
			},
			handleCancel() {
				this.show = false
			},
			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) {
									resolve(uploadResult.Data)
								} else {
									reject(uploadResult.ErrorMessage)
								}
							}
						}
					});
				})
			}
    }
  }
</script>

<style scoped>
	.base-info {
		padding: 16px;
		width: 100%;
		height: 100vh;
		position: relative;
		box-sizing: border-box;
	}
	.save-btn {
		margin-top: 20px;
	}
	.top-label {
		font-size: 14px;
		padding: 10px 0;
		line-height: 21px;
		text-align: center;
		color: #303133;
	}
	.signature-img {
		border: 1px solid #e5e5e5;
	}
	.action {
		display: flex;
	}
	.action .btn {
		width: 25%;
		text-align: center;
		padding: 10px 0;
		font-size: 14px;
		color: #333;
		border-right: 1px solid #e5e5e5;
		border-bottom: 1px solid #e5e5e5;
	}
	.action .btn:first-child {
		border-left: 1px solid #e5e5e5;
	}
</style>
