<template>
	<view class="container">
		<view class="form">
			<u--form :model="form" ref="uForm" label-width="170rpx">
				<u-gap height="10" bgColor="#f3f3f3"></u-gap>
				<view class="block">
					<u-form-item label="真实姓名" prop="realName" borderBottom>
						<u-input v-model="form.realName" maxlength="20" :disabled="isEdit" placeholder="真实姓名" />
					</u-form-item>
					<u-form-item label="身份证号" prop="certificateCode">
						<u-input v-model="form.certificateCode" maxlength="20" :disabled="isEdit" placeholder="身份证号" />
					</u-form-item>
				</view>
				<u-gap height="10" bgColor="#f3f3f3"></u-gap>
				<view class="block">
					<view class="upload">
						<u-upload :fileList="fileList1" :maxSize="1048576" width="190" height="120"
							@afterRead="afterRead" @delete="deletePic" :disabled="isEdit"  name="1" multiple :maxCount="2">
							<view class="id-card-upload">
								<image class="photograph" src="../../../static/icon/photograph.png" mode="widthFix">
								</image>
								<text v-if="fileList1.length == 0">上传正面照片</text>
								<text v-if="fileList1.length == 1">上传反面照片</text>
							</view>
						</u-upload>
						<!-- <u-upload :fileList="fileList1" :maxSize="3145728" width="250" height="150"
							@afterRead="afterRead" @delete="deletePic" :disabled="isEdit"  name="1" multiple :maxCount="2">
							<view class="id-card-upload">
								<image class="photograph" src="../../../static/icon/photograph.png" mode="widthFix">
								</image>
								<text>上传反面照片</text>
							</view>
						</u-upload> -->
					</view>
				</view>
				<u-gap height="10" bgColor="#f3f3f3"></u-gap>
				<view class="block">
					<view class="desc-title">拍摄身份证要求：</view>
					<view class="desc">大陆公民持有的本人有效二代身份证：<br>拍摄时确保身份证<text>边框完整，字体清晰，亮度均匀；<br>图片大小在1M以内；</text></view>
					<view class="photo">
						<image src="https://file.wsdns.cn/20230619/29a8c790211a46529fbbb66ee8d223d5.png"
							mode="widthFix"></image>
					</view>
				</view>
			</u--form>
		</view>
		<view class="btn-wrapper">
			<u-button :text="submitText" color="linear-gradient(to bottom, #010002, #681752)" :disabled="isEdit"
				shape="circle" @click="handleSubmit()"></u-button>
		</view>
	</view>
</template>

<script>
	import * as UploadApi from '@/api/upload'
	import store from '@/store'
	import * as CertificateApi from '@/api/love-certificate.js'

	const userId = uni.getStorageSync('userId')


	export default {
		data() {
			return {
				form: {
					certificateType: 'idCard',
					userId
				},
				fileList1: [],
				disabled: false,
				// 临时图片 (用于上传)
				tempFile: null,
				isEdit: false,
				submitText: '提交认证信息',
				eventChannel: null
				// rules: [

				// ]
			}
		},
		onLoad() {
			this.eventChannel = this.getOpenerEventChannel();
			this.getData()
		},
		methods: {
			getData() {
				const app = this
				const {
					form
				} = this
				CertificateApi.listCertificate({
					certificateType: 'idCard',
					userId
				}).then(res => {
					if (res.data && res.data.length > 0) {
						app.form = res.data[0]
						app.fileList1 = JSON.parse(res.data[0].files)

						if(app.form.status == 10){
							app.submitText = '认证中'
							app.isEdit = true
						}
						if(app.form.status == 20){
							app.submitText = '提交认证信息'
							app.isEdit = false
						}
						if(app.form.status == 30){
							app.submitText = '已通过'
							app.isEdit = true
						}
					}
				})
			},
			// 新增图片
			async afterRead(event) {
				console.log("event: ", event);
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url,
						thumb: result.thumbUrl
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					UploadApi.uploadFile({
						filePath: url,
						fileType: 'image',
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('AccessToken')
						},
					}).then(result => {
						setTimeout(() => {
							resolve(result.data)
						}, 1000)
					}).catch(err => {
						console.log("err: ", err);
					})
				})
			},
			// 删除图片
			deletePic(event) {
				if(this.isEdit == true){
					return false;
				}
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 确认修改
			async handleSubmit() {
				const app = this
				if(app.fileList1.findIndex(item => item.status != 'success') >= 0){
					return
				}
				if (app.disabled === true) return
				console.log("app.tempFile: ", app.tempFile);
				app.form.files = JSON.stringify(app.fileList1)
				const saveCertificate = app.isEdit ? CertificateApi.updateCertificate : CertificateApi.addCertificate
				
				uni.showLoading({
					mask: true,
					title: "正在验证"
				})
				saveCertificate(app.form).then(result => {
					app.$success('认证成功')
					this.getData()			
				}).catch(err => {
					app.$error(err.message)
				}).finally(()=>{
					store.dispatch('GetUserInfo')
					this.eventChannel.emit('reload');
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f3f3f3;
	}

	.container {

		.form {
			background-color: #ffffff;
		}

		.block {
			margin: auto;
			width: 700rpx;
			font-size: 28rpx;

			.upload {
				width: 360rpx;
				margin: 0 auto;
				padding: 20rpx 0;
				justify-content: center;

				.id-card-upload {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					text-align: center;
					margin: 10rpx auto;
					color: #cccccc;
					border: 5rpx dashed #d9d9d9;
					border-radius: 20rpx;
					width: 360rpx;
					height: 220rpx;

					.photograph {
						width: 60rpx;
					}
				}
			}

			.desc-title {
				line-height: 3rem;
			}

			.desc {
				color: #cccccc;

				text {
					color: #7f006f;
				}
			}

		}
	}

	.btn-wrapper {
		background: none;
		width: 360rpx;
		margin: 50rpx auto;
		// display: flex;
		// align-items: center;
		padding: 0 20rpx;
	}
</style>
