<template>
	<!-- popup -->
	<view>
		<uni-popup ref="deliveryOrderPopup" type="bottom" @change="changePopup">
			<view class="text-bold text-gray text-lg text-center left-top-sm-bar" data-popup="deliveryOrderPopup" @click="closePopup"><text
					class="cuIcon-close"></text></view>
			<view class="bg-white padding" style="padding-top: 74rpx; min-height: 1000rpx;">
				<view>
					<view class="solid-bottom padding-bottom-sm">
						<view v-if="columnTitleArr.length" class="flex justify-between margin-tb-sm">
							<view class="basis-df">{{columnTitleArr[0]}}</view>
							<view class="flex justify-end text-center basis-df">
								<view v-for="(title, index) in columnTitleArr" v-if="index >= 1" class="basis-df">{{title}}</view>
							</view>
						</view>
						<view class="flex justify-between margin-tb-xs align-center" v-for="(item,index) in pickedList" :key="index">
							<view class='cu-tag padding basis-lg'>{{item.goodsName}}</view>
							<view class="flex justify-end basis-df text-center align-center">
								<view class="basis-df">{{item.goodsNum}}</view>
								<view class="basis-df">
									<uni-number-box :min="0" :max="item.goodsNum" v-model="item.toAssignNum" @change="changePiecesNum($event, item)">
									</uni-number-box>
								</view>
							</view>
						</view>
					</view>
					<view class="padding-top-sm padding-bottom-xs flex justify-between align-center">
						<text class="margin-right-sm">本单可派任务金额：<text class="text-red text-lg">{{curOrder.serverMoney}}</text></text>
					</view>
					<view class="padding-bottom-sm flex justify-between align-center">
						<text class="margin-right-sm" style="width: 150rpx;">派单价格</text>
						<input type="digit" class="line-input radius-input" v-model="dispatchTotalPrice" placeholder="请输入派出总额"></input>
					</view>
				</view>
				
				<view class="solid-bottom padding padding-bottom-sm">
					<view class="flex justify-between align-center margin-bottom-xs padding-top">
						<view>
							<text class="text-xxl text-main-color"><text class="cuIcon-phone"></text></text>
							<text class="text-bold text-lg margin-lr-xs">{{data.customerPhone.substring(0, 3) + "****" + data.customerPhone.substring(7)}}</text>
						</view>
						<button class="cu-btn line-main-color" @click="makePhoneCall(data.customerPhone)">拨打</button>
					</view>
					<view class="text-sm">
						{{orderType === 1 ? '分次发货，请输入发货日期与时间，然后在”发货预约“栏按时发货。' : '拨打电话，按与客户约定的时间填入，完成排单，未完成排单将导致排单超时！'}}
					</view>
				</view>
				
				<view class="padding">
					<view class="margin-bottom-xs">
						<view class="margin-bottom-xs">选择日期：</view>
						<picker class="relative-view" mode="date" :value="date" :start="curDate" @change="dateChange">
							<input class="radius-input" v-model="date" disabled>
								<view class="text-lg input-arrow"><text class="cuIcon-triangledownfill"></text></view>
							</input>
						</picker>
					</view>
					<view>
						<view class="margin-bottom-xs">选择时间：</view>
						<view class="flex justify-start align-center">
							<picker class="relative-view" :class="disableTime ? 'readonlyPicker' : ''" mode="selector" :value="timeIndex" :range="timeList"
								@change="timeChange" @click="showTime">
								<input class="custom-input radius-input" v-model="time" disabled>
									<view class="text-lg input-arrow"><text class="cuIcon-triangledownfill"></text></view>
								</input>
							</picker>
							<text class="margin-lr-xs">或</text>
							<picker class="relative-view" :class="!disableTime ? 'readonlyPicker' : ''" mode="selector" :value="timeRangeIndex" :range="timeRangeList"
								@change="timeRangeChange" @click="showDuration">
								<input class="custom-input radius-input" v-model="timeRange" disabled>
									<view class="text-lg input-arrow"><text class="cuIcon-triangledownfill"></text></view>
								</input>
							</picker>
						</view>
					</view>
				</view>
				<view class="cu-bar bg-white solid-top">
					<view class="action margin-0 flex-sub text-black" @tap="closePopup">取消</view>
					<view class="action margin-0 flex-sub text-main-color solid-left" @click="assignWork">提交</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		emits: ['confirmFeedback', 'close'],
		props: {
			show: {
				type: Boolean,
				default: false
			},
			data: {
				type: Object,
				default: () => {}
			},
			product: {
				type: Object,
				default: {}
			},
			orderType: {
				type: Number,
				default: 0
			}
		},
		watch: {
			show: {
				handler(newVal) {
					if(newVal) {
						this.$nextTick(() => {
							this.$refs.deliveryOrderPopup.open()
							this.loadData(this.data)
						})
					}
				},
				immediate: true
			}
		},
		data() {
			return {
				dispatchTotalPrice: null,
				showDispatchPriceModal: false,
				columnTitleArr: ['购买机型', '待派单', '派单量'],
				curOrder: {},
				pickedList: [],
				workerName: null,
				curUserInfo: null,
				date: null,
				time: null,
				timeList: [],
				timeIndex: 0,
				timeRangeList: [],
				timeRange: null,
				timeRangeIndex: 0,
				expectTimeStart: null,
				expectTimeEnd: null,
				disableTime: false
			}
		},
		onReady() {
			this.timeRangeList = this.$globalData.timeRangeList;
			this.timeList = this.$globalData.timeList;
		},
		methods: {
			changePopup(e) {
				console.log(e);
				if(!e.show) {
					this.closePopup()
				}
			},
			closePopup() {
				this.$emit('close')
			},
			dateChange(e) {
				this.date = e.detail.value;
				this.changeExpectTime();
			},
			showTime() {
				this.disableTime = false;
			},
			showDuration() {
				this.disableTime = true;
			},
			timeChange(e) {
				this.timeIndex = e.detail.value;
				this.time = this.timeList[this.timeIndex];
				this.timeRange = null;
				this.changeExpectTime();
			},
			timeRangeChange(e) {
				this.timeRangeIndex = e.detail.value;
				this.timeRange = this.timeRangeList[this.timeRangeIndex];
				this.time = null;
				this.changeExpectTime();
			},
			changeExpectTime() {
				let time = this.time != null ? this.time : this.timeRange;
				if (time != null) {
					let timeRangeSplit = this.$globalData.timeRangeSplit;
					let timeArr = time.split(timeRangeSplit);
					this.expectTimeStart = this.date + ' ' + timeArr[0] + ':00';
					this.expectTimeEnd = this.date + ' ' + timeArr[1] + ':00';
				}
			},
			showModal(e) {
				this[e.currentTarget.dataset.modal] = true;
			},
			hideModal(e) {
				this[e.currentTarget.dataset.modal] = false;
			},
			changePiecesNum(curNum, curItem) {
				curItem.toAssignNum = curNum;
			},
			resetData() {
				this.dispatchTotalPrice = null;
				this.pickedList = [];
				this.curOrder = {};
				this.curUserInfo = null;
				this.date = null;
				this.time = null;
				this.timeRange = null;
				this.timeRangeIndex = 0;
				this.expectTimeStart = null,
				this.expectTimeEnd = null;
			},
			loadData(order) {
				this.resetData();
				this.curUserInfo = this.$request.getCurUserInfo();
				this.getCanAssignList(order);
			},
			async getCanAssignList(order) {
				// 获取最新的订单信息
				let getOrderRes = await this.$request.getOrderMasterDetail({
					id: order.orderMasterId
				});
				
				let res = await this.$request.getCanAssignList({
					orderMasterId: order.orderMasterId
				});
				let pickedList = res.data;
				this.curOrder = getOrderRes.data;
				this.pickedList = pickedList;
			},
			assignWork() {
				let goodsToAssign = [];
				// 标识是否派完所有goods，1为派完，0为未派完
				let isAll = 1;
				this.pickedList.forEach((item) => {
					if (item.toAssignNum && item.goodsNum !== item.toAssignNum) {
						isAll = 0;
					}
					if (item.toAssignNum) {
						goodsToAssign.push({
							goodsStandardId: item.goodsStandardId,
							num: item.toAssignNum
						})
					}
				});
				if (goodsToAssign.length > 0) {
					if (this.dispatchTotalPrice) {
						if (!(this.time || this.timeRange)) {
							uni.showToast({
								title: '请选择预约时间',
								icon: 'none'
							})
							return;
						}
						this.UpdateTime()
						let params = {
							goodsList: goodsToAssign,
							workerId: this.curUserInfo.workerId,
							totalPay: this.dispatchTotalPrice,
							orderMasterId: this.curOrder.orderMasterId,
							isAll: isAll,
							workerName: this.curUserInfo.realName
						}
						this.$emit('assignWork', params);
					} else {
						uni.showToast({
							title: '请填写派单价格',
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: '请至少选择一种规格',
						icon: 'none'
					})
				}
			},
			makePhoneCall(customerPhone) {
				uni.makePhoneCall({
					phoneNumber: customerPhone
				})
			},
			async UpdateTime() {
				const datetimeArr = [this.expectTimeStart, this.expectTimeEnd];
				let reqFunName = "updateOrder", id;
				if (this.data.orderDetailId == null) {
					id = this.data.orderMasterId;
				} else {
					reqFunName = "updateDetailOrder";
					id = this.data.orderDetailId;
				}
				// 确定参数
				let params = datetimeArr && datetimeArr.length > 1 ? {
					id: id,
					expectTimeStart: datetimeArr[0],
					expectTimeEnd: datetimeArr[1],
					useTimeNotRange: datetimeArr[1] == null ? true : false
				} : {
					id: id,
					revTime: datetime
				}
				
				let res = await this.$request[reqFunName](params);
				if (res.code === 0) {
					this.$emit('confirmFeedback')
				} else {
					uni.showToast({
						title: '操作失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style scoped>
	
	.relative-view {
		position: relative;
	}
	
	.input-arrow {
		position: absolute;
		right: 10rpx;
		top: 25%;
	}
</style>