<template>
	<view style="padding: 30rpx;">
		<!-- 订单信息 -->
		<view class="container">
			<block v-for="(item, index) in detailData">
				<view>
					<view class="details">
						<u-image
							width="140rpx"
							height="200rpx"
							:src="baseUrl + item.picUrl"
							class="img"
						></u-image>
						<view class="right">
							<view class="name">{{ item.goodsName }}</view>
							<view class="tag">
								<block
									v-for="(item1, index1) in item.specifications.length"
									:key="index1"
								>
									<u-tag
										:text="item.specifications[index1]"
										type="info"
										size="mini"
										style="margin: 8rpx 8rpx 8rpx 0;"
									/>
								</block>
							</view>

							<view class="sum-price">
								<view style="display: flex; flex-direction: column;">
									<view
										style="display: flex; flex-direction: row; align-items: center; margin-bottom: 10rpx;"
									>
										<text>设置单价：</text>
										<u-input
											v-model="item.unitPrice"
											type="number"
											height="50"
											placeholder="请输入单价"
											style="width: 200rpx;"
										/>
									</view>
									<view
										style="display: flex; flex-direction: row; align-items: center; margin-bottom: 10rpx;"
									>
										<text>合同报价：</text>
										<u-input
											v-model="item.contractQuotation"
											type="number"
											:disabled="true"
											height="50"
											placeholder=""
											style="width: 200rpx;"
										/>
									</view>
									<view style="margin-bottom: 10rpx;">
										金额：￥{{
											item.unitPrice
												? (Number(item.unitPrice) * item.number).toFixed(2)
												: 0
										}}
									</view>
									<view style="margin-bottom: 10rpx;">
										含税金额：￥{{
											item.unitPrice
												? (
														Number(item.unitPrice) * item.number +
														Number(item.unitPrice) *
															item.number *
															tax *
															0.01
												  ).toFixed(2)
												: 0
										}}
									</view>
								</view>
								<text style="color: #969799; font-size: 12px;">
									x{{ item.number }}
								</text>
							</view>
						</view>
					</view>
					<u-line v-if="detailData.length > 1" color="#e8e8e8" />
				</view>
			</block>
		</view>
		<!-- 发货地址 -->
		<view class="address">
			<view class="top"><text>发货信息</text></view>
			<view class="bottom">
				<view>
					<text style="margin-right: 20rpx;">{{ formData.attend }}</text>
					<text style="margin-right: 20rpx;">{{ formData.tel }}</text>
					<text>{{ formData.email }}</text>
				</view>
				<text>{{ formData.deliverGoodsAddr }}</text>
			</view>
		</view>
		<!-- 收货地址 -->
		<view class="address" @tap="tapAddresss">
			<view class="top">
				<text>收货信息</text>
				<u-icon name="arrow-right"></u-icon>
			</view>
			<view class="bottom">
				<text>{{ formData.toCust }}</text>
				<view class="">
					<text style="margin-right: 10rpx;">{{ formData.quotationAttend }}</text>
					<text>{{ formData.quotationTel }}</text>
				</view>
				<text>{{ formData.addr }}</text>
			</view>
		</view>
		<u-form :model="formData" ref="uFormRef" label-width="200">
			<view
				style="background-color: #fff; padding: 0 20rpx; border-radius: 10rpx; margin: 20rpx 0; box-shadow:0 0 10px #e1e1e1;"
			>
				<u-form-item label="预计交货时间:" prop="deliveryDate">
					<u-input
						type="number"
						v-model="formData.deliveryDate"
						placeholder="请输入预计交货时间(天)"
					/>
				</u-form-item>
				<u-form-item label="交货期:" prop="deliveryTime">
					<u-input v-model="formData.deliveryTime" placeholder="请输入交货期" />
				</u-form-item>
				<u-form-item label="订单号:" prop="noOrder">
					<u-input type="number" v-model="formData.noOrder" placeholder="请输入订单号" />
				</u-form-item>
				<u-form-item label="付款方式:" prop="pay">
					<u-input v-model="formData.pay" placeholder="请输入付款方式" />
				</u-form-item>
				<u-form-item label="保修:" prop="guarantee">
					<u-input
						v-model="formData.guarantee"
						:disabled="true"
						placeholder="请输入保修"
						@tap="guaranteeShow = true"
					/>
				</u-form-item>
				<u-form-item label="备注:" prop="remarks" :border-bottom="false">
					<u-input type="textarea" v-model="formData.remarks" placeholder="请输入备注" />
				</u-form-item>
			</view>
		</u-form>

		<view style="height: 100rpx;"></view>
	</view>
	<u-row class="footer">
		<u-col :span="8">
			<view class="price">
				<text style="margin-bottom: 10rpx;">商品总价：￥{{ totlePirce }}</text>
				<text>含税商品总价：￥{{ taxTotlePirce }}</text>
			</view>
		</u-col>
		<u-col :span="4"><u-button type="error" @click="submit">提交</u-button></u-col>
	</u-row>
	<u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm"></u-picker>
	<u-picker mode="region" v-model="pickerShow1" @confirm="regionConfirm1"></u-picker>
	<u-picker mode="time" v-model="pickerDateShow" @confirm="dateConfirm"></u-picker>
	<u-select v-model="guaranteeShow" :list="guaranteeList" @confirm="guaranteeConfirm"></u-select>
	<order-form ref="orderRef" @onSubmit="onSubmit" />
	<u-modal
		v-model="showModel"
		:content="content"
		@confirm="modelConfirm"
		@cancel="modelCancel"
		showCancelButton
	></u-modal>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, ComponentInternalInstance, computed  } from 'vue';
