<template>
	<s-layout title="添加新发票" class="set-userinfo-wrap" :bgStyle="{ background:'white !important' }">
		<!-- <view class="invoiceTitle">发票列表</view> -->
		<view class="invoiceHeader">
			<uni-forms ref="baseForm" label-width="200" :modelValue="state.baseFormData">
				<uni-forms-item label="抬头类型" required name="type">
					<uni-data-checkbox selectedColor="#7D9337" @change="headChange" v-model="state.baseFormData.type"
						:localdata="state.sexs" />
				</uni-forms-item>
				<uni-forms-item label="发票抬头名称" required name="name">
					<uni-easyinput :clearable="false" class="right-input" v-model="state.baseFormData.name"
						inputBorder="false" placeholder="请输入发票抬头名称" />
				</uni-forms-item>
				<uni-forms-item label="纳税人识别号" :required="numberRequire" name="taxNumber">
					<uni-easyinput maxlength="18" :clearable="false" class="right-input" v-model="state.baseFormData.taxNumber"
						:placeholder="numberRequire?'请输入纳税人识别号(必填)':'请输入纳税人识别号(非必填)'" />
				</uni-forms-item>
				<uni-forms-item label="手机号" name="companyTel">
					<uni-easyinput :clearable="false" maxlength="11" class="right-input" v-model="state.baseFormData.companyTel"
						placeholder="请输入手机号" />
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="companyAddress">
					<uni-easyinput :clearable="false" class="right-input" v-model="state.baseFormData.companyAddress"
						placeholder="请输入详细地址" />
				</uni-forms-item>

				<uni-forms-item label="邮箱(非必填)" name="email">
					<uni-easyinput :clearable="false" required class="right-input" v-model="state.baseFormData.email"
						placeholder="请输入邮箱" />
				</uni-forms-item>
				<!-- <uni-forms-item label="公司开户行">
					<uni-easyinput v-model="state.baseFormData.name" placeholder="请输入公司开户行" />
				</uni-forms-item>
				<uni-forms-item label="开户行账号">
					<uni-easyinput v-model="state.baseFormData.name" placeholder="请输入开户行账号" />
				</uni-forms-item>
				<uni-forms-item label="开户行账号">
					<uni-easyinput v-model="state.baseFormData.name" placeholder="请输入开户行账号" />
				</uni-forms-item> -->

				<view class="agreement-box ss-flex ss-row-left" name="isDefault">
					<label class="radio ss-flex ss-col-center" @tap="onChange">
						<radio :checked="state.baseFormData.isDefault" color="var(--ui-BG-Main)"
							style="transform: scale(0.8)" @tap.stop="onChange" />
						<view class="agreement-text ss-flex ss-col-center ss-m-l-8">
							设置为默认抬头
						</view>
					</label>
				</view>

			</uni-forms>
		</view>

		<view class="addInvoiceBtn" @tap.stop="addInvoice">保存</view>
		<view class="cancelInvoiceBtn" @tap.stop="onClickBack">取消</view>
	</s-layout>
</template>

