<template>
	<view style="width: 100%;">
		<view class="card_ordermang" v-for="(item,index) in orderList" :key="index" @click="goOrderDetails(item)">
			<view class="head_ordermang space_between">
				<view class="waybill_title">运单号:<span>{{item.waybillNo}}</span></view>
				<span class="card_state" :style="{color:getState(item.status)}">{{orderStatus(item.status)}}</span>
			</view>
			<view class="title_ordermang"><span>订单号:</span>{{item.orderNo}}</view>
			<view class="title_ordermang"><span>收货人地址:</span>{{item.consigneeAddressDetails}}</view>
			<view class="title_ordermang"><span>收货人电话:</span>{{item.consigneeAddressPhone}}</view>
			<view class="title_ordermang"><span>下单时间:</span>{{item.orderTime}}</view>
			<view style="display: flex;margin-top: 15rpx;"
				v-if="item.status == 1 || item.status == 2 || item.status == 3">
				<!-- <view class="btn_printil markd10"
					@click.stop="modifyOrder(item)">
					<u-button size="small" type="warning" text="修改运单"></u-button>
				</view>
				<view class="btn_printil markd10" @click.stop="antiDismantle(item)">
					<u-button size="small" type="primary" text="防拆标签"></u-button>
				</view>
				<view class="btn_printil markd10" @click.stop="sendOrders(item)">
					<u-button size="small" type="success" text="派单"></u-button>
				</view> -->
				<view class="btn_printil markd10" @click.stop="toDeliver(item)">
					<u-button size="small" type="success" text="去配送"></u-button>
				</view>
			</view>
			<view style="display: flex;" v-if="item.status == 4 && !item.is_secondary_distribution">
				<view class="btn_printil markd10" @click.stop="rejection(item)">
					<u-button size="small" type="error" text="拒收"></u-button>
				</view>
				<view class="btn_printil markd10" @click.stop="signFor(item)">
					<u-button size="small" type="primary" text="签收"></u-button>
				</view>
			</view>
			<view style="display: flex;" v-else-if="item.status == 4 && item.is_secondary_distribution">
				<view class="btn_printil markd10" @click.stop="finished(item)">
					<u-button size="small" type="success" text="已完成"></u-button>
				</view>
				<view class="btn_printil markd10" @click.stop="distributionOrder(item)">
					<u-button size="small" type="primary" text="分配订单"></u-button>
				</view>
			</view>
		</view>
		<u-popup :show="signForShow" mode="center" round="6" closeable :closeOnClickOverlay="false" @close="close">
			<view class="center_in title_sign">{{signRejection}}</view>
			<view class="card_sign_for">
				<view class="img_sign_rejection">运单号: {{orderNumber}}</view>
				<view style="margin-bottom: 20rpx;" v-if="!rejectionFlag">
					<u-radio-group v-model="modePayment">
						<span style="font-size: 30rpx;margin: 0rpx 20rpx 15rpx 0rpx;">支付方式:</span>
						<u-radio style="margin: 0rpx 20rpx 15rpx 0rpx;" v-for="(item, index) in radiolist" :key="index"
							:label="item.name" :name="item.value"></u-radio>
					</u-radio-group>
				</view>
				<view style="margin-bottom: 20rpx;" v-if="!rejectionFlag">
					<u-radio-group v-model="statePayment">
						<span style="font-size: 30rpx;margin: 0rpx 20rpx 15rpx 0rpx;">支付状态:</span>
						<u-radio style="margin: 0rpx 20rpx 15rpx 0rpx;" v-for="(item, index) in stateList" :key="index"
							:label="item.name" :name="item.value"></u-radio>
					</u-radio-group>
					<view v-if="statePayment == 2">
						<u--input placeholder="请输入未结清备注" border="surround" v-model="remarksSettled"></u--input>
					</view>
				</view>
				<view class="card_image_sign">
					<view class="img_sign_rejection">{{signRejection}}图片</view>
					<u-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
						@delete="deletePic"></u-upload>
				</view>
				<view class="card_image_sign">
					<view class="img_sign_rejection" @click="goSignature('client')">客户签字</view>
					<u-image :showLoading="true" :src="imageData" width="300rpx" height="155rpx"
						@click="goSignature('client')" mode="scaleToFill"></u-image>
				</view>
				<view class="rejection_card" v-if="rejectionFlag">
					<view class="img_sign_rejection">拒收原因</view>
					<u-textarea v-model="rejectionValue" placeholder="请输入拒收原因" autoHeight></u-textarea>
				</view>
				<u-button style="margin-top: 30rpx;" size="small" type="primary" text="确定" :loading="signLoading"
					@click="confirm()"></u-button>
			</view>
		</u-popup>
		<u-popup :show="antiShow" mode="center" closeable :closeOnClickOverlay="false" round="6" @close="close">
			<view class="card_dismantle">
				<view class="headline_anti">防拆标签</view>
				<x-form ref="goods" :list="goodsList" :model="goodsModel" :rules="goodsRules"></x-form>
				<u-button style="margin-top: 10rpx;" size="small" type="primary" text="确定"
					@click="modifiedTamper()"></u-button>
			</view>
		</u-popup>
		<!-- 确定完成 -->
		<u-modal :show="logoutShow" showCancelButton :title="title" :content='content' @cancel="cancel"
			@confirm="definiteCompletion"></u-modal>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	import {
		formRules,
	} from "./waybill.js";
	export default {
		name: 'xOrderManagement',
		props: {
			// 运单列表
			orderList: {
				type: Array,
				default: () => [],
			},
			userInfo: {
				type: Object,
				default: () => {},
			}
		},
		data() {
			return {
				signForShow: false,
				fileList1: [],
				rejectionValue: '',
				rejectionFlag: false,
				signRejection: '',
				orderNumber: '',
				imageUrl: '',
				antiShow: false,
				goodsList: formRules(),
				goodsModel: {
					tamperProofLabel: '',
					tamperProofLabelImg: '',
				},
				goodsRules: {
					tamperProofLabel: {
						required: true,
						message: '请输入防拆标签码',
						trigger: ['blur', 'change']
					},
					tamperProofLabelImg: {
						required: true,
						message: '请上传防拆标签图片',
						trigger: ['blur', 'change']
					},
				},
				antiList: {},
				imageData: '',
				radiolist: [{
					name: '现金',
					value: 1,
				}, {
					name: '线上支付',
					value: 2,
				}, {
					name: '银行卡',
					value: 3,
				}, {
					name: '医保',
					value: 4,
				}, {
					name: '其他',
					value: 5,
				}],
				stateList: [{
					name: '已结清',
					value: 1,
				}, {
					name: '未结清',
					value: 2,
				}],
				modePayment: null,
				statePayment: null,
				remarksSettled: '',

				logoutShow: false,
				title: '确定完成该订单？',
				content: '确定完成后将无法分配运单，重新下单后即可分配',
				orderId: null,
				signLoading: false,
			}
		},
		mounted() {
			// console.log(this.userInfo, 26)
		},
		methods: {
			// 打印条码
			printBarCode(value) {
				this.$cache.setCache('commodity', JSON.stringify(value))
				uni.navigateTo({
					url: '/pages/order/quantum?waybillNo=' + value.waybillNo + '&printType=barCode'
				});
			},
			// 派单
			sendOrders(value) {
				this.$emit('sendOrders', value)
			},
			// 防拆标签
			antiDismantle(value) {
				this.antiList = value
				this.antiShow = true
				this.goodsModel.tamperProofLabel = value.tamperProofLabel
				this.goodsModel.tamperProofLabelImg = value.tamperProofLabelImg
				this.goodsModel.id = value.id
				if (value.tamperProofLabelImg) {
					let arrImg = value.tamperProofLabelImg.split(',')
					let arrImgList = []
					arrImg.forEach((item) => {
						const arr = {
							url: item,
						}
						arrImgList.push(arr)
					})
					this.$nextTick(() => {
						this.$refs.goods.fileList1 = arrImgList
					})
				}
			},
			// 去配送
			toDeliver(event) {
				uni.setStorageSync('incubatorValue', event.coolerBox)
				uni.setStorageSync('orderValue', JSON.stringify(event))
				uni.navigateTo({
					url: '/pages/order/dispatching'
				});
			},
			// 拒收
			rejection(value) {
				this.orderNumber = value.waybillNo
				this.signForShow = true
				this.rejectionFlag = true
				this.signRejection = '拒收'
			},
			// 签收
			signFor(value) {
				this.orderNumber = value.waybillNo
				this.signForShow = true
				this.rejectionFlag = false
				this.signRejection = '签收'
			},
			// 已完成
			finished(event) {
				this.orderId = event.id
				this.logoutShow = true
			},
			// 分配订单
			distributionOrder(event) {
				uni.navigateTo({
					url: '/pages/order/distributionOrder?flag=true&waybillNo=' + event.waybillNo
				});
			},
			// 确定签收/拒收
			confirm() {
				let params = {
					waybillNo: this.orderNumber,
					receiptImg: this.imageUrl,
					status: 5,
					rejectionReason: this.rejectionValue,
					receiptsign: this.imageData,
					paymentType: this.modePayment,
					paymentStatus: this.statePayment,
					paymentremark: this.remarksSettled,
				}
				let verify = false
				if (this.rejectionFlag) {
					params.status = 6
					verify = this.verification(params)
				} else {
					params.status = 5
					verify = this.verification(params)
				}
				if (verify) {
					this.signLoading = true
					this.$api.post('/api/waybill/receipt', params).then(res => {
						if (res.code == 200) {
							this.signForShow = false
							uni.$u.toast(res.msg)
							this.$emit('operateSuccessfully')
						} else {
							uni.$u.toast(res.msg)
						}
						this.signLoading = false
					})
				}
			},
			// 拒收签收验证
			verification(params) {
				let flag = false
				if (this.rejectionFlag) {
					if (params.receiptImg) {
						flag = true
					} else {
						uni.$u.toast('请上传' + this.signRejection + '图片')
					}
				} else {
					if (params.paymentType) {
						if (params.paymentStatus) {
							if (params.receiptImg) {
								flag = true
								// if (params.receiptsign) {
								// 	flag = true
								// } else {
								// 	uni.$u.toast('请上传客户签字图片')
								// }
							} else {
								uni.$u.toast('请上传' + this.signRejection + '图片')
							}
						} else {
							uni.$u.toast('请选择支付状态')
						}
					} else {
						uni.$u.toast('请选择支付方式')
					}
				}
				return flag
			},
			// 修改防拆标签
			async modifiedTamper() {
				let flag2 = await this.$refs['goods'].validateForm();
				if (flag2) {
					let params = {
						senderAddressName: this.antiList.senderAddressName,
						senderAddressPhone: this.antiList.senderAddressPhone,
						senderAddressDetails: this.antiList.senderAddressDetails,
						consigneeAddressName: this.antiList.consigneeAddressName,
						consigneeAddressPhone: this.antiList.consigneeAddressPhone,
						consigneeAddressDetails: this.antiList.consigneeAddressDetails,
						deliveryName: this.antiList.deliveryName,
						deliveryPhone: this.antiList.deliveryPhone,
						...this.goodsModel,
					}
					uni.showLoading();
					// 修改运单
					this.$api.put('/api/waybill', params).then(res => {
						if (res.code == 200) {
							this.antiShow = false
							uni.$u.toast(res.msg)
							this.$emit('proofRenewal')
						} else {
							uni.$u.toast('修改失败')
						}
						uni.hideLoading();
					}).catch(() => {
						uni.hideLoading();
					})
				}
			},
			// 打印温湿度记录
			humidityRecording(value) {
				this.$cache.setCache('commodity', JSON.stringify(value))
				uni.navigateTo({
					url: '/pages/order/quantum?waybillNo=' + value.waybillNo + '&printType=record'
				});
			},
			// 修改运单
			modifyOrder(value) {
				this.$cache.setCache('orderDetails', value)
				uni.redirectTo({
					url: '/pages/order/addWaybill?title=修改运单&type=2'
				});
			},
			// 运单详情
			goOrderDetails(value) {
				this.$cache.setCache('orderDetails', value)
				uni.navigateTo({
					url: '/pages/order/orderDetails?type=details'
				});
			},
			// 运单状态
			orderStatus(value) {
				if (value == 3) {
					return '待配送'
				} else if (value == 4) {
					return '配送中'
				} else if (value == 5) {
					return '已送达'
				} else if (value == 6) {
					return '已拒收'
				} else if (value == 8) {
					return '已取消'
				}
			},
			// 运单文字颜色
			getState(value) {
				if (value == 3) {
					return '#9ddd54'
				} else if (value == 4) {
					return '#4bc7fc'
				} else if (value == 5) {
					return '#1cc723'
				} else if (value == 6) {
					return '#fe880e'
				} else if (value == 8) {
					return '#fa3534'
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				uni.showLoading({
					title: '上传中',
					mask: true,
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				var arr = []
				this.fileList1.forEach(item1 => {
					arr.push(item1.url)
				})
				uni.hideLoading();
				this.imageUrl = arr.join()
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				var arr = []
				this.fileList1.forEach(item1 => {
					arr.push(item1.url)
				})
				this.imageUrl = arr.join()
			},
			// 签字
			goSignature(title) {
				uni.navigateTo({
					url: '/pages/order/signatureBoard'
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: ENV.APP_DEV_URL + '/api/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
						},
						success: (res) => {
							let state = JSON.parse(res.data)
							setTimeout(() => {
								if (state.code == 200) {
									resolve(state.data)
								}
							}, 100)
						}
					});
				})
			},
			// 确定完成订单
			definiteCompletion() {
				this.$api.put('/api/waybill/update-status', {
					id: [this.orderId],
					status: 5,
				}).then(res => {
					if (res.code == 200) {
						uni.$u.toast('操作成功')
						this.$emit('definiteCompletion')
					} else {
						uni.$u.toast(res.msg)
					}
					this.logoutShow = false
				})
				console.log('确定完成订单')
			},
			// 取消
			cancel() {
				this.logoutShow = false
			},
			close() {
				this.signForShow = false
				this.modePayment = null
				this.statePayment = null
				this.remarksSettled = ''
				this.fileList1 = []
				this.imageData = ''
				this.rejectionValue = ''
				this.antiShow = false
			},
		}
	}
