<template>
	<!-- 表单 -->
	<form @submit="formSubmit">
		<view v-for="(item, index) in formData" :key="index">
			<view v-show="!item.show">
				<!-- 是否显示-->
				<view style="min-height: 90rpx" :class="
            item.vertical === 2 ? 'as-layout-vertical' : 'as-layout-horizontal'
          ">
					<!-- 标题 -->
					<view class="as-gravity-center-start" :style="'min-width:' + config.titleWidth + 'rpx'" style="
              margin: 0 20rpx;
              flex-direction: row;
              display: flex;
              flex-direction: row;
            ">
						<image class="img-size" :src="item.required ? `${$imgUrl}must.png` : ''" mode="aspectFill">
						</image>
						<view :class="item.vertical === 2 ? 'text-left' : 'text-justify'" class="text-title"
							style="width: 100%">
							{{ item.title }}
						</view>
					</view>

					<!-- 内容 -->
					<view class="as-weight as-gravity-center-start">
						<!-- 文本内容 -->
						<view v-if="item.type === 1" class="text" :style="item.style">{{
              item[item.value]
            }}</view>
						<!-- 输入框 -->
						<view v-if="item.type === 2" style="width: 100%">
							<input :disabled="item.disabled" v-model="item[item.value]" :type="item.inputType"
								:placeholder="item.hint ? item.hint : '请输入' + item.title" placeholder-class="text-hint"
								class="text as-gravity-center-start" :maxlength="item.maxlength" :style="item.style"
								style="min-height: 90rpx; word-break: break-all" />
						</view>
						<!-- 多项选择器 -->
						<view v-if="item.type === 3">
							<checkbox-group @change="checkboxChange($event, item)" :disabled="item.disabled">
								<view class="as-layout-horizontal">
									<label style="
                      display: flex;
                      flex-direction: row;
                      margin-right: 30rpx;
                    " v-for="(itemData, index) in item.itemData" :key="index">
										<checkbox style="transform: scale(0.7)" :value="itemData.value"
											:checked="itemData.checked" />
										<view>{{ itemData.name }}</view>
									</label>
								</view>
							</checkbox-group>
						</view>
						<!-- 普通选择器 当 range 是一个 Array＜Object＞ 时，通过 range-key 来指定 Object 中 key 的值作为选择器显示内容  :range-key="item[item.value]"-->
						<view v-if="item.type === 4" style="width: 100%">
							<!-- range[范围] value[初始选择]-->
							<picker :disabled="item.disabled" :range-key="item.itemKey"
								:mode="item.mode ? item.mode : 'selector'" @change="bindPickerChange($event, item)"
								:range="item.itemData">
								<view class="text">
									{{
                    item[item.value]
                      ? item.itemKey
                        ? item[item.value][item.itemKey]
                        : item[item.value]
                      : item.hint
                      ? item.hint
                      : "请选择" + item.title
                  }}
								</view>
							</picker>
						</view>

						<!-- 富文本框 -->
						<view v-if="item.type === 5" style="width: 100%">
							<view>
								<textarea :disabled="item.disabled" class="text" v-model="item[item.value]"
									@input="textareaInput($event, item)" placeholder-class="text-hint"
									style="width: 100%" :maxlength="item.maxlength" auto-height
									:placeholder="item.hint ? item.hint : '请输入' + item.title">
                </textarea>
								<view v-if="item.maxlength" class="as-gravity-center-end"
									style="display: flex; flex-direction: row; height: 20%">
									<view class="text">{{ !item.num ? "0" : item.num }}</view>
									<view class="text">/{{ item.maxlength ? item.maxlength : 100 }}</view>
								</view>
							</view>
						</view>

						<!-- 图片选择器  :imgWidth="imgWidth ? imgWidth : 0"-->
						<view v-if="item.type === 6" style="width: 100%">
							<form-image @backImg="backImg($event, item)" style="width: 100%" :retract="40"></form-image>
						</view>

						<!-- 单向选择器 -->
						<view v-if="item.type === 7" style="width: 100%">
							<radio-group @change="radioChange($event, item)">
								<view class="as-layout-horizontal">
									<label style="
                      display: flex;
                      flex-direction: row;
                      margin-right: 30rpx;
                    " v-for="(itemData, index) in item.itemData" :key="index">
										<radio style="transform: scale(0.7)" :value="itemData.value"
											:checked="itemData.checked" />
										<view>{{ itemData.name }}</view>
									</label>
								</view>
							</radio-group>
						</view>

						<!-- 证件照上传 -->
						<view v-if="item.type === 8" style="width: 100%">
							<view style="margin: 0 40rpx">
								<view class="text-error">{{ item.hint }}</view>
								<view class="as-layout-horizontal as-gravity-center"
									style="height: 250rpx; margin-top: 20rpx">
									<view class="as-layout-vertical" style="width: 90%; height: 100%">
										<image mode="aspectFill" :src="
                        item.placeholderImg1
                          ? item.placeholderImg1
                          : `${$imgUrl}license2.png`
                      " style="width: 100%; height: 80%" @tap="ImageSelection(item, 1)"></image>
										<view class="as-gravity-center text-hint" style="margin-top: 5rpx">
											{{ item.hint1 }}
										</view>
									</view>
									<view style="width: 40rpx"></view>
									<view class="as-layout-vertical" style="width: 90%; height: 100%">
										<image :src="
                        item.placeholderImg2
                          ? item.placeholderImg2
                          : `${$imgUrl}license2.png`
                      " style="width: 100%; height: 80%" @tap="ImageSelection(item, 2)" mode="aspectFill"></image>
										<view class="as-gravity-center text-hint" style="margin-top: 5rpx">
											{{ item.hint2 }}
										</view>
									</view>
								</view>
							</view>
						</view>

						<!-- 车牌号输入 -->
						<view v-if="item.type === 9" style="width: 100%">
							<view style="margin: 20rpx 30rpx 0 30rpx">
								<car-num-ber-input @numberInputResult="numberInputResult($event, item)">
								</car-num-ber-input>
							</view>
						</view>

						<!-- 车牌号输入 -->
						<view v-if="item.type === 10" style="width: 100%">
							<pick-regions :defaultRegion="defaultRegionCode" @getRegion="handleGetRegion($event, item)">
								<view class="text">
									{{
                    item[item.value]
                      ? item.itemKey
                        ? item[item.value][item.itemKey]
                        : item[item.value]
                      : item.hint
                      ? item.hint
                      : "请选择" + item.title
                  }}
								</view>
							</pick-regions>
						</view>
					</view>
				</view>

				<view v-show="index !== formData.length - 1 && !item.underline" class="as-line3"
					style="margin: 0rpx 20rpx 0rpx 20rpx"></view>
			</view>
		</view>

		<button class="btn btn-text as-gravity-center" form-type="submit">
			{{ config ? config.submitName : "提交" }}
		</button>
	</form>