import { fillQuotation, quotationInit, quotationOrder } from '@/api/cart';
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';
import { orderDetail, getTax } from '@/api/index';
import { quotationExist } from '@/api/cart'
import config from '@/utils/config';
import orderForm from './components/orderForm.vue';

let { proxy } : any = getCurrentInstance() as ComponentInternalInstance
let orderRef = ref()
let baseUrl = config.baseUrl;
let pickerShow = ref(false)
let pickerShow1 = ref(false)
let pickerDateShow = ref(false)
let guaranteeShow = ref(false)
let showModel = ref(false)
let content = ref('是否下载execl？')
let formData = ref({
	attend: '',
	tel: '',
	addr: '',
	deliveryAddr: '',
	deliveryDate: '',
	toCust: '',
	email: '',
	pay: '',
	quotationAttend: '',
	quotationEmail: '',
	quotationTel: '',
	remarks: '',
	noOrder: '',
	guarantee: '',
	deliveryTime: ''
}); // 报价单数据
let detailData = ref()


let rules = ref({
	attend: [{ required: true, message: '请输入发货人', trigger: 'blur' }],
	tel: [{ required: true, message: '请输入发货人手机号', trigger: 'blur' },
	{
		validator: (rule, value: any, callback) => {
			return proxy.$u.test.mobile(value);
		},
		message: '手机号码不正确',
		trigger: 'blur',
	}],
	email: [{ required: true, message: '请输入发货email', trigger: 'blur' },
	{
		validator: (rule, value: any, callback) => {
			return proxy.$u.test.email(value);
		},
		message: 'email不正确',
		trigger: 'blur',
	}],
	addr: [{ required: true, message: '请选择发货地址', trigger: ['blur', 'change'] }],
	toCust: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
	quotationAttend: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
	quotationEmail: [{ required: true, message: '请输入收货email', trigger: 'blur' },
	{
		validator: (rule, value: any, callback) => {
			return proxy.$u.test.email(value);
		},
		message: 'email不正确',
		trigger: 'blur',
	}],
	quotationTel: [{ required: true, message: '请输入收货联系人', trigger: 'blur' },
	{
		validator: (rule, value: any, callback) => {
			return proxy.$u.test.mobile(value);
		},
		message: '手机号码不正确',
		trigger: 'blur',
	}],
	deliveryAddr: [{ required: true, message: '请选择收货地址', trigger: 'blur' }],
	deliveryDate: [{ required: true, message: '请选择交货时间', trigger: 'blur' },
	{ pattern: /^[+]{0,1}(\d+)$/g, message: '必须为正整数', trigger: 'blur' }],
	noOrder: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
	pay: [{ required: true, message: '请输入付款方式', trigger: 'blur' }],
	guarantee: [{ required: true, message: '请输入保修', trigger: 'blur' }],
	deliveryTime: [{ required: true, message: '请输入交货期', trigger: 'blur' }],
});