</script>

<style lang="scss">
	.card_ordermang {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
		margin: 20rpx;
	}

	.head_ordermang {
		margin-bottom: 10rpx;
	}

	.title_ordermang {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #909399;

		span {
			font-size: 26rpx;
			color: #909399;
			margin-right: 10rpx;
		}
	}

	.waybill_title {
		font-size: 30rpx;

		span {
			margin-left: 10rpx;
		}
	}

	.card_state {
		color: #606266;
		font-size: 28rpx;
	}

	.card_specification {
		display: flex;
		align-items: center;
	}

	.specification_title {
		margin-right: 20rpx;
	}

	.btn_printil {
		flex: 1;
		margin-top: 10px;
	}

	.markd10:nth-child(1) {
		margin: 10rpx 10rpx 0rpx 0rpx;
	}

	.markd10:nth-child(2) {
		margin: 10rpx 0rpx 0rpx 10rpx;
	}

	.markd10:nth-child(3) {
		margin: 10rpx 0rpx 0rpx 20rpx;
	}

	.title_sign {
		padding: 10rpx 0rpx;
		height: 60rpx;
	}

	.card_sign_for {
		width: 640rpx;
		padding: 10rpx 30rpx 30rpx 30rpx;
	}

	.rejection_card {
		margin-bottom: 20rpx;
	}

	.card_image_sign {
		display: flex;
		flex-direction: column;
		margin-bottom: 10rpx;
	}

	.img_sign_rejection {
		font-size: 30rpx;
		margin-bottom: 20rpx;
	}

	.card_dismantle {
		padding: 30rpx;
	}

	.headline_anti {
		font-size: 38rpx;
		font-weight: 600;
		display: flex;
		justify-content: center;
		border-bottom: 1rpx solid #e7e6e4;
		padding-bottom: 15rpx;
		margin-bottom: 15rpx;
		align-items: center;
	}

	::v-deep .u-radio-group--row {
		flex-wrap: wrap;
	}
</style>