<template>
	<view class="form-container container-with-elep full-height-with-titile">
		
		<view style="background-color: white; padding: 30px 20px; border-radius: 20px;">
			<u-steps :current="step">
				<u-steps-item :title="languageData.me.basicInformation" desc=""></u-steps-item>
				<u-steps-item :title="languageData.me.authenticationInformation" desc=""></u-steps-item>
				<u-steps-item :title="languageData.me.submitForReview" desc=""></u-steps-item>
			</u-steps>
			<!-- <view class="form-title">{{formData.userType == '0' ? languageData.me.personalData:languageData.me.merchantInfo}}</view> -->
			<uni-forms style="max-height: 60vh; margin-top:30px; overflow-y: auto;" label-position="left" :label-width="70" label-align="left" ref="form" :model="formData" :rules="rules">
				<view v-show="step!==1">
					<uni-forms-item :label="languageData.me.userType" name="userType">
						<uni-easyinput disabled :placeholder="languageData.me.personAcc" clearable />
					</uni-forms-item>
					<uni-forms-item :label="languageData.me.phoneNumber" name="phone">
						<view class="phone-item">
							<uni-easyinput v-model="formData.phone" :placeholder="languageData.me.inputPhoneNumber"
								:disabled="!!formData.phone" clearable />
						</view>
					</uni-forms-item>
					<uni-forms-item :label="languageData.me.email" name="email">
						<view class="phone-item">
							<uni-easyinput v-model="formData.email" :placeholder="languageData.me.pleaseEnterYourEmailAddress"
								:disabled="step === 2" clearable />
						</view>
					</uni-forms-item>
					<uni-forms-item :label="languageData.me.name" name="name">
						<uni-easyinput :disabled="step === 2" v-model="formData.fullName" :placeholder="languageData.me.namePh" clearable />
					</uni-forms-item>
					<uni-forms-item :label="languageData.me.gender">
						<view class="gender-options">
							<u-radio-group :disabled="step === 2"
								v-model="formData.gender"
								placement="row"
								style="justify-content: space-around;"
							  >
								<u-radio
								size="25"
								  :customStyle="{marginBottom: '8px'}"
								  v-for="(item, index) in [{label: languageData.me.man, name:'1'},{label:languageData.me.woman,name:'0'}]"
								  :key="index"
								  :label="item.label"
								  :name="item.name"
								>
								</u-radio>
							  </u-radio-group>
						</view>
					</uni-forms-item>
					<view @click="dateClick('b')">
						<uni-forms-item style="pointer-events: none;" :label="languageData.me.dateOfBirth" name="birthday">
							<u--input
								border="surround"
								v-model="formData.birthDate"
								:placeholder="languageData.me.pleaseDelectYourDateOfBirth"
								:disabled="true"
								:disabledColor="step === 2 ? '#F7F6F6':'white'"
								suffixIcon="arrow-down"
							  ></u--input>
						</uni-forms-item>
					</view>
				</view>
				<view v-show="step !== 0">
					<view v-show="formData.userType == '0'">
						<uni-forms-item :label="languageData.me.authenticationType">
							<view class="gender-options">
								<u-radio-group :disabled="step === 2" v-model="formData.licenseType" placement="row"
									style="justify-content: space-around;" >
									<u-radio size="25" :customStyle="{marginBottom: '8px'}"
									  v-for="(item, index) in [{label: languageData.functions.idCard, name:1},{label:languageData.functions.passport,name:0}]"
									  :key="index" :label="item.label" :name="item.name">
									</u-radio>
								  </u-radio-group>
							</view>
						</uni-forms-item>
						<uni-forms-item :label="languageData.functions.iDNumber" name="id">
							<uni-easyinput :disabled="step === 2" v-model="formData.idCardNumber" :placeholder="languageData.me.idPh" clearable />
						</uni-forms-item>
						<view @click="dateClick('s')">
							<uni-forms-item style="pointer-events: none;" :label="languageData.functions.dateOfdocumentissuance" name="expDate">
								<u--input
									border="surround"
									v-model="formData.dateOfIssue"
									:placeholder="languageData.functions.dateOfdocumentissuance"
									:disabled="true"
									:disabledColor="step === 2 ? '#F7F6F6':'white'"
									suffixIcon="arrow-down"
								  ></u--input>
							</uni-forms-item>
						</view>
						<view @click="dateClick('e')">
							<uni-forms-item style="pointer-events: none;" :label="languageData.me.expireTime" name="expDate">
								<u--input
									border="surround"
									v-model="formData.expirationTime"
									:placeholder="languageData.functions.pleaseSelectTheExpirationDateOfTheDocument"
									:disabled="true"
									:disabledColor="step === 2 ? '#F7F6F6':'white'"
									suffixIcon="arrow-down"
								  ></u--input>
							</uni-forms-item>
						</view>
						
						<view @click="addrClick('a')">
							<uni-forms-item style="pointer-events: none" :label="languageData.functions.BelongingRegion" name="address">
								<u--input
									border="surround"
									v-model="formData.area"
									:placeholder="languageData.me.pAddressPh"
									:disabled="true"
									:disabledColor="step === 2 ? '#F7F6F6':'white'"
									suffixIcon="arrow-down"
								  ></u--input>
							</uni-forms-item>
						</view>
						<uni-forms-item :label="languageData.functions.detailedAddress" name="address">
							<uni-easyinput :disabled="step === 2" v-model="formData.commonContactAddress" :placeholder="languageData.functions.detailedAddress" clearable />
						</uni-forms-item>
					</view>
					<view v-if="formData.licenseType == 1">
						<uni-forms-item style="align-items: left;" :label="languageData.functions.frontOfIDCard" name="cardImg">
							<view>
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList1" @afterRead="(e)=>afterRead(e, 'up')"
									@delete="(e)=>deletePic(e, 'up')" name="1" multiple :maxCount="1">
								</u-upload>
							</view>
						</uni-forms-item>
						<uni-forms-item style="align-items: left;" :label="languageData.functions.reverseOfIDCard" name="cardImg">
							<view>
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList2" @afterRead="(e)=>afterRead(e, 'ba')"
									@delete="(e)=>deletePic(e, 'ba')" name="2" multiple :maxCount="1">
								</u-upload>
							</view>
						</uni-forms-item>
						<uni-forms-item style="align-items: left;" :label="languageData.functions.handheldIDPhoto" name="cardImg">
							<view>
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList3" @afterRead="(e)=>afterRead(e, 'ha')"
									@delete="(e)=>deletePic(e, 'ha')" name="3" multiple :maxCount="1">
								</u-upload>
							</view>
						</uni-forms-item>
					</view>
					<uni-forms-item v-if="formData.licenseType == 0" style="align-items: left;" :label="languageData.functions.passportInformation" name="cardImg">
						<view>
							<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList4" @afterRead="(e)=>afterRead(e, 'pa')"
								@delete="(e)=>deletePic(e, 'pa')" name="4" multiple :maxCount="1">
							</u-upload>
						</view>
					</uni-forms-item>
				</view>
				
				
			</uni-forms>
			<view>
				<button v-show="step>0 && !checkOnly" class="submit-btn" @click="step = step === 0 ? step:step-1">{{languageData.functions.lastStep}}</button>
				<button v-show="step<2 && !checkOnly" class="submit-btn" @click="nextStep()">{{languageData.functions.nextStep}}</button>
				<button v-show="step===2 && !checkOnly" class="submit-btn" @click="handleSubmit">{{languageData.me.submit}}</button>
			</view>
			
		</view>

		<u-datetime-picker
			ref="datetimePicker"
			:show="showBirth"
			mode="date"
			:value="pickerDate"
			:minDate="0"
			:maxDate="7289625599000"
			@confirm="dateConf"
			@cancel="dateClose"
		>
		</u-datetime-picker>
		
		
		<u-picker :show="showAddr" ref="uPicker" 
		:columns="addrData.province"
		 @confirm="addrConf" @change="addrChg"
		 @cancel="addrClose"></u-picker>
		
		<loading ref="loading" :custom="false" :shadeClick="false" :type="1" />

	</view>