let guaranteeList = ref([
	{ value: '1年', label: '1年' },
	{ value: '2年', label: '2年' },
	{ value: '其他', label: '其他' }
])

let uFormRef = ref();
let quotationData = ref();
let orderId = ref()
let addressData = ref() // 获取收货地址信息
let tax = ref() // 税率

onLoad((options: any) => {
	orderId.value = options.orderId
	// 判断是否重复报价
	quotationExist({ orderId: orderId.value }).then((res: any) => {
		if(res.data.code === 200) {
			if(res.data.data) {
				uni.reLaunch({
					url: '../order/editQuotation?orderId=' + orderId.value
				})
			} else {
				initQuotation(orderId.value);
				setTimeout(() => {
					initQuotaionData(orderId.value)
				}, 50)
				initTax()
			}
		}
	})
});

onShow(() => {
	// 判断是否在报价页面返回
	if(addressData.value) {
		// 同步修改收货地址的信息
		formData.value.toCust = addressData.value.name
		formData.value.quotationAttend = addressData.value.contactName
		formData.value.quotationEmail = addressData.value.customerEmail
		formData.value.quotationTel = addressData.value.tel
		formData.value.addr = addressData.value.province +
			addressData.value.city + addressData.value.county + addressData.value.addressDetail
	}

})

// 引入校验
onReady(() => {
	uFormRef.value?.setRules(rules.value);
})

// 总价格
let totlePirce: any = computed(() => {
	let totlePic = 0;
	if (detailData.value) {
		detailData.value.map((item: any) => {
			if (typeof item.unitPrice !== 'undefined') {
				totlePic += Number(item.unitPrice);
			}
		});
	}
	return totlePic.toFixed(2);
});

// 含税总价格
let taxTotlePirce = computed(() => {
	let taxTotlePic = Number(totlePirce.value) + Number(totlePirce.value) * tax.value * 0.01;
	return Number(taxTotlePic).toFixed(2);
});

let submit = () => {
	uFormRef.value?.validate((valid: any, err: any) => {
		if(valid) {
			detailData.value.some((item: any) => {
				if (typeof item.unitPrice === 'undefined') {
					return uni.showToast({
						title: `请填写 ${item.goodsName} 单价`,
						icon: 'none',
					});
				}
			})
			quotationData.value.items.forEach((item: any) => {
				console.log(item);
				detailData.value.map((res: any) => {
					if(item.goodsName == res.goodsName) {
						item.price = res.unitPrice
					}
				})
			})
			let data = {
				items: quotationData.value.items,
				quotation: formData.value,
			};
			fillQuotation(data).then((res: any) => {
				if (res.data.code === 200) showModel.value = true
			});
		} else {
			console.log(err);
		}
	})
};

// 确认下载xlsx
let modelConfirm = () => {
	uni.downloadFile({
		url: baseUrl + '/wx/quotation/download?orderId=' + orderId.value,
		header: {'Authorization': uni.getStorageSync('token'), 'Content-Type': 'application/octet-stream;charset=UTF-8'},
		success: (res: any) => {
			let downloadElement = document.createElement('a');
			downloadElement.href = res.tempFilePath;
			downloadElement.download = orderId.value + '.xlsx'; //下载后文件名
			document.body.appendChild(downloadElement);
			downloadElement.click(); //点击下载
			document.body.removeChild(downloadElement); //下载完成移除元素
			window.URL.revokeObjectURL(res.tempFilePath); //释放掉blob对象
			uni.redirectTo({
				url: './editQuotation?orderId=' + orderId.value
			})
		}
	})
}

