<template>
	<view class="list">
		<!-- <uni-search-bar @confirm="search" :focus="true" v-model="searchValue" @blur="blur" @focus="focus" @input="input" @cancel="cancel" @clear="clear"></uni-search-bar> -->
		<uni-easyinput v-model="searchValue" placeholder="请输入单号" suffixIcon="scan" @iconClick="scanInput" />
		<view class="item" v-for="(item, i) in waybillDelivery" :key="i" @click="itemClick(item)">
			<view class="order-no">
				<text>
					派送单号: {{ item.order_no }}
				</text>
				<image @click="copyOrderNo(item.order_no)" class="icon" src="/static/copy.png" mode="aspectFill" />
			</view>
			<view class="address-info">
				<view class="info">
					<view class="user">
						<text>
							{{ item.address.first_name + ' ' + item.address.last_name }}
							{{ '+' + item.address.mobile_code + ' ' + item.address.mobile }}
						</text>
						<image @click="callPhone(item.address.mobile_code + ' ' + item.address.mobile)" class="icon" src="/static/call.png" mode="aspectFill" />
					</view>
					<view>
						<text class="address">
							<text class="city">{{ item.address.city }}</text>
							{{ item.address.zip_code }}
						</text>
						<image @click="copyOrderNo(item.address.zip_code)" class="icon" src="/static/copy.png" mode="aspectFill" />
					</view>
				</view>
				<view class="info"></view>
			</view>
			<view></view>
			<view class="operations">
				<button v-for="(operation, i) in item.operations" :key="i" @click="onButtonClick(item, operation.value)" type="info" size="mini">{{ operation.text }}</button>
			</view>
		</view>

		<view v-if="waybillDelivery.length === 0" class="is-empty">暂无派送单</view>

		<uni-popup ref="messageRef" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<uni-drawer ref="showRightRef" mode="right" :mask-click="true">
			<scroll-view style="height: 100%" scroll-y="true">
				<view class="button-group">
					<button @click="resetForm" type="info">重置</button>
					<button @click="confirmForm" type="primary">确认</button>
				</view>
			</scroll-view>
		</uni-drawer>
	</view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import permision from '@/common/permission.js';
import { onLoad, onNavigationBarButtonTap } from '@dcloudio/uni-app';
import { pickupWaybillDeliveryOrderURL, sendOutURL, deliveredURL, refuseURL, createTrackPodURL, cancelFedExPickUpURL } from '@/utils/api.js';
const loading = ref(false);
const loadingBtn = ref(false);
const token = ref();
const searchValue = ref();
const waybillDelivery = ref([]);
const messageType = ref();
const messageText = ref();
const messageRef = ref();
const showRightRef = ref();


const resetForm = () => {};
const confirmForm = () => {
	showRightRef.value.close();
};

const copyOrderNo = (order_no) => {
	uni.setClipboardData({
		data: order_no,
		success: function () {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
				duration: 2000
			});
		},
		fail: function () {
			console.log('复制失败');
		}
	});
};

const callPhone = (phoneNumber) => {
	console.log(phoneNumber);
	// #ifdef APP-PLUS
	uni.makePhoneCall({
		phoneNumber: phoneNumber,
		success: function () {
			console.log('拨打电话成功！');
		},
		fail: function () {
			console.log('拨打电话失败！');
		}
	});
	// #endif

	// #ifdef MP-WEIXIN
	wx.makePhoneCall({
		phoneNumber: phoneNumber,
		success: function () {
			console.log('拨打电话成功！');
		},
		fail: function () {
			console.log('拨打电话失败！');
		}
	});
	// #endif
};

const checkPermission = async () => {
	let status = permision.isIOS ? await permision.requestIOS('camera') : await permision.requestAndroid('android.permission.CAMERA');

	if (status === null || status === 1) {
		status = 1;
	} else {
		uni.showModal({
			content: 'Camera permission required',
			confirmText: 'Setting',
			success: function (res) {
				if (res.confirm) {
					permision.gotoAppSetting();
				}
			}
		});
	}
	return status;
};

const scanInput = async () => {
	// #ifdef APP-PLUS
	let status = await checkPermission();
	if (status !== 1) {
		return;
	}
	// #endif
	uni.scanCode({
		success: (res: any) => {
			// valiFormData.value.order_code = res.result;
			// onsubmit();
		},
		fail: (err) => {
			// 需要注意的是小程序扫码不需要申请相机权限
		}
	});
};

const itemClick = (item: any) => {
	uni.setStorageSync('selectItem', item);

	uni.navigateTo({
		url: '/pages/waybillDeliveryOrder/orderInfo?id=' + item.id
	});
};