</template>
<script setup lang="ts">
	import { TypeData } from "./tools";
	import { request } from "@/utils/network/request.js";
	import carNumBerInput from "@/components/car-number-input/car-number-input";
	import { pathToBase64 } from "@/utils/util/imageTool.js";
	import pickRegions from "@/login/pick-regions/pick-regions.vue";
	import { fileURL } from "@/datas/fileURL.js";

	const defaultRegionCode = "520115";
	const props = defineProps({
		formData: {
			type: Array as () => Array<TypeData>,
			default: () => [],
		},
		config: {
			type: Object,
			default: function () {
				return {
					submitName: "提交", //提交按钮名称
					titleWidth: 160, //标题宽度
				};
			},
		},
	});

	//defineEmits
	const emit = defineEmits<{
		(e : "submit", content : any) : void;
		(e : "uploadImg", content : any, item : TypeData, index : Number) : void;
		(e : "radioChange", event : any, item : TypeData) : void;
	}>();
	//defineExpose 可宏来显式指定在 <script setup> 组件中要暴露出去的属性。

	//普通选择器
	function bindPickerChange(e : any, item : TypeData) {
		let select = e.target.value;
		// #ifdef H5
		select = e.detail.value;
		// #endif
		if (item.mode === "date" || item.mode === "time") {
			/* 日期选择器*/
			item[item.value] = select;
		} else {
			/* 普通选择器*/
			item[item.value] = item.itemData[select];
		}
	}

	// 获取选择的地区
	function handleGetRegion(e : any, item : TypeData) {
		console.log("输出内容", e);
		item[item.value] = e[0].name + "-" + e[1].name + "-" + e[2].name;
	}

	//多项选择器
	function checkboxChange(e : any, item : TypeData) {
		item[item.value] = e.detail.value; /* 赋值*/
	}

	//单项选择器
	function radioChange(e : any, item : TypeData) {
		item[item.value] = e.detail.value; /* 赋值*/
		emit("radioChange", e, item);
	}

	//富文本框输入内容
	function textareaInput(e : Event, item : TypeData) {
		item.num = item[item.value].length;
	}

	//点击图片按钮
	function backImg(e : Event, item : TypeData) {
		item[item.value] = e;
	}

	//车牌输入
	function numberInputResult(e : Event, item : TypeData) {
		console.log("输出内容", e);
		item[item.value] = e;
	}

	//选择图片按钮
	function ImageSelection(item : TypeData, index : number) {
		uni.chooseImage({
			count: 1, //最多可以选择的文件个数
			sourceType: ["camera"], //album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
			success(res : any) {
				if (res.tempFiles[0].size > 2000000) {
					uni.showToast({
						title: "图片大于2M，请重新上传",
						icon: "none",
						duration: 1500,
					});
					return;
				}

				// #ifdef MP-WEIXIN
				uni.getFileSystemManager().readFile({
					filePath: res.tempFiles[0].tempFilePath, //要读取的文件的路径
					encoding: "base64", //编码格式
					success: (res) => {
						let imgBase64 = res.data;
						let reqData = {
							imageBase: imgBase64,
							accountNum: "qtzl_xcx",
							secretKey: "4DE47302-EDC7-41D4-888F-59A79DF4EA46",
						};
						//上传给服务器
						uni.showLoading({
							title: "正在加载中...",
							mask: true,
						});
						//文件上传
						request("", {
							baseUrl: "https://etcfile.etcjz.cn/v1/file/uploadImageBaseFile",
							data: reqData,
						}).then((content) => {
							uni.hideLoading();
							if (content.rc != "00") {
								uni.showModal({
									title: "请求错误",
									content: "图片上传失败",
									showCancel: false,
									confirmText: "取消",
								});
							}
							//处理后的 Data
							let data = {
								source: 2, //来源
								imageBase64: imgBase64,
								imageType: index,
								imageUrl: content.data.fileUrl,
							};
							emit("uploadImg", data, item, index);
						});
					},
					fail: (err) => {
						console.log("错误提示", err);
					},
				});
				// #endif

				// #ifdef H5
				pathToBase64(res.tempFilePaths[0]).then((data) => {
					let base64 = data.replaceAll("data:image/jpeg;base64,", "");
					base64 = base64.replaceAll("data:image/png;base64,", "");
					base64 = base64.replaceAll("data:image/jpg;base64,", "");
					let reqData = {
						imageBase: base64,
						accountNum: "qtzl_xcx",
						secretKey: "4DE47302-EDC7-41D4-888F-59A79DF4EA46",
					};
					//上传给服务器
					uni.showLoading({
						title: "文件上传中...",
						mask: true,
					});
					//文件上传
					request("", {
						baseUrl: "https://etcfile.etcjz.cn/v1/file/uploadImageBaseFile",
						data: reqData,
					})
						.then((content) => {
							console.log("上传结果", content);
							uni.hideLoading();
							if (content.rc != "00" && content.rc != 0) {
								uni.showModal({
									title: "请求错误",
									content: "图片上传失败",
									showCancel: false,
									confirmText: "取消",
								});
							}
							//展示缩略图
							if (index % 2 != 0) {
								//奇数第一张 偶数第二张
								item.placeholderImg1 = content.data.fileUrl;
								item[item.value.split(",")[0]] = content.data.fileUrl;
							} else {
								item.placeholderImg2 = content.data.fileUrl;
								item[item.value.split(",")[1]] = content.data.fileUrl;
							}
							//只展示缩略图
							if (!item.inputType) {
								emit("uploadImg", data, item, index);
							} else {
								//if(item.type === 1)
								//证件OCR识别
								uni.showLoading({
									title: "证件识别中...",
									mask: true,
								});
								let reqData2 = {
									imageDriveBase: "",
									imageBase64: base64,
									imageType: index % 2 != 0 ? 1 : 2, //1代表身份证正面，2代表反面
									imageUrl: content.data.fileUrl,
								};
								//默认身份证
								let code = "IF010012019070410001";
								if (item.inputType == "2") {
									//2为行驶证
									code = "IF010012019070410002";
									reqData2.imageBase64 = "";
									reqData2.imageDriveBase = base64;
								}
								request(code, {
									data: reqData2,
								}).then((ocr) => {
									uni.hideLoading();
									if (ocr.rc !== "00") {
										uni.showModal({
											title: "请求错误",
											content: "证件识别失败",
											showCancel: false,
											confirmText: "取消",
										});
									}
									let data = ocr.rd;
									//[身份证正面]姓名(name) 住址(address) 出生日期(birthday) 身份证号(idno) 民族(nation)
									//[身份证反面]证件机关(agency) 有效起始日期(begindate) 有效结束日期(enddate)
									emit("uploadImg", data, item, index);
								});
							}
						})
						.catch((e) => {
							console.log("输出内容", e);
						});
				});
				// #endif
			},
			fail(res : any) {
				if (!res.authSetting["scope.album"]) {
					uni.showModal({
						title: "授权失败",
						content: "需要从您的相机或相册获取图片，请在设置界面打开相关权限",
						success: (res) => {
							if (res.confirm) {
								uni.openSetting();
							}
						},
					});
				}
			},
		});
	}

	function showToast(hint : string) {
		uni.showToast({
			icon: "none",
			title: hint,
		});
	}

	//内容提交
	function formSubmit() {
		let content = {};
		/* 整理数据对象返回内容 */
		for (var i = 0; i < props.formData.length; i++) {
			let data = props.formData[i];
			/* 时间另外判断 */
			if (data.required) {
				let reg = new RegExp("：", "g"); //g代表全部
				let newMsg = data.title.replace(reg, "");
				if (data.value.indexOf(",") != -1 && data.type === 8) {
					if (!data[data.value.split(",")[0]]) {
						showToast(data.hint1 + "不能为空");
						return;
					} else if (!data[data.value.split(",")[1]]) {
						showToast(data.hint2 + "不能为空");
						return;
					}
				} else if (!data[data.value]) {
					showToast(newMsg + "不能为空");
					return;
				}
			}
			if (data.value.indexOf(",") != -1 && data.type === 8) {
				if (data[data.value.split(",")[0]]) {
					content[data.value.split(",")[0]] = data[data.value.split(",")[0]];
				}
				if (data[data.value.split(",")[1]]) {
					content[data.value.split(",")[1]] = data[data.value.split(",")[1]];
				}
			} else if (data.type === 10) {
				console.log("输出内容========", data);
				for (var i = 0; i < data.value.split(",").length; i++) {
					content[data.value.split(",")[i]] = data[data.value].split("-")[i];
				}
			} else {
				if (data.type === 4 && data.name) {
					content[data.value] = data[data.value][data.name];
				} else {
					content[data.value] = data[data.value];
				}
			}
		}
		emit("submit", content);
	}
</script>
<style lang="scss" scoped>
	.img-size {
		width: 30rpx;
		height: 30rpx;
	}

	.btn {
		height: 80rpx;
		background: #307afe;
		opacity: 1;
		border-radius: 100rpx;
		margin: 20rpx 20rpx 20rpx 20rpx;
	}

	.btn-text {
		color: #ffffff;
		font-size: 28rpx;
	}
</style>