<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.merchantAcc" clearable />
					</uni-forms-item>
					<uni-forms-item :label="languageData.me.merchanrName" name="name">
						<uni-easyinput :disabled="step === 2" v-model="formData.merchantName" :placeholder="languageData.log.merchantPh" clearable />
					</uni-forms-item>
					<view @click="showBizType = true">
						<uni-forms-item style="pointer-events: none" :label="languageData.me.runType" name="operateType">
							<u--input
								border="surround"
								v-model="formData.operateTypeLabel"
								:placeholder="languageData.me.runType"
								:disabled="true"
								:disabledColor="step === 2 ? '#F7F6F6':'white'"
								suffixIcon="arrow-down"
							  ></u--input>
						</uni-forms-item>
					</view>
				</view>
				<view v-show="step !== 0">
					<!-- 商户用户 -->
					<view>
						<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.passport,name:0},
									  {label:languageData.functions.idCard, name:1}]"
									  :key="index" :label="item.label" :name="item.name">
									</u-radio>
								  </u-radio-group>
							</view>
						</uni-forms-item>
						<uni-forms-item :label="languageData.me.leName" name="legalPersoName">
							<uni-easyinput :disabled="step === 2" v-model="formData.legalPersonName" :placeholder="languageData.me.leName" clearable />
						</uni-forms-item>
						<uni-forms-item :label="languageData.me.lePhone" name="contactPersonPhone">
							<uni-easyinput :disabled="step === 2" v-model="formData.contactPersonPhone" :placeholder="languageData.me.lePhone" clearable />
						</uni-forms-item>
						<uni-forms-item :label="languageData.me.leMail" name="contactPersonEmail">
							<uni-easyinput :disabled="step === 2" v-model="formData.contactPersonEmail" :placeholder="languageData.me.leMail" clearable />
						</uni-forms-item>
						<view @click="dateClick('i')">
							<uni-forms-item style="pointer-events: none;" :label="languageData.me.signDate" name="expDate">
								<u--input
									border="surround"
									v-model="formData.legalPersonDateOfIssue"
									:placeholder="languageData.me.signDate"
									: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.legalPersonExpirationTime"
									:placeholder="languageData.me.expireTime"
									:disabled="true"
									:disabledColor="step === 2 ? '#F7F6F6':'white'"
									suffixIcon="arrow-down"
								  ></u--input>
							</uni-forms-item>
						</view>
						<uni-forms-item :label="languageData.me.leId" name="legalPersonIdCard">
							<uni-easyinput :disabled="step === 2" v-model="formData.legalPersonIdCard" :placeholder="languageData.me.leId" clearable />
						</uni-forms-item>
						<view v-show="formData.licenseType == 1">
							<uni-forms-item  style="align-items: left;" :label="languageData.me.leupIdImg" name="cardImg">
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList1" @afterRead="afterRead"
									@delete="deletePic" name="1" multiple :maxCount="1">
								</u-upload>
							</uni-forms-item>
							<uni-forms-item style="align-items: left;" :label="languageData.me.lebackIdImg" name="cardImg">
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList2" @afterRead="afterRead"
									@delete="deletePic" name="2" multiple :maxCount="1">
								</u-upload>
							</uni-forms-item>
							<uni-forms-item style="align-items: left;" :label="languageData.me.leholdIdImg" name="cardImg">
								<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList3" @afterRead="afterRead"
									@delete="deletePic" name="3" multiple :maxCount="1">
								</u-upload>
							</uni-forms-item>
						</view>
						<view v-show="formData.licenseType == 0">
							<uni-forms-item v-if="formData.licenseType == 0" style="align-items: left;" :label="languageData.functions.passportInformation" name="cardImg">
								<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>
							</uni-forms-item>
						</view>
						
						<view @click="addrClick('a')">
							<uni-forms-item style="pointer-events: none" :label="languageData.me.runArea" name="address">
								<u--input
									border="surround"
									v-model="formData.area"
									:placeholder="languageData.me.runArea"
									:disabled="true"
									:disabledColor="step === 2 ? '#F7F6F6':'white'"
									suffixIcon="arrow-down"
								  ></u--input>
							</uni-forms-item>
						</view>
						<uni-forms-item :label="languageData.me.addrDetail" name="address">
							<uni-easyinput :disabled="step === 2" v-model="formData.address" :placeholder="languageData.me.addrDetail" clearable />
						</uni-forms-item>
						<uni-forms-item :label="languageData.me.runCode" name="businessLicenseNumber">
							<uni-easyinput :disabled="step === 2" v-model="formData.businessLicenseNumber" :placeholder="languageData.me.runCode" clearable />
						</uni-forms-item>
					</view>
					<uni-forms-item v-show="true" style="align-items: left;" :label="languageData.me.runImg" name="cardImg">
						<view>
							<u-upload :disabled="step === 2" style="margin-left: 0px;" :fileList="fileList5" @afterRead="afterRead"
								@delete="deletePic" name="5" 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 @cancel="bizTYpeCancel" @confirm="bizTypeConfirm" keyName="label" :show="showBizType" 
		:columns="opTypes"></u-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 {
		getMerchantProfile,
		updateMerchantProfile,
		verifyPhoneNumber
	} from "@/api/system/user";
	import { baseUrl } from "@/config";
	import { addr } from "@/config/addr";

	export default {
		computed:{
			user(){
				return this.$store.state.user
			},
			baseUrl(){
				return baseUrl
			}
		},
		data() {
			return {
				opTypes:[[{label:this.$languageData.me.lspf, id:0},{label:this.$languageData.me.manu, id:1},{label:this.$languageData.me.serv, id:2}]],
				showBizType:false,
				pickerDate: new Date().getTime(),
				step: 0,
				addrData: '',
				dateItem: '',
				showBirth: false,
				showAddr: false,
				fileList1:[],
				fileList2:[],
				fileList3:[],
				fileList4:[],
				fileList5:[],
				formData: {},
				rules: {
				},
				languageData:{},
				checkOnly: false
			}
		},
		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: {
			bizTypeConfirm(e){
				this.formData.operateTypeLabel = e.value[0].label
				this.formData.operateType = e.value[0].id
				this.showBizType = false
			},
			bizTYpeCancel(e){
				this.showBizType = false
			},
			nextStep(){
				let msg = '';
				if(this.step===0){
					// if(this.formData.email === '' || this.formData.email == null)
					// 	msg += ' 电子邮箱 '
					if(this.formData.merchantName === '' || this.formData.merchantName == null)
						msg += ' '+this.$languageData.me.merchanrName+' '
					if(this.formData.operateType === '' || this.formData.operateType == null)
						msg += ' '+this.$languageData.me.runType+' '
				}
				else if(this.step === 1){
					if(this.formData.legalPersonName === '' || this.formData.legalPersonName == null)
						msg += ' '+this.$languageData.me.leName+' '
					if(this.formData.contactPersonPhone === '' || this.formData.contactPersonPhone == null)
						msg += ' '+this.$languageData.me.lePhone+' '
					if(this.formData.contactPersonEmail === '' || this.formData.contactPersonEmail == null)
						msg += ' '+this.$languageData.me.leMail+' '
					if(this.formData.legalPersonDateOfIssue === '' || this.formData.legalPersonDateOfIssue == null)
						msg += ' '+this.$languageData.me.signDate+' '
					if(this.formData.legalPersonExpirationTime === '' || this.formData.legalPersonExpirationTime == null)
						msg += ' '+this.$languageData.me.exTime+' '
					if(this.formData.legalPersonIdCard === '' || this.formData.legalPersonIdCard == null)
						msg += ' '+this.$languageData.me.leId+' '
						
					if((this.fileList1 == null || this.fileList1.size === 0) && this.formData.licenseType == 1)
						msg += ' '+this.$languageData.me.leupIdImg+' '
					if((this.fileList2 == null || this.fileList2.size === 0) && this.formData.licenseType == 1)
						msg += ' '+this.$languageData.me.lebackIdImg+' '
					if((this.fileList3 == null || this.fileList3.size === 0)  && this.formData.licenseType == 1)
						msg += ' '+this.$languageData.me.leholdIdImg+' '
						
					if(this.formData.area == null || this.formData.area === 0)
						msg += ' '+this.$languageData.me.runArea+' '
					if(this.formData.address == null || this.formData.address === 0)
						msg += ' '+this.$languageData.me.addrDetail+' '
						
		
					if(this.formData.businessLicenseNumber === '' || this.formData.businessLicenseNumber == null)
						msg += ' '+this.$languageData.me.runCode+' '
						
					if(this.fileList4 == null || this.fileList4.size === 0)
						msg += ' '+this.$languageData.me.runImg+' '
					if((this.fileList5 == null || this.fileList5.size === 0) && this.formData.licenseType == 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){
				this.showBirth = false;
				//签发
				if(this.dateItem === 'i'){
					this.formData.legalPersonDateOfIssue = this.$dayjs(e.value).format("DD/MM/YYYY")
				}
				//到期日期
				if(this.dateItem === 'e'){
					this.formData.legalPersonExpirationTime = 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() {
				getMerchantProfile().then(response => {
					this.formData = response.data
					if(this.formData.operateAddress){
						let addr = this.formData.operateAddress
						let idx = addr.lastIndexOf('/')
						this.formData.area = addr.substring(0, idx)
						this.formData.address = addr.substring(idx+1)
					}
					if(this.formData.operateType){
						
						this.formData.operateTypeLabel = this.opTypes[0].filter(item=>item.id == this.formData.operateType)[0].label
					}
					if(this.formData.legalPersonIdCardFrontImagePath)
						this.fileList1 = [{type: "image", url: this.formData.legalPersonIdCardFrontImagePath, 
						thumb: this.formData.legalPersonIdCardFrontImagePath, status:"sucess"}]
					if(this.formData.legalPersonIdCardBackImagePath)
						this.fileList2 = [{type: "image", url: this.formData.legalPersonIdCardBackImagePath, 
						thumb: this.formData.legalPersonIdCardBackImagePath, status:"sucess"}]
					if(this.formData.legalPersonUserWithIdCardImagePath)
						this.fileList3 = [{type: "image", url: this.formData.legalPersonUserWithIdCardImagePath, 
						thumb: this.formData.legalPersonUserWithIdCardImagePath, status:"sucess"}]
					if(this.formData.businessLicenseImage)
						this.fileList4 = [{type: "image", url: this.formData.businessLicenseImage, 
						thumb: this.formData.businessLicenseImage, status:"sucess"}]
					if(this.formData.passportImagePath)
						this.fileList5 = [{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.operateAddress = this.formData.area + '/' + this.formData.address
				if(this.fileList1.length > 0)
					this.formData.legalPersonIdCardFrontImagePath = this.fileList1[0].url
				if(this.fileList2.length > 0)
					this.formData.legalPersonIdCardBackImagePath = this.fileList2[0].url
				if(this.fileList3.length > 0)
					this.formData.legalPersonUserWithIdCardImagePath = this.fileList3[0].url
				if(this.fileList4.length > 0)
					this.formData.businessLicenseImage = this.fileList4[0].url
				if(this.fileList5.length > 0)
					this.formData.passportImagePath = this.fileList5[0].url
					
				this.formData.commonContactAddress = this.formData.area + '/' + this.formData.commonContactAddress
				this.$refs.form.validate().then(res => {
					updateMerchantProfile(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 => {
						this.$refs.loading.close();
					})
				})
			},
			
			handleSubmit() {
				console.log(JSON.stringify(this.formData))
				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>