<template>
	<view>
		<image class='bg-image' mode="widthFix"
			src="https://qtzl.etcjz.cn/default-bucket/20240324/3eba2095f5204798a1f8101b_beijing.jpg"></image>
		<view class="content-re">
			<custom-header title="用户信息" :back="config.hasReturn === 'true'"></custom-header>
			<view v-if="isShow">
				<formBuilderVue :formData="formData" :config="config" @radioChange="radioChange" @submit="submit"
					@uploadImgOcr="uploadImg"></formBuilderVue>
			</view>
		</view>
		<agreementfrom />
	</view>
</template>

<script setup lang='ts'>
	import {
		unifyTemplate
	} from '@/hooks/unifyTemplate'
	import {
		TypeData,
		Index
	} from '@/components/form-builder/tools'
	import agreementfrom from './components/agreement'
	import {
		ref,
		nextTick
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		requestNew,
		request
	} from '@/utils/network/request'
	import fromData from './fromData'
	import ocrHandle from './ocrHandle'
	import {
		setToken,
		setItem,
		StorageKeys
	} from '@/utils/storage'
	// import {
	// 	userInfoFormData
	// } from '@/utils/formDataHandle'
	let config = ref < any > ({
		hasReturn: 'false',
		submitName: '下一步',
		titleWidth: 180,
		isHeader: true,
	})
	let formData = ref < any > (fromData)

	const {
		formBuilderVue, //组件
		CustomHeader, //头部组件
		initData, //初始化数据
		isShow, //是否展示formBuilderVue组件
		qdOrderVal //qdOrder中数据 ref
	} = unifyTemplate() //初始化数据
	//获取页面配置
	onLoad((opin) => {
		// 初始化数据
		initData(opin, 1).then(data => {
			// formData.value = userInfoFormData(data.order, JSON.parse(data.config.tableConfig))
			formData.value = JSON.parse(data.config.tableConfig)
			let keys = hanToNext(data.order)
			if(keys) return
			nextTick(() => {
				if (data.order.userType === 'PERSONAL_USER') {
					// 个人办理
					danChange(false)
				} else {
					// 单位办理
					danChange(true)
				}
			})
			isShow.value = true
			console.log('新版', formData.value)
			handleMobile(data)//处理联系方式
			handleAgentTel(data)//处理经办人电话
			delete data.config.tableConfig
			config.value = Object.assign(data.config, config.value)
		})
	})

	function hanToNext(order) {
		let url = ''
		if (order.orderStep === 2) {
			url = '/pages/drivingLicense/drivingLicense'
		} else if (order.orderStep !== 1) {
			url = '/pages/payment/payment' 
		}
		if (url) {
			uni.navigateTo({
				url: url + `?qdOrderNo=${qdOrderVal.value.orderNo}`,
				animationType: 'pop-in',
				animationDuration: 500
			})
			return true
		}
		return false
	}

	function handleMobile(data) {
		const itemData = formData.value[Index('联系方式', formData.value)]
		if (data.order.customerTel) {
			itemData[itemData.value] = data.order.customerTel || ''
			itemData.disabled = true
		}
	}
	function handleAgentTel(data) {
		const itemData = formData.value[Index('经办人电话', formData.value)]
		if (data.order.customerTel) {
			itemData[itemData.value] = data.order.customerTel || ''
			itemData.disabled = true
		}
	}
	//初始判断单位办理还是个人办理
	function danChange(key) {
		if (key) {
			submitCode = '20'
			// 单位办理
			businesses(false)
			handleDan(false)
			formData.value[Index('部门名称', formData.value)].department = '本部'

		} else {
			submitCode = '22'
			// 个人办理
			businesses(true)
			handleDan(true)
		}
	}
	//单项选择器
	function radioChange(e: any, item: TypeData) {
		if (item.title === '本人办理') {
			if (e.detail.value === '1') {
				businesses(true)
			} else {
				businesses(false)
			}
		}
	}
	//本人办理还是他人办理 ,true为本人办理
	function businesses(key: Boolean) {
		formData.value[Index('委托书', formData.value)].show = key
		formData.value[Index('本人办理', formData.value)].underline = key
		formData.value[Index('经办人姓名', formData.value)].show = key
		formData.value[Index('经办人证件号码', formData.value)].show = key
		formData.value[Index('经办人电话', formData.value)].show = key
		formData.value[Index('经办人证件识别信息如下', formData.value)].show = key
		formData.value[Index('经办人证件人像面', formData.value)].show = key
		formData.value[Index('经办人证件国徽面', formData.value)].show = key
	}
	// 个人办理还是单位办理 true为个人办理
	function handleDan(key) {
		formData.value[Index('营业执照', formData.value)].show = key
		formData.value[Index('委托书', formData.value)].show = key
		formData.value[Index('公司名称', formData.value)].show = key
		formData.value[Index('部门名称', formData.value)].show = key
		formData.value[Index('社会信用代码', formData.value)].show = key
		// formData.value[Index('住址', formData.value)].show = !key
		formData.value[Index('本人办理', formData.value)].show = !key
		formData.value[Index('人像面', formData.value)].show = !key
		formData.value[Index('国徽面', formData.value)].show = !key
		formData.value[Index('证件号码', formData.value)].show = !key
		// formData.value[Index('住址', formData.value)].show = !key
		formData.value[Index('姓名', formData.value)].show = !key
		formData.value[Index('联系方式', formData.value)].show = !key
	}

	// 提交个人信息接口
	let submitCode = '22'
	// ocr图片处理和额外请求参数处理
	const {
		uploadImgHandle,
		submitQuery
	} = ocrHandle()

	function uploadImg(fileList, item) {
		uploadImgHandle(fileList, item, formData)
	}
	async function submit(item: any) {
		try {
			if (isLock.value) return
			isLock.value = true
			let data = {
				...submitQuery.value,
				agentId: qdOrderVal.value.agencyId, //渠道编号
				channelId: qdOrderVal.value.channelId, //网点编号
				channelType: qdOrderVal.value.promotionModes, //网点类型
				source: qdOrderVal.value.orderSource, //订单来源
				orderNo: qdOrderVal.value.orderNo //订单id
			}
			// 处理参数，为空的不携带
			for (const key in item) {
				if (item[key] || item[key] === 0 || item[key] === false) {
					data[key] = item[key]
				}
			}
			console.log(data, 'isAgent之前');
			data.isAgent = +data.isAgent === 1 ? false : true
			const openIdKey = await register(data)
			if (!openIdKey) {
				return
			}
			// promotionModes是1，openId的值是userId
			// promotionModes是2，openId的值是staffId，
			if (qdOrderVal.value.promotionModes === 2) {
				data.openId = qdOrderVal.value.staffId //操作人id
			} else if (qdOrderVal.value.promotionModes === 1) {
				data.openId = qdOrderVal.value.userId //操作人id
			}
			let {
				jumpPage
			} = config.value
			data.userAddress = data.userAddress || data.address

			let options = {
				type: 2,
				data: data,
				method: 'POST',
				showLoading: true
			}
			console.log(options, '请求参数')
			// return
			await request('ISSUES_ORDER_USERUPLOAD', options).then((res) => {
				console.log(res, 'res')
				if (res.statusCode === 0) {
					uni.navigateTo({
						url: '/' + jumpPage + `?qdOrderNo=${qdOrderVal.value.orderNo}`,
						animationType: 'pop-in',
						animationDuration: 500
					})
				}

			})

		} catch (e) {
			//TODO handle the exception
		} finally {
			isLock.value = false
		}

	}
	let isLock = ref(false)
	// 无感注册拿到openId
	function register(data: any) {
		let params: any = {}
		params.idNum = data.userIdNum;
		params.idType = data.userIdType;
		params.mobile = data.mobile || data.agentTel;
		params.userName = data.userName;
		params.gender = 'UNKOWN';
		params.certifyChannel = 'BAIDUOCR'; //实名渠道
		params.address = data.userAddress;

		if (data.isSelf === '0' || submitCode === '20') {
			// 他人办理
			params.agentIdNum = data.agentIdNum;
			params.agentIdType = data.agentIdType;
			params.agentName = data.agentName;
		}
		if (submitCode === '20') {
			// 单位办理
			params.userType = 'ENTERPRISE'
			params.department = data.department;
		} else {
			params.userType = 'PERSONAL'
		}
		console.log(params, 'params', submitCode);
		return requestNew('/iaw/issue/userBasic/registerFull', {
			data: params,
		}).then((res) => {
			console.log(res, 'fanhui');
			if (res.code === 0) {
				let data = res.data
				// 保存token
				setToken(data.accessToken)
				setItem(StorageKeys.OpenId, data.openId)
				return data.openId
			} else {
				return false
			}
		})
	}
</script>
<style lang='scss' scoped>

</style>