<template>
	<!-- 添加运单 -->
	<view>
		<u-navbar :title="headline" autoBack placeholder></u-navbar>
		<view class="space_between card_Address">
			<view class="title_waybill">收件人:</view>
			<view class="card_flex_il" @click="addressBook('consignee')">
				<!-- <u-icon name="order" size="22"></u-icon> -->
				<span class="iconfont icon-dizhibu icon_bottom"></span>
				<view class="title_sou">收件人簿</view>
			</view>
		</view>
		<x-form ref="recipients" :list="list" :model="recipientsModel" :rules="rules"></x-form>
		<x-form ref="goods" :list="goodsList" :model="goodsModel" :rules="goodsRules" :productData="productData"
			:addloading="addloading" @selector="selector" @getSweep="getSweep"></x-form>
		<view class="safeBottom" style="width: 100%;height: 150rpx;"></view>
		<view class="btn_print" @click="printWaybill">
			<u-button type="primary" :loading="printLoading" :text="headline"></u-button>
		</view>
		<u-popup :show="courierShow" mode="bottom" closeable :round="10" :closeOnClickOverlay="false" @close="close">
			<view class="card_courier">
				<view class="headline">{{courierHeadline}}</view>
				<view class="search_card">
					<u-search :showAction="false" v-model="keyword" @change="searchChange"
						placeholder="输入关键字快速查找"></u-search>
				</view>
				<scroll-view class="scroll-view" scroll-y="true" @scrolltolower="loadMore">
					<view class="courier" v-if="courieList.length > 0">
						<view class="courier_item space_between" v-for="(item,index) in courieList" :key="index"
							@click="bindingDistributor(item)">
							<view class="courier_name">
								<view class="title_name">{{item.nickName}}</view>
								<view class="title_phone">{{item.phone}}</view>
							</view>
							<view class="xd_title center_in">选择TA</view>
							<!-- <view class="xd_title center_in">下单给TA</view> -->
						</view>
					</view>
					<view style="margin-top: 30rpx;" v-else>
						<u-empty mode="list" :text="textEmpty"></u-empty>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		formRules,
		pickupRulesil,
		printList
	} from "./waybill.js";
	export default {
		name: 'addWaybill',
		data() {
			return {
				senderModel: {
					name: '',
					phone: '',
					address: '',
				},
				recipientsModel: {
					name: '',
					phone: '',
					address: '',
				},
				courierModel: {
					name: '',
					phone: '',
				},
				goodsModel: {
					reCheckId: '',
					reCheckName: '',
					is_secondary_distribution: false,
					deliveryId: '',
					deliveryName: '',
					drugBarCode: '',
					tamperProofLabel: '',
					tamperProofLabelImg: '',
					remark: '',
					prescription: [],
				},
				rules: {
					name: {
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					phone: [{
						required: true,
						message: '请输入电话',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '请输入正确手机号码',
						trigger: ['change', 'blur'],
					}],
					address: {
						required: true,
						message: '请输入地址',
						trigger: ['blur', 'change']
					},
				},
				goodsRules: {
					reCheckName: {
						required: true,
						message: '请选择复核人',
						trigger: ['blur', 'change']
					},
					deliveryName: {
						required: true,
						message: '请选择配送人',
						trigger: ['blur', 'change']
					},
					tamperProofLabel: {
						required: false,
						message: '请输入防拆标签码',
						trigger: ['blur', 'change']
					},
					tamperProofLabelImg: {
						required: false,
						message: '请上传防拆标签图片',
						trigger: ['blur', 'change']
					},
				},
				list: pickupRulesil(),
				courierList: printList(),
				goodsList: formRules(),
				productData: [],
				userInfo: {},
				headline: '添加运单',
				type: 1,
				operationType: 'sender',
				courierShow: false,
				courieList: [],
				keyword: '',
				incubatorMore: true,
				Pagination: 1,
				pageSize: 10,
				saveSenderAddress: true,
				saveConsigneeAddress: true,
				courierHeadline: '选择配送员',
				textEmpty: '暂无配送员',
				selectiveType: '',
				addloading: false,
				printLoading: false,
			}
		},
		onUnload() {
			// console.log('页面销毁')
			uni.removeStorageSync('selectAddress')
		},
		onShow() {
			let address = uni.getStorageSync('selectAddress')
			if (address) {
				if (this.operationType == 'sender') {
					// this.$nextTick(() => {
					// 	this.$refs['sender'].validateForm();
					// })
					this.senderModel = address
					this.saveSenderAddress = false
				} else {
					this.$nextTick(() => {
						this.$refs['recipients'].validateForm();
					})
					this.recipientsModel = address
					this.saveConsigneeAddress = false
				}
			}
		},
		onLoad(value) {
			this.headline = value.title
			this.type = Number(value.type)
			if (this.type == 2) {
				var orderList = this.$cache.getCache('orderDetails')
				this.recipientsModel.name = orderList.consigneeAddressName
				this.recipientsModel.phone = orderList.consigneeAddressPhone
				this.recipientsModel.address = orderList.consigneeAddressDetails
				this.goodsModel.tamperProofLabel = orderList.tamperProofLabel
				this.goodsModel.tamperProofLabelImg = orderList.tamperProofLabelImg
				this.goodsModel.remark = orderList.remark
				this.goodsModel.reCheckId = orderList.reCheckId
				this.goodsModel.reCheckName = orderList.delivery.nickName
				this.goodsModel.deliveryId = orderList.deliveryId
				this.goodsModel.deliveryName = orderList.reCheck.nickName
				this.goodsModel.id = orderList.id
				if (orderList.tamperProofLabelImg) {
					let arrImg = orderList.tamperProofLabelImg.split(',')
					let arrImgList = []
					arrImg.forEach((item) => {
						const arr = {
							url: item,
						}
						arrImgList.push(arr)
					})
					this.$nextTick(() => {
						this.$refs.goods.fileList1 = arrImgList
					})
				}
			}
		},
		mounted() {
			var userInfo = this.$cache.getCache('userInfo')
			this.userInfo = userInfo
		},
		methods: {
			// 添加运单
			async printWaybill() {
				let flag1 = await this.$refs['recipients'].validateForm();
				let flag2 = await this.$refs['goods'].validateForm();
				if (flag1 && flag2) {
					if (this.productData.length > 0) {
						let params = {
							is_phone: true,
							consigneeAddressName: this.recipientsModel.name,
							consigneeAddressPhone: this.recipientsModel.phone,
							consigneeAddressDetails: this.recipientsModel.address,
							saveConsigneeAddress: this.saveConsigneeAddress,
							drugs: this.productData,
							...this.goodsModel,
						}
						delete params.drugBarCode
						uni.showLoading({
							mask: true
						});
						this.printLoading = true
						if (this.type == 1) {
							// 添加运单
							this.$api.post('/api/waybill', params).then(res => {
								if (res.code == 200) {
									uni.redirectTo({
										url: '/pages/order/index'
									});
								} else {
									uni.$u.toast(res.msg)
								}
								uni.hideLoading();
								this.printLoading = false
							}).catch(() => {
								uni.hideLoading();
								this.printLoading = false
							})
						} else {
							// 修改运单
							this.$api.put('/api/waybill', params).then(res => {
								if (res.code == 200) {
									// uni.$u.toast(res.msg)
									uni.redirectTo({
										url: '/pages/order/index'
									});
								} else {
									uni.$u.toast('修改失败')
								}
								uni.hideLoading();
								this.printLoading = false
							}).catch(() => {
								uni.hideLoading();
								this.printLoading = false
							})
						}
					} else {
						uni.$u.toast('请扫码添加商品')
					}
				} else {
					uni.$u.toast('请先完善表单')
				}
			},
			// 选择类型
			addressBook(type) {
				this.operationType = type
				uni.navigateTo({
					url: '/pages/order/addressBook?type=' + type
				});
			},
			// 配送员
			deliveryBook() {
				this.courierShow = true
				this.courierHeadline = '选择配送员'
				this.textEmpty = '暂无配送员'
				this.getDelivery()
			},
			// 复核人
			selector(value) {
				this.selectiveType = value.field
				this.courieList = []
				this.incubatorMore = true
				this.Pagination = 1
				if (value.field == 'deliveryName') {
					this.courierHeadline = '选择配送人'
					this.textEmpty = '暂无配送人'
					this.getDelivery(value.field)
				} else if (value.field == 'reCheckName') {
					this.courierHeadline = '选择复核人'
					this.textEmpty = '暂无复核人'
					this.getDelivery(value.field)
				}
				this.courierShow = true
			},
			// 获取药品信息码上放心
			getSweep(event) {
				let idExists = this.productData.some(obj => obj.code === event);
				if (!idExists) {
					this.addloading = true
					uni.request({
						url: 'https://public.coldbaozhida.com/Ali_msfx/codedetail', //仅为示例，并非真实接口地址。
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded', // 默认值
						},
						data: {
							code: event,
						},
						success: (res) => {
							if (res.data.status == 200) {
								let arr = JSON.parse(res.data.data)
								if (arr.result.models.length > 0) {
									let drugList = {
										code: '',
										physic_name: '',
										physic_type_desc: '',
										pkg_spec_crit: '',
										ent_name: '',
									}
									drugList.code = arr.result.models[0].code
									drugList.physic_name = arr.result.models[0].drug_ent_base_d_t_o.physic_name
									drugList.physic_type_desc = arr.result.models[0].drug_ent_base_d_t_o
										.physic_type_desc
									drugList.pkg_spec_crit = arr.result.models[0].drug_ent_base_d_t_o
										.pkg_spec_crit
									drugList.ent_name = arr.result.models[0].p_user_ent_d_t_o.ent_name
									this.productData.push(drugList)
									this.productData = this.uniqueArray(this.productData)
								} else {
									uni.$u.toast('该商品不存在')
								}
								this.addloading = false
							}
						}
					});
				} else {
					uni.$u.toast('该商品已存在')
				}
			},
			// 去重
			uniqueArray(arr) {
				return [...new Set(arr)];
			},
			// 获取配送员
			getDelivery(field) {
				if (field == 'deliveryName') {
					// 配送人
					this.$api.get('/api/sys-user', {
						page: this.Pagination,
						pageSize: this.pageSize,
						name: this.keyword,
						// type: 3,
					}).then(res => {
						if (res.code == 200) {
							const data = res.data.list
							if (this.incubatorMore == true) {
								this.courieList = this.courieList.concat(data);
							}
							if (data.length < this.pageSize) {
								this.incubatorMore = false
							} else {
								this.incubatorMore = true
							}
						}
					})
				} else if (field == 'reCheckName') {
					// 复核人
					this.$api.get('/api/sys-user', {
						page: this.Pagination,
						pageSize: this.pageSize,
						name: this.keyword,
					}).then(res => {
						if (res.code == 200) {
							const data = res.data.list
							if (this.incubatorMore == true) {
								this.courieList = this.courieList.concat(data);
							}
							if (data.length < this.pageSize) {
								this.incubatorMore = false
							} else {
								this.incubatorMore = true
							}
						}
					})
				}
			},
			// 选择
			bindingDistributor(value) {
				// this.$refs['courier'].validateForm();
				if (this.selectiveType == 'deliveryName') {
					this.goodsModel.deliveryId = value.id
					this.goodsModel.deliveryName = value.nickName
					this.$refs['goods'].formValidation('deliveryName')
				} else if (this.selectiveType == 'reCheckName') {
					this.goodsModel.reCheckId = value.id
					this.goodsModel.reCheckName = value.nickName
					this.$refs['goods'].formValidation('reCheckName')
				}
				this.courierShow = false
			},
			// 滚动加载更多
			loadMore() {
				if (this.incubatorMore) {
					this.Pagination++
					this.getDelivery(this.selectiveType)
				}
			},
			// 搜索配送员
			searchChange() {
				this.Pagination = 1
				this.incubatorMore = true
				this.courieList = []
				this.getDelivery(this.selectiveType)
			},
			close() {
				this.courierShow = false
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff !important;
	}

	.title_waybill {
		font-size: 32rpx;
		padding: 20rpx;
	}

	.card_Address {
		position: relative;
	}

	.card_flex_il {
		display: flex;
		align-items: center;
		padding: 20rpx;
	}

	.title_sou {
		font-size: 32rpx;
	}

	.icon_bottom {
		font-size: 36rpx;
		margin-right: 10rpx;
	}

	.card_Address:before {
		content: " ";
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 1px;
		border-top: 1px solid #e7e6e4;
		-webkit-transform-origin: 0 0;
		transform-origin: 0 0;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
	}

	.card_courier {
		min-height: 600rpx;
		padding-bottom: 20rpx;
	}

	.scroll-view {
		max-height: 60vh;
		overflow: hidden;
	}

	.headline {
		padding: 30rpx 30rpx 0rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding-bottom: 30rpx;
		font-size: 32rpx;
		font-weight: 600;
	}

	.search_card {
		padding: 0rpx 30rpx 10rpx 30rpx;
	}

	.courier_item {
		margin: 20rpx 20rpx;
		width: calc(100% - 80rpx);
		padding: 20rpx;
		border-radius: 20rpx;
		// box-shadow: 0 2rpx 10rpx 0 rgba(0, 0, 0, .1);
		border: 1rpx solid #e7e6e4;
	}

	.courier_name {
		display: flex;
		flex-direction: column;
	}

	.title_name {
		font-weight: 600;
		font-size: 32rpx;
		margin-bottom: 10rpx;
	}

	.title_phone {
		font-size: 28rpx;
	}

	.xd_title {
		width: auto;
		font-size: 28rpx;
		font-weight: 500;
		padding: 15rpx 30rpx;
		border-radius: 35rpx;
		// border: 3rpx solid #82848a;
		background-color: #E4E7ED;
	}
</style>