<template>
	<view class="page">
		<view class="steps-box">
			<u-steps :list="numList" :current="active"></u-steps>
		</view>
		<view>
			<view class="add-list" v-show="active == 0">
				<view style="padding:15px;margin-top:10px;" v-if="map ==0">
						<wu-calendar :insert="true" @change="calendarChange" slideSwitchMode="horizontal" mode="range" :selected="selected"  color="#3f9b6a" style="border-radius: 10px;" :data="today" :startDate="startDate" :endDate="endDate"></wu-calendar>
					</view>
				<u-form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="250">
					<u-form-item label="*租赁周期" prop="intendedLeaseTerm" borderBottom v-if="map==0">
						<u-input v-model="model1.intendedLeaseTerm" type="select" placeholder="请选择上面时间" ></u-input>
					</u-form-item>
					<u-form-item label="*租赁周期" prop="intendedLeaseTerm" borderBottom v-else>
						<u-input v-model="model1.intendedLeaseTerm"  placeholder="请输入租赁周期" ></u-input>
					</u-form-item>
					<u-form-item label="*经营用途" prop="businessPurpose" borderBottom>
						<u-input v-model="model1.businessPurpose"></u-input>
					</u-form-item>
				</u-form>
			</view>
			<view class="add-list" v-show="active == 0">
				<u-form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="250">
					<u-form-item label="*租金方案" prop="businessPurpose" borderBottom>
						<u-input v-model="model1.fangan" type="select" @click="celueShow = true" placeholder='请选择类型' />
					</u-form-item>
					<view style="padding: 10rpx; color: #31AA6A;font-size: 18px;">
						{{zujin}}
					</view>
					<u-form-item v-if="zhengce" label="优惠政策" prop="intendedLeaseTerm" borderBottom>

						<u-parse :html="zhengce"></u-parse>
					</u-form-item>
					<u-form-item v-if="shuoming" label="其他说明" prop="operatingEntity" borderBottom>

						<u-parse :html="shuoming"></u-parse>
					</u-form-item>
				</u-form>
			</view>
			<view class="add-list" v-show='active == 1'>
				<u-form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="250">
					<u-form-item label="*主体名称" prop="entityName" borderBottom>
						<u-input v-model="model1.entityName"></u-input>
					</u-form-item>
					<u-form-item label="*统一社会信用代码" prop="unifiedSocialCreditCode" borderBottom>
						<u-input v-model="model1.unifiedSocialCreditCode"></u-input>
					</u-form-item>
					<u-form-item label="*主体类型" prop="entityType" borderBottom>
						<u-input v-model="model1.entityType" type="select" @click="typeShow = true"
							placeholder='请选择类型' />
					</u-form-item>
					<u-form-item label="*法定代表人" prop="legalRepresentative" borderBottom>
						<u-input v-model="model1.legalRepresentative"></u-input>
					</u-form-item>
					<u-form-item label="*经营范围" prop="businessScope" borderBottom>
						<u-input v-model="model1.businessScope"></u-input>
					</u-form-item>
					<u-form-item label="*注册资本" prop="registeredCapital" borderBottom>
						<u-input v-model="model1.registeredCapital"></u-input>
					</u-form-item>
					<u-form-item label="*成立日期" prop="establishmentDate" borderBottom>
						<!-- <u-input v-model="model1.establishmentDate"></u-input> -->
						<u-input v-model="model1.establishmentDate" type="select" @click="establishow = true"
							placeholder="请选择" />
						<u-picker mode="time" v-model="establishow" :params="params"
							@confirm="establiChange"></u-picker>
					</u-form-item>
					<u-form-item label="*住所" prop="residence" borderBottom>
						<u-input v-model="model1.residence"></u-input>
					</u-form-item>
					<u-form-item label="*邮箱地址" prop="emailAddress" borderBottom>
						<u-input v-model="model1.emailAddress"></u-input>
					</u-form-item>
					<u-form-item label="*经营开始时间" prop="businessStartDate" borderBottom>
						<u-input v-model="model1.businessStartDate" type="select" @click="busStartshow = true"
							placeholder="请选择" />
						<u-picker mode="time" v-model="busStartshow" :params="params"
							@confirm="busStTimeChange"></u-picker>
					</u-form-item>
					<u-form-item label="*经营结束时间" prop="businessEndDate" borderBottom>
						<u-input v-model="model1.businessEndDate" type="select" @click="busEndtshow = true"
							placeholder="请选择" />
						<u-picker mode="time" v-model="busEndtshow" :params="params"
							@confirm="busEndTimeChange"></u-picker>
					</u-form-item>
					<u-form-item label="*营业执照" prop="businessLicense" borderBottom labelPosition="top">
						<u-upload :action="$upload" :auto-upload="false" ref="businessLicense" :max-count="1"
							@on-choose-complete="(response, file, fileList) => onsuccess1(response, file, fileList, 'businessLicense')"></u-upload>
					</u-form-item>
				</u-form>
			</view>
			<!-- <view v-show="active==2">
				<u-form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="250">
					<view class="add-list">
						<u-form-item label="*经营者姓名" prop="operatorName" borderBottom>
							<u-input v-model="model1.operatorName"></u-input>
						</u-form-item>
						<u-form-item label="*证件类型" prop="idCardType" borderBottom>
							<u-input v-model="model1.idCardType" type="select" @click="IdtypeShow = true"
								placeholder='请选择类型' />
						</u-form-item>
						<u-form-item label="*身份证号码" prop="idNumber" borderBottom>
							<u-input v-model="model1.idNumber"></u-input>
						</u-form-item>
						<u-form-item label="*有效开始时间" prop="idValidStart" borderBottom>
							<u-input v-model="model1.idValidStart" type="select" @click="idCardStartshow = true"
								placeholder="请选择" />
							<u-picker mode="time" v-model="idCardStartshow" :params="params1"
								@confirm="idCardStTimeChange"></u-picker>
						</u-form-item>
						<u-form-item label="*有效结束时间" prop="idValidEnd" borderBottom>
							<u-input v-model="model1.idValidEnd" type="select" @click="idCardEndtshow = true"
								placeholder="请选择" />
							<u-picker mode="time" v-model="idCardEndtshow" :params="params1"
								@confirm="idCardEndTimeChange"></u-picker>
						</u-form-item>
					</view>
					<view class="add-list">
						<view class="deom-box">
							<view class="img-deom">
								<u-upload :action="$upload" :custom-btn="true"
									@on-choose-complete="(response, file, fileList) => onsuccess1(response, file, fileList, 'idPhotoFront')"
									:auto-upload="false" :max-count="1" ref="idPhotoFront">
									<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover"
										hover-stay-time="150">
										<u-image width="304rpx" height="182rpx"
											:src="$imgUrl('/uploadID1.png')"></u-image>
									</view>
								</u-upload>
								<text>点击上传证件人像面</text>
							</view>
							<view class="img-deom">
								<u-upload :action="$upload" :custom-btn="true"
									@on-choose-complete="(response, file, fileList) => onsuccess1(response, file, fileList, 'idPhotoBack')"
									:auto-upload="false" :max-count="1" ref="idPhotoBack">
									<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover"
										hover-stay-time="150">
										<u-image width="304rpx" height="182rpx"
											:src="$imgUrl('/uploadID2.png')"></u-image>
									</view>
								</u-upload>
								<text>点击上传证件国徽面</text>
							</view>
						</view>
					</view>
					<view class="add-list">
						<view style="line-height: 60rpx;">上传示例</view>
						<view class="deom-box">
							<view class="img-deom">
								<u-image width="304rpx" height="182rpx" :src="$imgUrl('/front-icon.png')"></u-image>
								<text>人脸示例图</text>
							</view>
							<view class="img-deom">
								<u-image width="304rpx" height="182rpx" :src="$imgUrl('/back-icon.png')"></u-image>
								<text>国徽面示例图</text>
							</view>
						</view>
					</view>
					<text
						style="display: inline-block; font-size: 24rpx; line-height: 30px; margin: 24rpx 30rpx 0;">请拍摄证件原件，保证照片拍摄清晰，取图完整，不反光。</text>
					<view class="add-list" labelPosition="left" :model="model1" :rules="rules" ref="uForm"
						:labelWidth="250">
						<u-form-item label="*是否为法人" prop="isLegalPerson" borderBottom>
							<u-radio-group v-model="model1.isLegalPerson">
								<u-radio :name="1">是</u-radio>
								<u-radio :name="0">否</u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="*企业授权书" prop="enter" borderBottom labelPosition="top">

							<u-upload :action="$upload" ref="enter" :max-count="1"
								@on-choose-complete="(response, file, fileList) => onsuccess1(response, file, fileList, 'enterpriseAuthorization')"
								:auto-upload="false"></u-upload>
						</u-form-item>
					</view>
				</u-form>
			</view> -->
		</view>
		<u-select v-model="typeShow" :list="activesType" @confirm="typeChange"></u-select>
		<u-select v-model="celueShow" :list="celueType" @confirm="celueChange"></u-select>
		<u-select v-model="IdtypeShow" :list="idType" @confirm="IdtypeChange"></u-select>
		<!-- 保存按钮 -->
		<view class="page-footer">
			<u-button style="background-color: #DFE0E4; flex: 1; margin: 0 10px;" @click="toBefor"
				v-if="active != 0">上一步</u-button>
			<u-button type="success" style="flex: 1; margin: 0 10px;" @click="toNext" v-if="active != 1">下一步</u-button>
			<u-button type="success" style="flex: 1; margin: 0 10px;" @click="go" v-if="active == 1">提交申请</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				active: 0,
				// numList: [{
				// 	name: '租赁信息'
				// }, {
				// 	name: '主体信息'
				// }, {
				// 	name: '经营者信息'
				// }],
				numList: [{
					name: '租赁信息'
				}, {
					name: '营业执照信息'
				}],
				model1: {
					businessPurpose: '',
					intendedLeaseTerm: '',
					operatingEntity: '',
					entityName: '',
					unifiedSocialCreditCode: '',
					entityType: '',
					legalRepresentative: '',
					businessScope: '',
					registeredCapital: '',
					establishmentDate: '',
					residence: '',
					emailAddress: '',
					businessStartDate: '',
					businessEndDate: '',
					operatorName: '',
					idCardType: '',
					idNumber: '',
					idValidStart: '',
					idValidEnd: '',
					idPhotoFront: '',
					idPhotoBack: '',
					isLegalPerson: '',
					enterpriseAuthorization: '',
					auditStatus: '1',
					fangan: ''
				},
				rules: {
					businessPurpose: [{
						required: true,
						message: '请输入经营用途',
						trigger: 'blur'
					}],
					intendedLeaseTerm: [{
						required: true,
						message: '请输入意向租期',
						trigger: 'blur'
					}],
					operatingEntity: [{
						required: true,
						message: '请输入经营主体',
						trigger: 'blur'
					}]
				},
				// 类型
				showType: false,
				params: {
					year: true,
					month: true,
					day: true,
				},
				params1: {
					year: true,
					month: true,
					day: true
				},
				TimeStratshow: false,
				typeShow: false,
				activesType: [{
						value: 1,
						label: '个体'
					},
					{
						value: 2,
						label: '企业'
					},
				],
				idType: [{
					value: 1,
					label: '身份证'
				}],
				celueType: [],
				celueShow: false,
				IdtypeShow: false,
				busStartshow: false,
				busEndtshow: false,
				idCardStartshow: false,
				idCardEndtshow: false,
				ziyuanId: '',
				moban: [],
				zhengce: '',
				shuoming: '',
				zujin: '',
				selected: [],
							map:0,
							establishow:false,
							today:['',''],
							startDate:'',
							endDate:''
			};
		},
		onLoad(option) {
			this.ziyuanId = option.ids
			let paesize = {
				pageNumber: 0,
				pageSize: 10,
				resourcesId: option.ids
			}
		const containsSp = option.ids.includes('sp');
			if (containsSp) {
			  this.map = 1;
			} else {
			  this.map = 0; // 或者其他默认值
			}
			this.$http.sendRequest('/cereResourceStrategy/queryByResources', 'POST', paesize, 1).then(res => {

				this.moban = res.data.data
				this.moban.map((item, index) => {
					let obj = {
						value: index,
						label: item.policyName
					}
					this.celueType.push(obj)
				})
			}).catch(err => {
				console.log(err)
				//请求失败
			})
			
		},
		onShow() {
			this.calculateDates()
			let pageHe={
				pageNumber: 0,
				pageSize: 10,
				shopNumber:this.ziyuanId,
				dataStatus:1
			}
					this.$http.sendRequest('/cereContractInformation/getPage', 'POST', pageHe,1).then(res => {
						if(res.data.data.content.length !=0){
							res.data.data.content.map(item=>{
								this.generateDateRange([item.contractTerminationDate,item.leaseStartDate])
							})
							
						}
					})
					
		},
		methods: {
			generateDateRange(datas) {
			     const result = [];
			     const startDate = new Date(datas[0])
			     const endDate = new Date(datas[1])
			     if (startDate > endDate) {
			       [startDate, endDate] = [endDate, startDate]
			     }
			     let currentDate = new Date(startDate);
			     while (currentDate <= endDate) {
			       const year = currentDate.getFullYear();
			       const month = String(currentDate.getMonth() + 1).padStart(1, '0');
			       const day = String(currentDate.getDate()).padStart(1, '0');
			       const dateString = `${year}-${month}-${day}`;
			       this.selected.push({
			         date: dateString,
			         info: '已租',
			         disable: true
			       });
			       currentDate.setDate(currentDate.getDate() + 1);
			     }
			     return result;
			   },
							calendarChange(e){
								if(e.range.after == ''){
									uni.showToast({
										icon: 'none',
										title: '请选择结束时间'
									})
									return
								}
								this.model1.intendedLeaseTerm = e.range.before+'至'+e.range.after
							},
			typeChange(e) {
				this.model1.entityType = e[0].label;
			},
			 calculateDates() {
			   const today = new Date();
			        const year = today.getFullYear();
			        const month = today.getMonth();
			      this.startDate =  this.formatDate(today);
			
			      // 获取后一个月的最后一天
			      const nextMonthLastDay = new Date(year, month + 2, 0);
			      this.endDate = this.formatDate(nextMonthLastDay);
			    },
			    formatDate(date) {
			      const year = date.getFullYear();
			      const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
			      const day = ('0' + date.getDate()).slice(-2);
			      return `${year}-${month}-${day}`;
			    },
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = ('0' + (now.getMonth() + 1)).slice(-2);
				const day = ('0' + now.getDate()).slice(-2);
				const hours = ('0' + now.getHours()).slice(-2);
				const minutes = ('0' + now.getMinutes()).slice(-2);
				const seconds = ('0' + now.getSeconds()).slice(-2);

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			onsuccess1(e, file, fileList, ziduan) {
				console.error(e, file, fileList, ziduan)
				uni.uploadFile({
					url: this.$upload, // 仅为示例，请替换为您的服务器上传接口
					filePath: e[0].url,
					name: 'file', // 后端接收的文件参数名
					formData: {
						filePath: 'xcx', // 其他表单数据
					},
					success: (uploadFileRes) => {
						if (ziduan == 'businessLicense') {
							this.model1.businessLicense = this.$img + JSON.parse(uploadFileRes.data).data
						} else if (ziduan == 'idPhotoFront') {
							this.model1.idPhotoFront = this.$img + JSON.parse(uploadFileRes.data).data
						} else if (ziduan == 'idPhotoBack') {
							this.model1.idPhotoBack = this.$img + JSON.parse(uploadFileRes.data).data
						} else {
							this.model1.enterpriseAuthorization = this.$img + JSON.parse(uploadFileRes.data).data
						}

						console.log('上传成功', this.model1);
						uni.showToast({
							title: '上传成功',
							icon: 'success',
						});
					},
					fail: (err) => {
						console.error('上传失败', err);
						uni.showToast({
							title: '上传失败',
							icon: 'none',
						});
					},
				});
			},
			chek() {
					if (!this.model1.entityName) {
						uni.showToast({
							icon: 'none',
							title: '请输入主体名称'
						});
						return false;
					}
					if (!this.model1.unifiedSocialCreditCode) {
						uni.showToast({
							icon: 'none',
							title: '请输入统一社会信用代码'
						});
						return false;
					}
					if (!this.model1.entityType) {
						uni.showToast({
							icon: 'none',
							title: '请选择主体类型'
						});
						return false;
					}
					if (!this.model1.legalRepresentative) {
						uni.showToast({
							icon: 'none',
							title: '请输入法定代表人'
						});
						return false;
					}
					if (!this.model1.businessScope) {
						uni.showToast({
							icon: 'none',
							title: '请输入经营范围'
						});
						return false;
					}
					if (!this.model1.registeredCapital) {
						uni.showToast({
							icon: 'none',
							title: '请输入注册资本'
						});
						return false;
					}
					if (!this.model1.establishmentDate) {
						uni.showToast({
							icon: 'none',
							title: '请输入成立日期'
						});
						return false;
					}
					if (!this.model1.residence) {
						uni.showToast({
							icon: 'none',
							title: '请输入住所'
						});
						return false;
					}
					if (!this.model1.emailAddress) {
						uni.showToast({
							icon: 'none',
							title: '请输入邮箱地址'
						});
						return false;
					}
					if (!this.model1.businessStartDate) {
						uni.showToast({
							icon: 'none',
							title: '请选择经营开始时间'
						});
						return false;
					}
					if (!this.model1.businessEndDate) {
						uni.showToast({
							icon: 'none',
							title: '请选择经营结束时间'
						});
						return false;
					}
					if (!this.model1.businessLicense) {
						uni.showToast({
							icon: 'none',
							title: '请上传营业执照'
						});
						return false;
					}
					return true;
				},
			go() {
				this.model1.rentalResourcesId = this.ziyuanId
				this.model1.applicant = uni.getStorageSync('user').phone
				this.model1.applicationTime = this.getCurrentTime()
			let show = this.chek()
				if(show == false){
					return
				}
				console.log(this.model1.applicant)
				let info = {
					...this.model1,
					businessLicense:this.model1.businessLicense.replace(this.$img,''),
					// idPhotoFront:this.model1.idPhotoFront.replace(this.$img,''),
					// idPhotoBack:this.model1.idPhotoBack.replace(this.$img,''),
					// enterpriseAuthorization:this.model1.enterpriseAuthorization.replace(this.$img,''),
				}
				
				// return
				this.$http.sendRequest('/cereBusinessInfo/add', 'POST',info, 1).then(res => {
					// uni.redirectTo({
					// 	url: '/pages/record/record'
					// })
					uni.showToast({
						title: '提交成功',
						icon: 'none',
					});
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)

				})
			},
			// 上一步
			toBefor() {
				this.active = +this.active - 1;
			},
			// 下一步
			toNext() {
				if(this.active == '0') {
					if (!this.model1.intendedLeaseTerm) {
						uni.showToast({
							icon: 'none',
							title: '请选择租赁周期'
						});
						return;
					}
					if (!this.model1.businessPurpose) {
						uni.showToast({
							icon: 'none',
							title: '请输入经营用途'
						});
						return;
					}
					if (!this.model1.fangan) {
						uni.showToast({
							icon: 'none',
							title: '请选择租金方案'
						});
						return;
					}
				}
				 
				this.active = +this.active + 1;
			},
			startTimeChange(val) {
				this.model1.scheduleTime = this.timeChange(val)
			},
			timeChange(val) {
				const {
					year,
					month,
					day,
				} = val;
				return `${year}-${month}-${day}`;
			},
			leiXpops(val) {
				this.model1.intentionalBusinessType = val[0].label
			},
			celueChange(val) {
				this.model1.fangan = val[0].label
				if (this.moban.length != 0) {
					this.zhengce = this.moban[val[0].value].preferentialPolicy
					this.shuoming = this.moban[val[0].value].otherDescription
					this.zujin = this.moban[val[0].value].rentalPrice + '元/' + this.moban[val[0].value].leaseTerm
				}

			},
			busStTimeChange(val) {
				this.model1.businessStartDate = this.timeChange(val)
				this.model1.businessEndDate = ''
			},
			establiChange(val){
				this.model1.establishmentDate = this.timeChange(val)
			},
			busEndTimeChange(val) {
				const time = this.timeChange(val);
				if (new Date(time).getTime() > new Date(this.model1.businessStartDate).getTime()) {
					this.model1.businessEndDate = time
				} else {
					uni.showToast({
						icon: 'none',
						title: '结束时间不能小于开始时间'
					})
				}
			},
			idCardStTimeChange(val) {
				this.model1.idValidStart = this.timeChange1(val)
				this.model1.idValidEnd = ''

			},
			idCardEndTimeChange(val) {
				const time = this.timeChange1(val);
				if (new Date(time).getTime() > new Date(this.model1.idValidStart).getTime()) {
					this.model1.idValidEnd = time
				} else {
					uni.showToast({
						icon: 'none',
						title: '结束时间不能小于开始时间'
					})
				}
			},
			IdtypeChange(e) {
				this.model1.idCardType = e[0].label;
			},
			timeChange1(val) {
				const {
					year,
					month,
					day
				} = val;
				return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style scoped lang="scss">
	@import 'leaseAdd.scss';
</style>