</template>
<script>
	import {
		getUserProfile,
		updateUserProfile,
		verifyPhoneNumber
	} from "@/api/system/user";
	
	import { addr } from "@/config/addr";
	import { baseUrl } from "@/config";

	export default {
		computed:{
			user(){
				return this.$store.state.user
			},
			baseUrl(){
				return baseUrl
			}
		},
		data() {
			return {
				checkOnly: false,
				pickerDate: new Date().getTime(),
				step: 0,
				addrData: '',
				dateItem: '',
				showBirth: false,
				showAddr: false,
				fileList1:[],
				fileList2:[],
				fileList3:[],
				fileList4:[],
				formData: {},
				rules: {
				},
				languageData:{}
			}
		},
		onLoad(e) {
			if(e.checkOnly){
				this.step = 2
				this.checkOnly = true
			}
			this.getUser()
			this.languageData = this.$languageData;
			if(uni.getLocale() == 'en'){
				this.addrData = addr.en
			}else if(uni.getLocale() == 'zh-Hans'){
				this.addrData = addr.cn
			}else{
				this.addrData = addr.laos
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.languageData = this.$languageData;
		},
		methods: {
			nextStep(){
				let msg = '';
				if(this.step===0){
					if(this.formData.email === '' || this.formData.email == null)
						msg += ' '+this.languageData.me.email+' '
					if(this.formData.fullName === '' || this.formData.fullName == null)
						msg += ' '+this.languageData.me.name+' '
					if(this.formData.gender === '' || this.formData.gender == null)
						msg += ' '+this.languageData.me.gender+' '
					if(this.formData.birthDate === '' || this.formData.birthDate == null)
						msg += ' '+this.languageData.me.dateOfBirth+' '
				}
				else if(this.step === 1){
					if(this.formData.licenseType === '' || this.formData.licenseType == null)
						msg += ' '+this.languageData.me.idType+' '
					if(this.formData.idCardNumber === '' || this.formData.idCardNumber == null)
						msg += ' '+this.languageData.me.iDNumber+' '
					if(this.formData.expirationTime === '' || this.formData.expirationTime == null)
						msg += ' '+this.languageData.me.exTime+' '
					if(this.formData.dateOfIssue === '' || this.formData.dateOfIssue == null)
						msg += ' '+this.languageData.me.signDate+' '
					if(this.formData.area === '' || this.formData.area == null)
						msg += ' '+this.languageData.me.area+' '
					if(this.formData.commonContactAddress === '' || this.formData.commonContactAddress == null)
						msg += ' '+this.languageData.me.address+' '
					if(this.formData.licenseType == 1){
						if(this.fileList1 == null || this.fileList1.length === 0)
							msg += ' '+this.languageData.functions.frontOfIDCard+' '
						if(this.fileList2 == null || this.fileList2.length === 0)
							msg += ' '+this.languageData.functions.reverseOfIDCard+' '
						if(this.fileList3 == null || this.fileList3.length === 0)
							msg += ' '+this.languageData.functions.handheldIDPhoto+' '
					}
					if(this.formData.licenseType == 0){
						if(this.fileList4 == null || this.fileList4.length === 0)
							msg += ' '+this.languageData.functions.passport+' '
					}
				}
				if(msg.length > 0){
					this.$modal.msg(msg+this.languageData.me.cannotbeNUll)
					return
				}
				this.step = this.step === 2 ? this.step:this.step+1
			},
			dateClick(type){
				if( this.step === 2) return
				this.dateItem = type
				this.showBirth = true;
			},
			dateConf(e){
				console.log(e)
				this.showBirth = false;
				//出生日期
				if(this.dateItem === 'b'){
					this.formData.birthDate = this.$dayjs(e.value).format("DD/MM/YYYY")
				}
				//到期日期
				if(this.dateItem === 'e'){
					this.formData.expirationTime = this.$dayjs(e.value).format("DD/MM/YYYY")
				}
				//签发日期
				if(this.dateItem === 's'){
					this.formData.dateOfIssue = this.$dayjs(e.value).format("DD/MM/YYYY")
				}
			},
			dateClose(e){
				this.showBirth = false
			},
			addrClick(type){
				if(this.step === 2) return
				this.showAddr = true
			},
			addrChg(e){
				const {columnIndex,value,values, index,picker = this.$refs.uPicker} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.addrData.district[index])
				}
			},
			addrConf(e){
				console.log(e)
				this.formData.area = e.value[0]+'/'+e.value[1]
				this.showAddr = false
			},
			addrClose(e){
				this.showAddr = false
			},
			getUser() {
				getUserProfile().then(response => {
					this.formData = response.data
					if(this.formData.commonContactAddress){
						let addr = this.formData.commonContactAddress
						let idx = addr.lastIndexOf('/')
						this.formData.area = addr.substring(0, idx)
						this.formData.commonContactAddress = addr.substring(idx+1)
					}
					if(this.formData.idCardFrontImagePath)
						this.fileList1 = [{type: "image", url: this.formData.idCardFrontImagePath, 
						thumb: this.formData.idCardFrontImagePath, status:"sucess"}]
					if(this.formData.idCardBackImagePath)
						this.fileList2 = [{type: "image", url: this.formData.idCardBackImagePath, 
						thumb: this.formData.idCardBackImagePath, status:"sucess"}]
					if(this.formData.userWithIdCardImagePath)
						this.fileList3 = [{type: "image", url: this.formData.userWithIdCardImagePath, 
						thumb: this.formData.userWithIdCardImagePath, status:"sucess"}]
					if(this.formData.passportImagePath)
						this.fileList4 = [{type: "image", url: this.formData.passportImagePath, 
						thumb: this.formData.passportImagePath, status:"sucess"}]
					if(this.formData.gender == null) this.formData.gender = ''
				})
			},
			submit(ref) {
				this.$refs.loading.open();
				this.formData.commonContactAddress = this.formData.area + '/' + this.formData.commonContactAddress
				if(this.fileList1.length > 0)
					this.formData.idCardFrontImagePath = this.fileList1[0].url
				if(this.fileList2.length > 0)
					this.formData.idCardBackImagePath = this.fileList2[0].url
				if(this.fileList3.length > 0)
					this.formData.userWithIdCardImagePath = this.fileList3[0].url
				if(this.fileList4.length > 0)
					this.formData.passportImagePath = this.fileList4[0].url
				
				this.$refs.form.validate().then(res => {
					updateUserProfile(this.formData).then(res => {
						if(res.code ===200){
							this.$store.dispatch('GetInfo').then(res => {
								setTimeout(() => {
									this.$refs.loading.close();
									setTimeout(() => {
										this.$modal.msgSuccess(this.languageData.updateSuccess)
										uni.switchTab({
											url: '/pages/home/index'
										})
									}, 500)
								}, 1000)
							})
						}
					}).catch(e => {
						uni.navigateBack()
						this.$refs.loading.close();
					})
				})
			},
			
			handleSubmit() {
				this.submit();
			},
			deletePic(event, type) {
				if(this.checkOnly  || this.step == 2)
					return
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				if(!this.formData.fileLlist){
					this.formData.fileList = []
				}
				// 当设置 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);
					const rsUrl = this.baseUrl + '/file/' +JSON.parse(result).data
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: rsUrl,
						})
					);
					this.formData.fileList.push(rsUrl)
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.baseUrl + "/commonFile/upload", // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						formData: {
							user: "test",
						},
						success: (res) => {
							// setTimeout(() => {
								resolve(res.data);
							// }, 1000);
						},
					});
				});
			},
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.form-container {
		padding: 40rpx;
	}

	.form-title {
		font-size: 24px;
		font-weight: 600;
		color: #1A1A1A;
		margin-bottom: 60rpx;
		position: relative;
		padding-left: 24rpx;
	}

	.form-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 6rpx;
		height: 32rpx;
		background: #3B7CFF;
		border-radius: 3px;
	}

	.phone-item {
		display: flex;
		align-items: center;
		gap: 24rpx;
	}

	.verify-btn {
		flex-shrink: 0;
		width: 160rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 14px;
		color: #FFFFFF;
		background: #3B7CFF;
		border: none;
		border-radius: 35rpx;
		box-shadow: 0 4rpx 12rpx rgba(59, 124, 255, 0.3);
		transition: all 0.3s ease;
	}

	.verify-btn:active {
		transform: scale(0.98);
		box-shadow: 0 2rpx 6rpx rgba(59, 124, 255, 0.2);
	}

	.gender-options {
		display: flex;
		gap: 80rpx;
		padding: 20rpx 0;
	}

	.gender-option {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.gender-option text {
		font-size: 15px;
		color: #333333;
	}

	.submit-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background: linear-gradient(135deg, #4B8BFF 0%, #3B7CFF 100%);
		color: #FFFFFF;
		font-size: 16px;
		font-weight: 500;
		border-radius: 44rpx;
		margin-top: 30rpx;
		box-shadow: 0 6rpx 16rpx rgba(59, 124, 255, 0.25);
		transition: all 0.3s ease;
	}

	.submit-btn:active {
		transform: scale(0.98);
		box-shadow: 0 3rpx 8rpx rgba(59, 124, 255, 0.15);
	}

	.error-tip {
		margin-top: 20rpx;
		color: #FF5252;
		font-size: 13px;
		text-align: center;
	}


	/* 美化uni-forms组件样式 */
	:deep(.uni-forms-item) {
		margin-bottom: 40rpx;
		background: #FFFFFF;
		padding: 24rpx 32rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
	}

	:deep(.uni-forms-item__label) {
		font-size: 15px;
		font-weight: 500;
		color: #1A1A1A;
		margin-bottom: 16rpx;
	}

	:deep(.uni-easyinput__content) {
		background: #F8F9FC;
		border-radius: 8rpx;
		height: 80rpx;
	}

	:deep(.uni-easyinput__content-input) {
		font-size: 15px;
		color: #333333;
	}

	:deep(.uni-forms-item__error) {
		padding-top: 12rpx;
		font-size: 13px;
		color: #FF5252;
	}

	:deep(radio .wx-radio-input) {
		width: 36rpx;
		height: 36rpx;
		border: 2px solid #E0E3E9;
	}

	:deep(radio .wx-radio-input.wx-radio-input-checked) {
		border-color: #3B7CFF !important;
		background: #3B7CFF !important;
	}
</style>