<template>
	<div class="container">
		<image class="greenbgc" src="https://www.focusnu.com/media/directive/index/greenbgc.png" />
		<view class="title-back" :style="{height:`${uni.getStorageSync('moveHeight')+40}px`}">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">入驻登记表</view>
			</view>
		</view>
		<view :style="{height:`${uni.getStorageSync('moveHeight') + 40}px`}"></view>
		<view class="white-content" style="margin-top: 20rpx;">
			<view class="content-title">
				<view class="shu"></view>
				<view class="content-weight">供应商信息</view>
			</view>
			<view class="white-message">
				<view>
					<view class="one">
						<view class="one-left">供应商名称</view>
						<input class="one-right" maxlength="20" placeholder="请输入供应商名称" v-model="form.suppliersName" />
					</view>
					<view class="one" style="position: relative;" @click="showmarry = true">
						<view class="one-left">供应商性质</view>
						<input disabled style="cursor: not-allowed;pointer-events: none;" class="one-right" type="text"
							placeholder="请选择供应商性质" v-model="form.name" />
						<image class="triangle-down" src="https://www.focusnu.com/media/directive/login/xia.png" />
					</view>
					<u-select style="font-size: 35rpx;" v-model="showmarry" :list="showmarrylist"
						@confirm="confirmmarry"></u-select>
					<view class="one">
						<view class="one-left">供应商地址</view>
						<input class="one-right" maxlength="30" placeholder="请输入供应商地址"
							v-model="form.suppliersAddress" />
					</view>
					<view class="one">
						<view class="one-left">负责人</view>
						<input class="one-right" maxlength="10" placeholder="请输入负责人" v-model="form.personInCharge" />
					</view>
					<view class="one">
						<view class="one-left">联系电话</view>
						<input class="one-right" type="number" maxlength="11" placeholder="请输入联系电话"
							v-model="form.contactNumber" />
					</view>
					<view class="one">
						<view class="one-left">开户行</view>
						<input class="one-right" maxlength="20" placeholder="请输入开户行" v-model="form.openingBank" />
					</view>
					<view class="one">
						<view class="one-left">开户行账号</view>
						<input class="one-right" maxlength="20" placeholder="请输入开户行账号" v-model="form.openingBankNo" />
					</view>
				</view>
			</view>

			
		</view>
		<view class="white-content">
			<view class="content-title" style="margin-bottom: 25rpx;">
				<view class="shu"></view>
				<view class="content-weight">资质照片</view>
			</view>
			<view class="white-photo" @click="selectphoto()">
				<view class="photo-left">
					<view class="photo-weight">资质照片</view>
					<view class="photo-font">请上传资质照片</view>
				</view>
				<view style="position: relative;">
					<image class="photo"
						:src="form.imgPath ? `${media_base_url}${form.imgPath}` : `https://www.focusnu.com/media/directive/index/zizhi.png`" />
					<image style="width: 100%;height: 100%;top: 0;left: 0;z-index: 1;position: absolute;"
						:src="form.imgPath ? `` : `https://www.focusnu.com/media/directive/index/bian.png`" />
					<image v-if="!form.imgPath"
						style="position: absolute;top: 50%;left: 50%;width: 70rpx;height: 60rpx;transform: translate(-50%,-50%);"
						src="https://www.focusnu.com/media/directive/index/takephoto.png" />
				</view>
		
			</view>
		</view>
		<view style="display: flex;width: 100%;">
			<view class="finish-button" @click="next">
				确认并提交
			</view>
		</view>
		<u-action-sheet :list="bottomlist" @click="photoclick" v-model="bottomshow"></u-action-sheet>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		media_base_url,
		base_url
	} from '@/request/index.js';
	import {
		addSuppliers,
		editSuppliers,
		applySupOrg
	} from './api/api.js'
	import model from "@/compontent/public/model.vue"


	const uping = ref(true);
	const showmarry = ref(false);
	const showmarrylist = reactive(
		[{
				value: '代理商',
				label: '代理商',
			},
			{
				value: '批发商',
				label: '批发商',
			},
			{
				value: '制造商',
				label: '制造商',
			},
		]
	)
	const bottomlist = [{
		text: '拍摄图片',
		fontSize: 40
	}, {
		text: '图片预览',
		fontSize: 40
	}]


	const confirmmarry = (item) => {
		form.name = item[0].value
		form.suppliersNature = String(item[0].index + 1)
	}


	const form = reactive({
		// 供应商名称
		suppliersName: "",
		suppliersNature: ``, //供应商性质 1代理商 2批发商 3制造商
		// 供应商地址
		suppliersAddress: "",
		// 负责人
		personInCharge: "",
		// 联系电话
		contactNumber: "",
		// 开户行
		openingBank: "",
		// 开户行账号
		openingBankNo: "",
		// 资质照片
		imgPath: "",
		name: "",
		openId: uni.getStorageSync('openid'),
	})
	const bottomshow = ref(false)
	const selectphoto = () => {

		if (!uping.value) {
			return
		}
		// imgetarget.value = number
		if (form.imgPath) {
			bottomshow.value = true;
		} else {
			getMessage()
		}

	}
	const photoclick = (element) => {
		if (element) {
			uni.previewImage({
				urls: [`${media_base_url}${form.imgPath}`], // 必填，所有要预览的图片地址数组
				// current: headImge.value, // 可选，当前显示图片的地址，默认是 urls[0]
				indicator: 'default', // 可选，指示器样式，H5/App 有效，值为 'default'（圆点）或 'number'（数字）
				longPressActions: { // 可选，仅 App 支持，长按图片时弹出的操作项
					itemList: ['保存图片到相册'],
				},
			});
		} else {
			getMessage()
		}

	}
	// 拍照并上传
	function getMessage() {

		uni.chooseImage({
			count: 1,
			sourceType: ['album', 'camera'],
			success: chooseRes => {
				// tempImagePath.value = chooseRes.tempFilePaths[0]
				uni.navigateTo({
					url: `/compontent/public/camera?url=${chooseRes.tempFilePaths[0]}&type=0&size=1`
				});
			},
			fail: err => {
				console.error('拍照失败：', err)
			}
		})
	}
	onShow(() => {
		const img = uni.getStorageSync('imgkey0')
		if (img) {
			// uploadImage(img)
			savephoto(img)
			uni.removeStorageSync('imgkey0')
		}
	})
	const savephoto = (filePath) => {
		uping.value = false;
		// category: 'jg' | 'yg' | 'zz' | 'jhr'
		const now = new Date();
		const yyyy = now.getFullYear();
		const mm = String(now.getMonth() + 1).padStart(2, '0'); // 补0
		let path = '';

		switch ('') {
			case 'jg': // 机构
				path = `${yyyy}/${mm}/jgxx/jg`;
				break;
			case 'yg': // 员工
				path = `${yyyy}/${mm}/ygxx/yg`;
				break;
			case 'zz': // 长者
				path = `${yyyy}/${mm}/zzxx/zz`;
				break;
			case 'jhr': // 监护人
				path = `${yyyy}/${mm}/zzxx/jhr`;
				break;
			default:
				path = `${yyyy}/${mm}/temp`;
		}
		uni.uploadFile({
			url: `${base_url}/sys/common/upload`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {
				biz: path
			},
			success: uploadRes => {
				// imgArray[imgetarget.value] = JSON.parse(uploadRes.data).message
				form.imgPath = JSON.parse(uploadRes.data).message
				// console.log("??///",form.imgPath)
				// fontphoto.value = JSON.parse(uploadRes.data).message;
				uping.value = true;
				uni.hideLoading()
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}

	function isValid11DigitNumber(val) {
		return /^1[3-9]\d{9}$/.test(val);
	}
	const next = () => {
		if (!uping.value) {
			return
		}
		console.log("form", form)
		if (!form.suppliersName) {
			uni.showToast({
				title: '请填写供应商名称',
				icon: 'none'
			})
		} else if (!form.suppliersNature) {
			uni.showToast({
				title: '请选择供应商性质',
				icon: 'none'
			})
		} else if (!form.suppliersAddress) {
			uni.showToast({
				title: '请填写供应商地址',
				icon: 'none'
			})
		} else if (!form.personInCharge) {
			uni.showToast({
				title: '请填写负责人',
				icon: 'none'
			})
		} else if (!form.contactNumber) {
			uni.showToast({
				title: '请填写手机号',
				icon: 'none'
			})
		} else if (!isValid11DigitNumber(form.contactNumber)) {
			uni.showToast({
				title: '手机号格式错误',
				icon: 'none'
			})

		} else if (!form.openingBank) {
			uni.showToast({
				title: '请填写开户行',
				icon: 'none'
			})

		} else if (!form.openingBankNo) {
			uni.showToast({
				title: '请填写开户行账号',
				icon: 'none'
			})

		} else if (!form.imgPath) {
			uni.showToast({
				title: '请上传资质照片',
				icon: 'none'
			})

		} else {
			gotopush()
		}


	}
	const gotopush = () => {
		if (form.id) {
			editSuppliers(form).then((res) => {
				// console.log("res",res)
				if (res.code == 200) {
					uni.setStorageSync(
						'isstaffchange', true);
					uni.reLaunch({
						url: `/pages/addsupplier/successpush`
					});
				}
			})
		} else {
			addSuppliers(form).then((res) => {
				let data = {
					orgCode: uni.getStorageSync('nostaffmessage'),
					openId: uni.getStorageSync('openid')
				}
				applySupOrg(data).then((data) => {
					if (data.success) {
						uni.requestSubscribeMessage({
							// 这里填后台申请好的 templateId 数组
							tmplIds: ['cWVzXm1C-iitx1gNFn1nZdijq9R_3fCv8vLbiqs9zww'],
							success: (res) => {

								setTimeout(() =>

									{
										uni.setStorageSync(
											'isstaffchange', false);
										uni.reLaunch({
											url: `/pages/addsupplier/successpush`
										});
									}

									, 1000)
							},
							fail: (err) => {
								console.error('订阅接口调用失败：', err);
								uni.showToast({
									title: '订阅失败',
									icon: 'none'
								});
							}
						});


					}


				})
				// console.log("res",res)
				// if (res.code == 200) {
				// 	uni.setStorageSync(
				// 		'isstaffchange', false);
				// 	uni.reLaunch({
				// 		url: `/pages/addsupplier/successpush`
				// 	});
				// }
			})
		}

	}
	const goBack = () => {
		uni.navigateBack()
	}

	onLoad((param) => {
		// console.log("param",JSON.parse(param.element))
		// form = JSON.parse(param.element)
		Object.assign(form, JSON.parse(param.element))
		form.name = showmarrylist[Number(form.suppliersNature) - 1].value
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		width: 100%;
		background-color: #F7F7F7;
		position: relative;

		.white-content {
			width: 90%;
			margin-left: 5%;
			border-radius: 35rpx;

			.content-title {
				display: flex;
				align-items: center;
				height: 100rpx;
				position: relative;
				font-weight: 600;
				

				.content-weight {
					font-size: 32rpx;
				}

				.content-img {
					position: absolute;
					right: 0;
					top: 0;
					width: 400rpx;
					height: 100%;
				}
			}
		}
	}


	.finish-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 80%;
		height: 90rpx;
		margin: 0rpx auto;
		margin-bottom: 80rpx;
		margin-top: 20rpx;
		background: linear-gradient(to bottom, #e7f4ff, #c5e5ff);
		border: 2rpx solid #9AD1FF;
		color: #007CFF;
		border-radius: 35rpx;
		font-size: 33rpx;
	}

	.title-back {
		background-color: #F7F7F7;
		width: 100%;
		height: 70rpx;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #cbd1d2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;
	}

	.left-father {
		display: flex;
		align-items: center;

		.back-img {
			width: 45rpx;
			height: 40rpx;
			margin-left: 40rpx;
			margin-right: 15rpx;
		}
	}

	.shu {
		width: 14rpx;
		height: 36rpx;
		background-color: #0097FF;
		border-radius: 10rpx;
		margin: 3rpx 20rpx 0 30rpx;
	}

	.line {
		margin: 10rpx 0;
	}


	.white-message {
		width: 100%;
		margin-top: 20rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		margin-bottom: 30rpx;
		border-radius: 35rpx;
		background-color: #fff;
		justify-content: space-around;
		display: flex;
		flex-direction: column;
	}

	.one {
		width: 90%;
		margin-left: 5%;
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;

		.one-left {
			margin-left: 10rpx;
			font-size: 30rpx;
			z-index: 999;
		}

		.one-right {
			font-size: 30rpx;
			height: 100%;
			color: #999999;
			overflow: hidden;
			/* 隐藏超出内容 */
			white-space: nowrap;
			/* 不换行 */
			// font-size: 25rpx;
			text-overflow: ellipsis;
			width: 350rpx;
			display: flex;
		}

		.triangle-down {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 26rpx;
			width: 20rpx;
			height: 20rpx;
		}
	}

	.triangle-down-mi {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: 26rpx;
		font-size: 30rpx;
		color: #999999;
	}

	.greenbgc {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 700rpx;
	}

	.white-photo {
		width: 100%;
		height: 300rpx;
		border-radius: 35rpx;
		background-color: #fff;
		justify-content: space-around;
		align-items: center;
		display: flex;

		.photo-left {
			.photo-weight {
				font-size: 30rpx;
				font-weight: 600;
			}

			.photo-font {
				font-size: 28rpx;
				margin-top: 10rpx;
			}

		}

		.photo {
			width: 300rpx;
			height: 200rpx;
		}
	}
</style>