<template>
	<view class="min-page bg-f7 u-font-28 color-333">
		<steps v-model="step" @itemClick="stepItemClick" />
		<view class="u-m-t-32">
			<basicInfo v-if="step==0" :data="form.merchantBaseInfo" :maxSize="maxSize"
				@update="update($event,'merchantBaseInfo')">
			</basicInfo>
			<legalPerpoleInfo v-if="step==1" :maxSize="maxSize" :data="form.legalPersonInfo"
				@update="update($event,'legalPersonInfo')">
			</legalPerpoleInfo>
			<businessLicenceInfo v-if="step==2" :maxSize="maxSize" :data="form.businessLicenceInfo"
				@update="update($event,'businessLicenceInfo')"></businessLicenceInfo>
			<storeInfo v-if="step==3" :maxSize="maxSize" :data="form.storeInfo" @update="update($event,'storeInfo')">
			</storeInfo>
			<settlementInfo v-if="step==4" :maxSize="maxSize" :data="form.settlementInfo"
				@update="update($event,'settlementInfo')">
			</settlementInfo>
		</view>
		<bottomBtnGroup @save="saveClick" @cancel="cancelClick" :cancelText="cancelText" :confirmText="confirmText">
		</bottomBtnGroup>
	</view>
</template>

<script setup>
	import steps from './components/steps.vue'
	import basicInfo from './components/basic-info.vue'
	import legalPerpoleInfo from './components/legalPerpole-info.vue'
	import businessLicenceInfo from './components/business-licence-info.vue'
	import storeInfo from './components/store-info.vue'
	import settlementInfo from './components/settlement-info.vue'
	import bottomBtnGroup from './components/bottom-btn-group.vue'
	import dayjs from 'dayjs'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		rules,
		isEmptyValue,
		returnKey,
		getNestedValue,
		verifyValue,
		verifyData
	} from './data.js'
	import {
		reactive,
		ref,
		watch,
		onMounted,
		computed
	} from 'vue';
	const form = reactive({
		"shopId": '',
		"merchantCode": '',
		"merchantBaseInfo": {
			"userType": "0",
			"shortName": "",
			"mccCode": "",
			"alipayAccount": "",
			"contactPersonType": "LEGAL",
			"contactName": "",
			"certType": "0",
			"contactPersonId": "",
			"contactPersonIdStartDate": dayjs().valueOf(),
			"contactPersonIdEndDate": dayjs().add(10, 'year').valueOf(),
			"contactIdCardBackPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"contactIdCardFrontPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"contactPhone": "",
			"contactAddr": "",
			"contactEmail": "",
			"companyChildType": "1"
		},
		"legalPersonInfo": {
			"legalPersonName": "",
			"legalPersonId": "",
			"legalIdPersonStartDate": dayjs().valueOf(),
			"legalPersonIdEndDate": dayjs().add(10, 'year').valueOf(),
			"legalPersonPhone": "",
			"legalPersonEmail": "",
			"legalGender": "",
			"legalAddress": "",
			"idCardHandPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"idCardFrontPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"idCardBackPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			}
		},
		"businessLicenceInfo": {
			"licenceName": "",
			"licenceNo": "",
			"licenceStartDate": dayjs().valueOf(),
			"licenceEndDate": dayjs().add(10, 'year').valueOf(),
			"registeredAddress": "",
			"licensePic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			}
		},
		"storeInfo": {
			"mercProvCode": "",
			"mercCityCode": "",
			"mercAreaCode": "",
			"mercProv": "",
			"mercCity": "",
			"mercArea": "",
			"businessAddress": "",
			"insidePic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"doorPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"cashierDeskPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			}
		},
		"settlementInfo": {
			"settlementType": "0",
			"noLegalName": "",
			"noLegalId": "",
			"settlementCardType": "21",
			"settlementCardNo": "",
			"settlementName": "",
			"bankMobile": "",
			"openAccProvinceId": "",
			"openAccCityId": "",
			"openAccAreaId": "",
			"openAccProvince": "",
			"openAccCity": "",
			"openAccArea": "",
			"bankName": "",
			"bankInstId": "",
			"bankType": "",
			"bankBranchName": "",
			"bankBranchCode": "",
			"bankCardFrontPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"bankCardBackPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"openAccountLicencePic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"noLegalHandSettleAuthPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"noLegalSettleAuthPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"noLegalIdCardFrontPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			},
			"noLegalIdCardBackPic": {
				"url": "",
				"wechatId": "",
				"alipayId": ""
			}
		}
	})

	import {
		addEntryManager,
		getEntryManager
	} from '@/http/api/order/entryManager.js'
	onLoad((opt) => {
		if (opt.licenceNo && opt.shopId) {
			getEntryManager(opt).then(res => {

				res.merchantBaseInfo.contactPersonIdEndDate = dayjs(res.merchantBaseInfo
					.contactPersonIdEndDate).valueOf()
				res.merchantBaseInfo.contactPersonIdStartDate = dayjs(res.merchantBaseInfo
					.contactPersonIdStartDate).valueOf()

				res.legalPersonInfo.legalIdPersonStartDate = dayjs(res.legalPersonInfo
					.legalIdPersonStartDate).valueOf()
				res.legalPersonInfo.legalPersonIdEndDate = dayjs(res.legalPersonInfo
					.legalPersonIdEndDate).valueOf()
				res.businessLicenceInfo.licenceStartDate = dayjs(res.businessLicenceInfo
					.licenceStartDate).valueOf()
				res.businessLicenceInfo.licenceEndDate = dayjs(res.businessLicenceInfo
					.licenceEndDate).valueOf()


				Object.assign(form, res)
			})

		} else {
			// const data = uni.getStorageSync('entryManager_submit_data')
			// if (data) {
			// 	Object.assign(form, data)
			// }
			form.shopId = opt.shopId || ''
		}

		watch(() => form, (newval) => {
			uni.setStorageSync('entryManager_submit_data', form)
		}, {
			deep: true,
			immediate: true
		})
	})

	function returnSettlementInfoRule() {
		let rule = {
			...rules.settlementInfo
		}
		if (form.settlementType * 1 == 0) {
			rule = {
				...rule,
				'noLegalHandSettleAuthPic.url': {
					required: true,
					errorMsg: '请上传非法人手持结算授权书',
				},
				'noLegalSettleAuthPic.url': {
					required: true,
					errorMsg: '请上传非法人结算授权书',
				},
				'noLegalIdCardFrontPic.url': {
					required: true,
					errorMsg: '请上传非法人身份证正面',
				},
				'noLegalIdCardBackPic.url': {
					required: true,
					errorMsg: '请上传非法人身份证反面',
				},
				noLegalName: {
					required: true,
					errorMsg: '请填写非法人姓名',
				},
				noLegalName: {
					required: true,
					errorMsg: '请填写非法人身份证号码',
				}
			}
		}
		if (form.settlementCardType * 1 == 21) {
			rule = {
				'bankCardBackPic.url': {
					required: true,
					errorMsg: '请上传银行卡反面照片',
				}
			}
		}
		return rule
	}

	function returnMerchantBaseInfoRule() {
		let rule = rules.merchantBaseInfo
		if (form.merchantBaseInfo.contactPersonType == 'SUPER') {
			rule = {
				...rule,
				'contactIdCardFrontPic.url': {
					required: true,
					errorMsg: '请上传联系人身份证正面照片',
				},
				'contactIdCardBackPic.url': {
					required: true,
					errorMsg: '请上传联系人身份证反面照片',
				},
				contactName: {
					required: true,
					errorMsg: '请填写联系人姓名',
				},
				contactPersonId: {
					required: true,
					errorMsg: '请填写联系人身份证号',
				},
				contactPersonIdStartDate: {
					required: true,
					errorMsg: '请填写联系人身份证开始日期',
				},
				contactPersonIdEndDate: {
					required: true,
					errorMsg: '请填写联系人身份证到期日期',
				},
				contactPhone: {
					required: true,
					errorMsg: '请填写联系人电话',
				},
				contactAddr: {
					required: true,
					errorMsg: '请填写联系人通讯地址',
				},
				contactEmail: {
					required: true,
					errorMsg: '请填写联系人邮箱',
				}
			}
		}
		console.log('rule', rule);
		return rule
	}
	const maxSize = ref(2)
	const step = ref(0)

	
	const ruleArr=['merchantBaseInfo','legalPersonInfo','businessLicenceInfo','storeInfo','settlementInfo']
	function stepItemClick(newStep) {
		
		const arr=ruleArr.slice(0,newStep-1)
		let isPas = true
		let result = null
		for (let index in arr) {
			const key=arr[index]
			if (key == 'settlementInfo') {
				result = verifyData(form[key], returnSettlementInfoRule())
			} else if (key == 'merchantBaseInfo') {
				result = verifyData(form[key], returnMerchantBaseInfoRule())
			} else {
				result = verifyData(form[key], rules[key])
			}
			if (!result.ispas) {
				uni.showToast({
					title: result.errorMsg || '请完善必填内容',
					icon: 'none'
				})
				result.step = index
				return result
			}
		}
		step.value = newStep
	}



	function verifyForm(step = null) {
		let result = {
			ispas: true,
			errorMsg: '',
			step: -1,
		}
		if (step != null) {
			if (step == 0) {
				result = verifyData(form.merchantBaseInfo, returnMerchantBaseInfoRule())
				result.step = 0;
			}
			if (step == 1) {
				result = verifyData(form.legalPersonInfo, rules.legalPersonInfo)
				result.step = 1;
			}
			if (step == 2) {
				result = verifyData(form.businessLicenceInfo, rules.businessLicenceInfo)
				result.step = 2;
			}
			if (step == 3) {
				result = verifyData(form.storeInfo, rules.storeInfo)
				result.step = 3;
			}
			if (step == 4) {
				result = verifyData(form.storeInfo, returnSettlementInfoRule())
				result.step = 4;
			}

		} else {
			let isPas = true
			let errorMsg = '';
			let result = null
			let index = -1;
			for (let key in rules) {
				index++
				if (key == 'settlementInfo') {
					result = verifyData(form[key], returnSettlementInfoRule())
				} else if (key == 'merchantBaseInfo') {
					result = verifyData(form[key], returnMerchantBaseInfoRule())
				} else {
					result = verifyData(form[key], rules[key])
				}
				if (!result.ispas) {
					uni.showToast({
						title: errorMsg || '请完善必填内容',
						icon: 'none'
					})
					result.step = index
					return result
				}
			}


		}

		return result;
	}

	function saveClick() {

		if (step.value == 4) {
			const {
				ispas,
				errorMsg,
				step: errorStep
			} = verifyForm()
			console.log(form.settlementInfo);
			if (!ispas) {
				uni.showToast({
					title: errorMsg || '请完善必填内容',
					icon: 'none'
				})
				step.value = errorStep
				return
			}
		}
		if (step.value < 4) {
			const {
				ispas,
				errorMsg,
				step: errorStep
			} = verifyForm(step.value)
			console.log('ispas', ispas);
			console.log('errorMsg', errorMsg);
			console.log('errorStep', errorStep);
			if (!ispas) {
				uni.showToast({
					title: errorMsg || '请完善必填内容',
					icon: 'none'
				})
				return
			}
		}

		if (step.value != 4) {
			step.value++
			return
		}

		const merchantBaseInfo = {
			...form.merchantBaseInfo,
			contactPersonIdEndDate: dayjs(form.merchantBaseInfo.contactPersonIdEndDate).format('YYY-MM-DD'),
			contactPersonIdStartDate: dayjs(form.merchantBaseInfo.contactPersonIdStartDate).format('YYY-MM-DD'),
		}
		const legalPersonInfo = {
			...form.legalPersonInfo,
			legalIdPersonStartDate: dayjs(form.legalPersonInfo.legalIdPersonStartDate).format('YYYY-MM-DD'),
			legalPersonIdEndDate: dayjs(form.legalPersonInfo.legalPersonIdEndDate).format('YYYY-MM-DD'),
		}
		const businessLicenceInfo = {
			...form.businessLicenceInfo,
			licenceStartDate: dayjs(form.businessLicenceInfo.licenceStartDate).format('YYYY-MM-DD'),
			licenceEndDate: dayjs(form.businessLicenceInfo.licenceEndDate).format('YYYY-MM-DD'),
		}

		addEntryManager({
			...form,
			merchantBaseInfo,
			legalPersonInfo,
			businessLicenceInfo
		}).then(res => {
			if (res) {
				uni.showToast({
					title: '提交成功',
				})
				uni.removeStorageSync('entryManager_submit_data')
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			} else {
				uni.showToast({
					title: '提交失败',
					icon: 'error'
				})
			}
		})

		return
	}

	function cancelClick() {
		if (step.value == 0) {
			return uni.navigateBack()
		}
		step.value--;
	}

	function update(value, key) {
		if (form.hasOwnProperty(key)) {
			form[key] = value
		}
	}


	const cancelText = computed(() => {
		if (step.value == 0) {
			return '返回'
		}
		return '上一步'
	})
	const confirmText = computed(() => {
		if (step.value == 4) {
			return '提交'
		}
		return '下一步'
	})
	onMounted(() => {

	})
</script>

<style lang="scss" scoped>
	.min-page {
		padding: 32rpx 28rpx;
	}

	.container {
		padding: 32rpx 28rpx;
		border-radius: 16rpx;
		margin-bottom: 32rpx;
		background-color: #fff;
	}
</style>