<template>
	<view class="content">
		<wd-message-box></wd-message-box>
		<wd-message-box selector="wd-message-box-slot" use-slot>
			<view>
				<wd-form :model="shipmentsModel">
					<wd-cell-group border>

						<view class="mb-4">
							<wd-radio-group v-model="shipmentsModel.send_type" shape="button" @change="change">
								<wd-radio :value="1">快递发货</wd-radio>
								<wd-radio :value="2">无需物流</wd-radio>
							</wd-radio-group>
						</view>

						<view class="mb-4 overflow-hidden bg-white border-gray-100 border-solid border-[8px] p-3 rounded"
							v-if="shipmentsModel.send_type == 1">

							<view class="mb-2">
								<wd-radio-group shape="button" v-model="shipmentsModel.delivery_company">
									<view class="flex overflow-auto">
										<wd-radio v-for="item of expressList" :value="item.value">{{ item.label }}</wd-radio>
									</view>
								</wd-radio-group>
							</view>

							<wd-input label-width="100px" clearable v-model="shipmentsModel.delivery_no" placeholder="快递单号">
							</wd-input>
						</view>

					</wd-cell-group>
				</wd-form>
			</view>
		</wd-message-box>

		<view class=" bg-white sticky top-0 z-50">
			<wd-search @search="search" @clear="search({ value: '' })" v-model="params.keywords" hide-cancel>
				<template #prefix>
					<wd-popover v-model="popover" mode="menu" :content="menu" @menuclick="changeSearchType">
						<view class="search-type">
							<text>{{ searchType }}</text>
							<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
						</view>
					</wd-popover>
				</template>
			</wd-search>
			<!-- <wd-drop-menu>
				<wd-drop-menu-item v-model="shipmentsModel.delivery_company" :options="expressList" />
			</wd-drop-menu> -->
			<wd-tabs @change="(e) => {
				params.status = e.index;
				search({ value: params.keywords })
			}" v-model="params.status">
				<wd-tab v-for="item in status" :key="item" :title="`${item.content}`"></wd-tab>
			</wd-tabs>
		</view>

		<view class="goodsBox p-2">
			<myList ref="myListRef" :apiObj="order.orderList" :params="{ ...params, status: params.status - 1 }">
				<template #default="{ list }">
					<view>
						<view v-for="item of list" class="goods">
							<wd-card type="rectangle">
								<template #title>
									<view class="title">

										<view>
											<span class="mr-2" v-if="item.shop">{{ item.shop.name }}</span>
											<span class="mr-2" v-else>商城自营</span>
											<span class="font-bold">({{ status[item.status + 1].content }})</span>
										</view>

										<view class="title-tip">
											<span style="font-size: 24rpx;margin-left: 8px;">单号：{{ item.order_no }}</span>
										</view>
									</view>
								</template>

								<view v-for="subItem of item.details" style="height: 60px;" class="content mb-4">
									<image :src="subItem.goods_pic" width="40" height="40" alt="joy"
										style="border-radius: 4px; margin-right: 12px;width: 60px;height: 60px;min-width: 60px;" />
									<view>
										<view class="line2" style="color: rgba(0,0,0,0.85); font-size: 16px;">{{ subItem.goods_name }}</view>
										<!-- <view class="font-bold" style="color: rgb(255, 0, 0); font-size: 16px;">￥{{ subItem.price }}
										</view> -->
										<view class="font-bold">小计: {{ subItem.price }} 元 <text
												style="color: rgb(255, 0, 0); font-size: 24rpx;">({{
													subItem.num }}) 件</text></view>
									</view>
								</view>

								<view class="bg-gray-50 p-2">
									<view class="text-[12px]" v-if="item.user">
										<view class="mb-1">
											下单用户：{{ item.user.nickname }}
											<text class="font-bold">
												( 会员ID：{{ item.user.id }} )
											</text>

											<view class="bg-gray-100 my-2 p-2">
												<view>收货人：{{ item.receiver_name }} &nbsp; 电话：{{ item.receiver_phone }}</view>
												<view>收货地址：{{ item.delivery_address }} {{ item.delivery_address_detail }}</view>
											</view>
										</view>

										<view class="flex items-center" v-if='[0, 1, 2][item.delivery_type]'>配送方式:
											<wd-tag class="ml-2" :type="['', 'success', 'primary'][item.delivery_type]">
												{{ ["", "快递配送", "到店自提"][item.delivery_type] }}
											</wd-tag>

											<view class="ml-2" v-if="item.delivery_type == 1">
												<wd-tag type="warning">
													运费: {{ item.delivery_money }}元
												</wd-tag>
											</view>
										</view>
									</view>
								</view>

								<template #footer>
									<view class="bg-gray-50 p-2 mb-2.5 flex justify-between" style="font-size: 22rpx;">
										<view>应付: {{ (Number(item.total_price) + Number(item.delivery_money)).toFixed(2) }} 元</view>
										<view>余额支付: {{ item.pay_balance }} 元</view>
										<view v-if="((Number(item.total_price) + Number(item.delivery_money)) -
											item.pay_price) > 0">优惠: {{ ((Number(item.total_price) + Number(item.delivery_money)) -
		item.pay_price).toFixed(2) }} 元</view>
									</view>

									<view class="flex justify-between items-center">
										<view class="font-bold">实付: {{ item.pay_price }} 元</view>
										<view class="flex-1 flex justify-end">

											<view v-if="item.apply_cancel === 1" class="mr-2">
												<wd-button type="error" @click="orderApproval(item)" size="small">退款</wd-button>
											</view>

											<view class="mr-2">
												<wd-button @click="printing(item)" size="small">小票打印</wd-button>
											</view>
											<view class="mr-2">
												<wd-button @click="orderNotes(item)" size="small">备注</wd-button>
											</view>
											<view v-if="item.status == 1" class="">
												<wd-button @click="shipments(item)" size="small">发货</wd-button>
											</view>
										</view>

									</view>
								</template>
							</wd-card>
						</view>
					</view>
				</template>
			</myList>
		</view>
		<wd-toast />
	</view>