// 点击取消按钮
let modelCancel = () => {
	uni.reLaunch({
		url: './editQuotation?orderId=' + orderId.value
	})
}

let onSubmit = (data: any) => {
	quotationData.value.items = data
	orderRef.value.show = false
}

// 设置地址
let tapAddresss = () => {
	uni.navigateTo({
		url: `../profile/address?cartId=${orderId.value}`,
	});
};

// 选择地区回调
let regionConfirm = (e: any) => {
	formData.value.addr = e.province.name + '-' + e.city.name + '-' + e.area.name;
}
// 选择地区回调
let regionConfirm1 = (e: any) => {
	formData.value.deliveryAddr = e.province.name + '-' + e.city.name + '-' + e.area.name;
}

// 选择时间回调
let dateConfirm = (e: any) => {
	formData.value.deliveryDate = e.year + '-' + e.month + '-' + e.day
}

// 选择保修回调
let guaranteeConfirm = (e: any) => {
	formData.value.guarantee = e[0].value
}

// 初始化数据
let initQuotation = (orderId: number) => {
	quotationInit({ orderId }).then((res: any) => {
		if (res.data.code === 200) {
			quotationData.value = res.data.data;
			formData.value = res.data.data.quotation;
			console.log(quotationData.value);
			// initQuotationOrder(orderId)
		}
	});
};

let initQuotaionData = (id: number) => {
	orderDetail({ orderId: id }).then((res: any) => {
			if (res.data.code === 200) {
				detailData.value = res.data.data.orderGoods
				// 从quotationData获取 在detailData中添加 合同报价字段
				if(quotationData.value) {
					quotationData.value.items.map((item: any) => {
						detailData.value.map((detail: any) => {
							if(item.goodsName == detail.goodsName) {
								detail.contractQuotation = item.contractQuotation
							}
						})
					})
				} else initQuotation(orderId.value)
				console.log(res, '订单详情信息');
			}
	});
}

// 二次查询详细信息
let initQuotationOrder = (orderId: number) => {
	quotationOrder({ orderId }).then((res: any) => {
		if(res.data.data) {
			formData.value = res.data.data
		}
	})
};

// 获取税率
let initTax = () => {
	getTax().then((res: any) => {
		if (res.data.code === 200) tax.value = Number(res.data.data.mall_tax_rate);
	});
};
</script>

<style lang="scss" scoped>
.container {
	box-sizing: border-box;
	background-color: #fff;
	border-radius: 10rpx;
	box-shadow: 0 0 10px #e1e1e1;
	margin-bottom: 20rpx;
	.details {
		width: 100%;
		padding: 16rpx 32rpx;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		.img {
			margin-right: 20rpx;
		}

		.tag {
			margin-top: 1%;
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			margin-bottom: 5%;
		}

		.right {
			width: 80%;

			.sum-price {
				display: flex;
				justify-content: space-between;
			}
		}
	}
}

.address {
	width: 100%;
	padding: 20rpx 32rpx;
	border-radius: 10rpx;
	background-color: #ffffff;
	margin-bottom: 20rpx;
	background-color: #fff;
	box-shadow: 0 0 10px #e1e1e1;

	.top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.bottom {
		display: flex;
		flex-direction: column;
		font-size: 24rpx;
		color: #969799;
		line-height: 36rpx;
	}
}
.footer {
	width: 100%;
	position: fixed;
	bottom: 0;
	padding: 20rpx;
	z-index: 99;
	background-color: #fff;
	border-top: 2rpx solid #f7f7f7;
	.price {
		display: flex;
		flex-direction: column;
	}
}
</style>