<script setup>
	import InvoiceApi from '@/sheep/api/trade/invoices';
	import {
		onMounted,
		reactive,
		ref,
		unref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	let numberRequire = ref(false);
	const state = reactive({
		invoList: [],
		sexs: [{
			text: '个人',
			value: false
		}, {
			text: '企业',
			value: true
		}],
		baseFormData: {
			id:'',
			name: '',
			taxNumber: '',
			companyTel: '',
			type: false,
			companyAddress: '',
			email: '',
			isDefault: false
		},
	})

	// const rules = {
	//   name: {
	//     rules: [
	//       {
	//         required: true,
	//         errorMessage: '请输入名称',
	//       },
	//     ],
	//   },
	//   taxNumber: {
	//     rules: [
	//       {
	//         required: true,
	//         errorMessage: '请输入纳税人识别号',
	//       },
	//     ],
	//   },
	//   companyAddress: {
	//     rules: [
	//       {
	//         required: true,
	//         errorMessage: '请输入详细地址',
	//       },
	//     ],
	//   },
	// };

	const baseForm = ref(null);
const invoHeadType = ref('add');
	onLoad((options) => {
		console.log("路由参数：", options)
		invoHeadType.value = options.type
		if (options.type === 'update') {
			getInvoiceheaddetail(options.headid)
		}
	})
	const hasHistory = sheep.$router.hasHistory();

	function onClickBack() {
		if (hasHistory) {
			sheep.$router.back();
		} else {
			sheep.$router.go('/pages/index/index');
		}
	}
	const headChange = (e) => {
		console.log("e", e)
		if (e.detail.value === true) {
			console.log("进这个")
			numberRequire.value = true
		} else {
			console.log("进这个2")
			numberRequire.value = false
		}
	}
	const onChange = () => {

		state.baseFormData.isDefault = !state.baseFormData.isDefault;

	}
	const getInvoiceheaddetail = async (headid) => {
		const res = await InvoiceApi.getInvoicesheadDetail(headid)
		console.log("返回的数据", res);
		state.baseFormData = Object.assign(state.baseFormData,res.data)
		if(state.baseFormData.type){
			numberRequire.value = true
		}
	}
	const addInvoice = async () => {
		console.log("进入这个0",state.baseFormData)
		if (!state.baseFormData.name) {
			
			uni.showToast({
				title: '请输入发票抬头名称',
				icon: 'none',
			});
			return
		}
		if (state.baseFormData.type) {
			
			if (!state.baseFormData.taxNumber || state.baseFormData.taxNumber.length !== 18) {
			    uni.showToast({
			      title: '请输入有效的纳税人识别号（18位）',
			      icon: 'none',
			    });
			    return;
			  }
		}
		// if (state.baseFormData.type && state.baseFormData.taxNumber?.length <18) {
		// 	uni.showToast({
		// 		title: '纳税人识别号不能小于18位',
		// 		icon: 'none',
		// 	});
		// 	return
		// }
		console.log("进入这个tel")
		const phoneRegex = /^1[3-9]\d{9}$/; // 匹配中国大陆手机号
		if (state.baseFormData.companyTel?.length > 0 && !phoneRegex.test(state.baseFormData.companyTel)) {
		  uni.showToast({
		    title: '请输入有效的11位手机号',
		    icon: 'none',
		  });
		  return;
		}
		// const validate = await unref(baseForm)
		// 	.validate()
		// 	.catch((error) => {
		// 		console.log('error: ', error);
		// 	});
		// if (validate) {

		console.log("进入这个3")
		if(invoHeadType.value === 'add'){
			addInvoicehead(state.baseFormData)
		}else{
			updateInvoicehead(state.baseFormData)
		}
		

		// } else {
		// 	console.log('验证失败');
		// 	uni.showToast({
		// 		title: '请检查输入内容',
		// 		icon: 'none',
		// 	});
		// }
	}
	
	const addInvoicehead = async (data) => {
		const res = await InvoiceApi.createInvoicehead(data)
		console.log("返回数据", res)
		if (res.code === 0) {
			uni.hideToast();
			uni.showToast({
				title: '提交成功',
				icon: 'success',
			});
			setTimeout(() => {
				onClickBack()
			}, 1000)

		} else {
			uni.showToast({
				title: res.msg,
				icon: 'error',
			});
		}
	}
	const updateInvoicehead = async (data) => {
		const res = await InvoiceApi.updateInvoicehead(data)
		console.log("返回数据", res)
		if (res.code === 0) {
			uni.hideToast();
			uni.showToast({
				title: '提交成功',
				icon: 'success',
			});
			setTimeout(() => {
				onClickBack()
			}, 1000)
	
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'error',
			});
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .invoiceHeader {
		// margin: 20rpx 16rpx;
		background-color: white;

		.uni-easyinput__content-input {
			direction: rtl;
			text-align: right;
		}

		.is-input-border {
			border: none;
		}

		.uni-data-checklist .checklist-group {
			justify-content: flex-end;
		}

		.uni-forms-item {
			position: relative;
			margin-bottom: 6rpx;
		}

		.uni-forms-item::after {
			content: '';
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 1rpx;
			/* 调整为你需要的边框厚度 */
			background-color: #ededed;
		}

		.uni-forms-item__inner {
			padding-bottom: 10rpx !important;
		}

		.agreement-text {
			white-space: nowrap;
		}

		.tcp-text {
			color: #7D9337;
		}

		.agreement-box {
			margin-top: 20rpx;
			width: 100%;
		}

		.uni-forms-item__label .label-text {
			font-size: 29rpx !important;
		}

		.right-input {
			direction: rtl;
			text-align: right;
		}

		.uni-data-checklist .checklist-group .checklist-box {
			margin-right: 20rpx !important;
		}
	}

	.addInvoiceBtn {
		width: 90%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 100rpx;
		position: fixed;
		color: white;
		font-size: 36rpx;
		background-color: #7D9337;
		bottom: 156rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.cancelInvoiceBtn {
		width: 90%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 100rpx;
		position: fixed;
		color: white;
		font-size: 36rpx;
		background-color: #7D9337;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.invoiceHeader {
		padding: 20rpx 20rpx 20rpx 30rpx;
		border-radius: 10rpx;
	}

	.invoList {
		width: 100%;
		background-color: #F5F5F5;

		.invoice_item {
			width: 95%;
			margin: 0 auto 20rpx;
			padding: 30rpx 20rpx;
			box-sizing: border-box;
			border-radius: 10rpx;
			background-color: white;

			.invoice_no {
				margin-bottom: 10rpx;
			}
		}
	}
</style>