const onButtonClick = async (row, value) => {
	if (value === 'send_out') {
		sendOut({ id: row.id });
	} else if (value === 'delivered') {
		//确认送达
		updateDelivered({ id: row.id });
	} else if (value === 'refuse') {
		updateRefuse({ id: row.id });
	} else if (value === 'create_track_pod') {
		createTrackPod({ id: row.id });
	} else if (value === 'edit') {
		// baTable.form.items = row;
		// baTable.form.operate = 'edit';
	} else if (value === 'generate_label') {
		// baTable.form.items = row;
		// generateLabelForm.id = row.id;
		// generateLabelVisible.value = true;
	} else if (value === 'fedex_appointment_pick_up') {
		// baTable.form.items = row;
		// baTable.form.operate = 'FedExPickUp';
	} else if (value === 'print_get_back_label') {
		// toPrintRetrieve(row);
	} else if (value === 'fedex_cancel_pick_up') {
		cancelFedExPickUp({ id: row.id });
	}
};

const sendOut = (data) => {
	loadingBtn.value = true;
	uni.request({
		url: sendOutURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: ({ data }: any) => {
			loadingBtn.value = false;
			messageType.value = 'success';
			messageText.value = '发出成功';
			messageRef.value.open();
		},
		fail: (err) => {
			loadingBtn.value = false;
			messageType.value = 'error';
			messageText.value = '发出失败，请稍后重试';
			messageRef.value.open();
		}
	});
};

const updateDelivered = (data) => {
	loadingBtn.value = true;
	uni.request({
		url: deliveredURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: ({ data }: any) => {
			loadingBtn.value = false;
			messageType.value = 'success';
			messageText.value = '确认送达成功';
			messageRef.value.open();
		},
		fail: (err) => {
			loadingBtn.value = false;
			messageType.value = 'error';
			messageText.value = '确认送达失败，请稍后重试';
			messageRef.value.open();
		}
	});
};

const updateRefuse = (data) => {
	loadingBtn.value = true;
	uni.request({
		url: refuseURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: ({ data }: any) => {
			loadingBtn.value = false;
			messageType.value = 'success';
			messageText.value = '已拒绝签收';
			messageRef.value.open();
		},
		fail: (err) => {
			loadingBtn.value = false;
			messageType.value = 'error';
			messageText.value = '修改失败，请稍后重试';
			messageRef.value.open();
		}
	});
};

const createTrackPod = (data) => {
	loadingBtn.value = true;
	uni.request({
		url: createTrackPodURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: ({ data }: any) => {
			loadingBtn.value = false;
			messageType.value = 'success';
			messageText.value = '同步成功';
			messageRef.value.open();
		},
		fail: (err) => {
			loadingBtn.value = false;
			messageType.value = 'error';
			messageText.value = '同步失败，请稍后重试';
			messageRef.value.open();
		}
	});
};

const cancelFedExPickUp = (data) => {
	loadingBtn.value = true;
	uni.request({
		url: cancelFedExPickUpURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: ({ data }: any) => {
			loadingBtn.value = false;
			messageType.value = 'success';
			messageText.value = '操作成功';
			messageRef.value.open();
		},
		fail: (err) => {
			loadingBtn.value = false;
			messageType.value = 'error';
			messageText.value = '操作失败，请稍后重试';
			messageRef.value.open();
		}
	});
};

const getList = () => {
	loading.value = true;
	uni.request({
		url: pickupWaybillDeliveryOrderURL + '/index',
		method: 'GET',
		header: {
			batoken: token.value
		},
		success: ({ data }: any) => {
			loading.value = false;
			console.log(data);
			if (data.code == 1) {
				waybillDelivery.value = data.data.list;
			} else {
				messageType.value = 'error';
				messageText.value = data.msg;
				messageRef.value.open();
			}
		},
		fail: (err) => {
			loading.value = false;
		}
	});
};
onLoad(() => {
	token.value = uni.getStorageSync('token');
	getList();
});
onNavigationBarButtonTap((event) => {
	if (event.index === 0) {
		showRightRef.value.open();
	}
});
</script>

<style lang="scss" scoped>
.list {
	margin: 0 auto;
	display: flex;
	flex-direction: column;
	// justify-content: center;
	align-items: center;
	flex: 1;

	.uni-easyinput {
		margin-top: 20rpx;
		width: calc(100% - 40rpx);
	}

	.item {
		margin-top: 20rpx;
		width: 95%;
		box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.2);
		border-radius: 20rpx;
		background-color: #fff;

		.order-no {
			padding: 14rpx;
			font-size: 16rpx;
		}

		.icon {
			margin-left: 5rpx;
			width: 24rpx;
			height: 24rpx;
		}

		.address-info {
			padding: 14rpx;
			font-size: 16rpx;
			margin-bottom: 10rpx;

			.info {
				display: flex;
				flex-direction: column;

				.user {
					margin-bottom: 10rpx;
					font-weight: bold;
				}

				.address {
					.city {
						font-size: 30rpx;
						font-weight: bold;
					}
				}
			}
		}
	}
	.is-empty {
		margin-top: 20rpx;
	}
}

.operations {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	width: 100%;

	button {
		font-size: 16rpx;
		margin: 10rpx;
	}
}

.button-group {
	margin-top: 15px;
	display: flex;
	flex-direction: row;
	justify-content: space-around;

	button {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 35px;
		width: 50%;
		margin-left: 10px;
		font-size: 16rpx;
	}

	.uni-icons {
		margin-right: 10px;
	}
}
</style>