</template>

<script setup>
import order from '@/api/store/order.js';
import myList from "/components/myList/index.vue";
import { useMessage } from '@/uni_modules/wot-design-uni';
import { useToast } from '@/uni_modules/wot-design-uni';
import { ref } from 'vue';

const message = useMessage('wd-message-box-slot');
const message1 = useMessage();
const toast = useToast();

const classify_id = ref(0);

const params = ref({
	keywords: "",
	status: "",
	type: 'order_no'
});

const myListRef = ref(null);

const search = ({ value }) => {
	myListRef.value.upData({
		keywords: value,
		classify_id: classify_id.value,
		status: params.value.status - 1
	});
};

const searchType = ref('订单编号');
const popover = ref(false);

const status = ref([
	{ content: '全部' },
	{ content: '未付款' },
	{ content: '待发货' },
	{ content: '已发货' },
	{ content: '已完成' },
	{ content: '已取消' },
	{ content: '待处理' },
	{ content: '回收站' }
]);

const menu = ref([
	{ content: '订单编号' },
	{ content: '商品名称' },
	{ content: '手机号' },
	{ content: '会员昵称' },
	{ content: '收货人' },
]);

/**
 * 切换搜索类型
 * @param {Object} item - 切换的项
 */
function changeSearchType({ item, index }) {
	searchType.value = item.content;

	if (item.content == '订单编号') {
		params.value.type = "order_no";
	}
	if (item.content == '商品名称') {
		params.value.type = "goods_name";
	}
	if (item.content == '手机号') {
		params.value.type = "receiver_phone";
	}
	if (item.content == '会员昵称') {
		params.value.type = "nickname";
	}
	if (item.content == '收货人') {
		params.value.type = "receiver_name";
	}
}

/**
 * 更改状态
 * @param {Object} row - 行数据
 */
const changeS = (row) => {
	// 处理状态改变的逻辑
	// goods.goodsEditAttribute({
	//   id: item.id,
	//   value: [1, 0][item.status],
	//   type: "status"
	// }).then(res => {
	//   if (res.code == 0) {
	//     toast.success('操作成功')
	//     item.status = [1, 0][item.status]
	//   } else {
	//     showNotify({ type: 'error', message: '出错了' })
	//   }
	// })
};

const expressList = ref([]);

/**
 * 获取物流公司列表
 */
const getExpressList = () => {
	order.GetExpressList().then(res => {
		expressList.value = Object.entries(res.data).reduce((express, item) => {
			express.push({ label: item[1], value: item[0] });
			return express;
		}, []);
	});
};

// 初始化调用获取物流公司列表
getExpressList();

const shipmentsModel = ref({
	send_type: 2,
	delivery_company: ""
});

/**
 * 处理发货操作
 * @param {Object} row - 行数据
 */
const shipments = (row) => {
	message
		.confirm({
			title: '订单发货',
		})
		.then((resp) => {
			if (shipmentsModel.value.send_type == 2) {
				order.orderSend({
					id: row.id,
					send_type: "2"
				});
				row.status = 2;
				toast.success('操作成功');
				setTimeout(() => {
					shipmentsModel.value = {
						send_type: 2,
						delivery_company: ""
					};
				}, 300);
			}

			if (shipmentsModel.value.send_type == 1) {
				if (shipmentsModel.value.delivery_company && shipmentsModel.value.delivery_no) {
					order.orderSend({
						id: row.id,
						send_type: "1",
						delivery_company: shipmentsModel.value.delivery_company,
						delivery_no: shipmentsModel.value.delivery_no,
					});
					row.status = 2;
					row.success('操作成功');
					setTimeout(() => {
						shipmentsModel.value = {
							send_type: 2,
							delivery_company: ""
						};
					}, 300);
				} else {
					toast.error('发货失败，请完善选择填写');
					shipments(row);
				}
			}
		})
		.catch((error) => {
			console.log(error);

			setTimeout(() => {
				shipmentsModel.value = {
					send_type: 2,
					delivery_company: ""
				};
			}, 300);
		});
};

/**
 * 处理打印小票操作
 * @param {Object} row - 行数据
 */
const printing = (row) => {
	message1
		.confirm({
			title: '打印小票',
		})
		.then((resp) => {
			order.printOrder({
				id: row.id,
				send_type: "2"
			}).then(res => {
				if (res.code == 0) {
					toast.success('调用成功');
				} else {
					toast.error('调用失败');
				}
			});
		})
		.catch((error) => {
			console.log(error);
		});
};

/**
 * 处理订单备注操作
 * @param {Object} row - 行数据
 */
const orderNotes = (row) => {
	message1
		.prompt({
			title: '订单备注',
		})
		.then((resp) => {
			order.updateNotes({
				id: row.id,
				notes: resp.value
			}).then(res => {
				if (res.code == 0) {
					toast.success('操作成功');
				} else {
					toast.error('操作失败');
				}
			});
		})
		.catch((error) => {
			console.log(error);
		});
};

/**
 * 处理退款审批操作
 * @param {Object} row - 行数据
 */
const orderApproval = (row) => {
	message1
		.confirm({
			title: '退款审批',
			confirmButtonText: "同意",
			cancelButtonText: "拒绝",
		})
		.then((resp) => {
			order.confirmCancel({
				id: row.id,
				apply_cancel_notes: "同意",
				handle_status: 1
			}).then(res => {
				if (res.code == 0) {
					toast.success('操作成功');
					row.apply_cancel = 0;
				} else {
					toast.error('操作失败');
				}
			});
		})
		.catch((error) => {
			if (error.action == 'cancel') {
				order.confirmCancel({
					id: row.id,
					apply_cancel_notes: "拒绝",
					handle_status: 0
				}).then(res => {
					if (res.code == 0) {
						toast.success('操作成功');
						row.apply_cancel = 0;
					} else {
						toast.error('操作失败');
					}
				});
			}
		});
};


</script>

<style lang="scss" scoped>
.search-type {
	position: relative;
	height: 30px;
	line-height: 30px;
	padding: 0 8px 0 16px;
	font-size: 24rpx;
	color: rgba(0, 0, 0, .45);
}

.search-type::after {
	position: absolute;
	content: '';
	width: 1px;
	right: 0;
	top: 5px;
	bottom: 5px;
	background: rgba(0, 0, 0, 0.25);
}

.search-type {
	:deep(.icon-arrow) {
		display: inline-block;
		font-size: 20px;
		vertical-align: middle;
	}
}

.goodsBox {

	.content,
	.title {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
	}

	.content {
		justify-content: flex-start;
	}

	.title {
		justify-content: space-between;
	}

	.title-tip {
		color: rgba(0, 0, 0, 0.25);
		font-size: 12px;
	}
}
</style>
