<template>
	<view class="address-page">
		<view class="address-section">
			<pub-list-scroll ref="pubListScrollRef" @next="onScrollTolower" :loaded="loaded" :text="loadText"
				:status="status">
				<view class="no-data" v-if="(!list || list.length == 0)&&!loaded">
					<image mode="heightFix" src="/static/image/no-data.png" />
					暂无数据
				</view>
				<view class="address-list" v-else>
					<view v-for="(item,index) in list" :key="'cf'+index" class="address-item" @click="onClickItem(item.shrxxid)"
						:class="item.shrxxid==curAddressId?'is-active':''">
						<view class="row address-item-top">
							<view>{{item.shrxm}}</view>
							<view>{{item.shrsjh}}</view>
						</view>
						<view class="">{{ formattedAddress(item) }}</view>
						<view class="address-item-bottom">
							<view class="row" @click.stop="updateDefault(item)">
								<text class="iconfont checkbox is-active" v-if="item.isDefaulted">&#xe63b;</text>
								<text class="iconfont checkbox" v-else>&#xe8bb;</text>
								默认收件地址
							</view>
							<view class="row">
								<view class="row" @click.stop="openDetails('edit',item)"><text class="iconfont">&#xe6ae;</text>编辑</view>
								<view class="row next-btn" @click.stop="openDeletePopup('center',item.shrxxid)"><text
										class="iconfont">&#xe626;</text>删除
								</view>
							</view>
						</view>
					</view>
				</view>
			</pub-list-scroll>
		</view>
		<view class="pub-button is-bg large" @click="openDetails('add')">新增地址</view>

		<!-- 选择弹窗 -->
		<uni-popup ref="confirmPopup" type="dialog">
			<uni-popup-dialog type="info" cancelText="取消" confirmText="确定" content="确定使用快递配送？" @confirm="onApply"
				@close="onCancel"></uni-popup-dialog>
		</uni-popup>
		<!-- 删除弹窗 注意这里取消按钮的位置 -->
		<uni-popup ref="delPopup" type="dialog">
			<uni-popup-dialog type="info" cancelText="确定" confirmText="取消" content="确定删除该地址？" @confirm="onDelApply"
				@close="onDelCancel"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue'
	import dlg from '@/lib/dlg'
	import { aesEncrypt, aesDecrypt } from "@/lib/encryption";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import rest from '@/stores/rest'
	import * as link from '@/lib/link'
	import { BasicInfoVO } from '../../lib/type';

	const pubListScrollRef = ref(null)
	const scrollTop = ref(0)
	const loaded = ref(false)
	const loadText = ref('数据加载中...')
	const status = ref('loading')
	const list = ref() //处方列表
	const queryParams = ref({
		pageNo: 1,
		pageSize: 10,
		hzid: '',
	})
	const ptwybh = ref()
	const total = ref(0)


	const confirmPopup = ref() // 弹出层
	const delPopup = ref() // 删除弹出层
	const deleteId = ref() // 删除的id
	const curAddressId = ref() // 选中项
	const selAddressId = ref() // 点击项

	// 拼接地址
	const formattedAddress = (item) => {
		const { province, city, area, shrdzxxdz } = item
		return `${province || ''}${city || ''}${area || ''}${shrdzxxdz || ''}`
	}

	const openDeletePopup = (position, id) => {
		deleteId.value = id
		delPopup.value.open(position)
	}

	const onClickItem = (id : string) => {
		console.log("onClickItem", ptwybh.value)
		if (ptwybh.value) {
			selAddressId.value = id
			confirmPopup.value.open('center')
		}
	}

	const onDelCancel = async () => {
		// 从 list 中找到该项的位置
		const index = list.value.findIndex(item => item.shrxxid === deleteId.value);
		if (index !== -1) {
			const [removedItem] = list.value.splice(index, 1);
			// 执行删除接口
			try {
				await rest.del('/default/consignee-info/delete?id=' + deleteId.value, {});
			} catch (error) {
				list.value.splice(index, 0, removedItem);
			}
		} else {
			console.warn("未找到要删除的项");
		}
	}

	const onDelApply = () => {
		// 删除取消
	}

	const onCancel = () => {
	}
	const onApply = async () => {
		if (ptwybh.value) {
			curAddressId.value = selAddressId.value
			const data = {
				ptwybh: ptwybh.value,
				shrxxid: curAddressId.value,
				kd: true
			}
			await rest.put('/default/consignee-info/bindShrxxid', data);
			dlg.success('操作成功')
			link.back()
		}
	}

	// 修改默认
	const updateDefault = async (item) => {
		if (item.isDefaulted === null) {
			item.isDefaulted = true;
			const index = list.value.findIndex(i => i.shrxxid === item.shrxxid);
			if (index !== -1) {
				const [movedItem] = list.value.splice(index, 1);
				list.value.unshift(movedItem);
				if (list.value.length > 1) {
					list.value[1].isDefaulted = null;
				}
			}
			await rest.put('/default/consignee-info/update', item)
		}
	}

	const getList = async () => {
		try {
			loaded.value = true;
			let res = await rest.get('/default/consignee-info/list', queryParams.value) as BasicInfoVO
			let _list = res.list


			if (queryParams.value.pageNo === 1) {
				list.value = _list;
			} else {
				list.value = list.value.concat(_list);
			}

			total.value = res.total
			if (res.total && queryParams.value.pageNo >= total.value / queryParams.value.pageSize) {
				status.value = "noMore"
			}
			// 重置滚动位置 
			if (queryParams.value.pageNo === 1) {
				pubListScrollRef.value.goTop()
			}
		} catch (e) {
			dlg.error(e)
		} finally {
			loaded.value = false;
		}
	}

	//下一页
	const onScrollTolower = async () => {
		if (!list.value || queryParams.value.pageNo > (total.value / queryParams.value.pageSize)) {
			return false;
		}
		if (queryParams.value.pageNo < total.value / queryParams.value.pageSize) {
			status.value = "loading";
		} else {
			status.value = "noMore"
			return;
		}
		queryParams.value.pageNo++;
		getList();
	}


	const openDetails = (action, item = null) => {
		console.log("内容", item)
		if (item) {
			link.addAddress(aesEncrypt(queryParams.value.hzid), aesEncrypt(item.shrxxid), aesEncrypt(item.isDefaulted ? 'true' : 'false'))
		} else {
			link.addAddress(aesEncrypt(queryParams.value.hzid))
		}
	}


	onLoad((data) => {
		queryParams.value.hzid = aesDecrypt(data.hzid)
		if (data.ptwybh) {
			console.log("进入了嘛")
			ptwybh.value = aesDecrypt(data.ptwybh)
		}
	})
	onShow(() => {
		queryParams.value.pageNo = 1;
		getList()
	})
</script>

<style lang="scss" scoped>
	.address-page {
		display: flex;
		flex-direction: column;
		height: 100%;

		.address-section {
			flex: 1;
			overflow-y: auto;
			margin-top: 16rpx;

			.address-list {

				.address-item {
					background: #fff;
					margin-bottom: 24rpx;
					padding: 24rpx 32rpx 16rpx;
					color: $uni-text-color-grey;
					border: 1px solid #fff;

					.row {
						@include flex;
					}

					.address-item-top {
						font-size: $uni-font-size-lg;
						line-height: $uni-line-height-lg;
						color: $uni-text-color;
						margin-bottom: 24rpx;

						>view+view {
							margin-left: 32rpx;
						}
					}

					.address-item-bottom {
						border-top: 1px solid $uni-border-color;
						margin-top: 24rpx;
						padding-top: 16rpx;
						@include flex-between;
						font-size: $uni-font-size-sm;
						line-height: $uni-line-height-sm;

						.iconfont {
							font-size: 36rpx;
							margin-right: 8rpx;

							&.checkbox {
								margin-right: 16rpx;
								color: $uni-text-color-disable;
							}

							&.is-active {
								color: $uni-color-primary;
							}


						}

						.next-btn {
							margin-left: 32rpx;
						}
					}

					&.is-active {
						border: 1px solid $uni-color-primary;
						box-sizing: border-box;
					}



				}
			}

			::v-deep .scroll-view {
				height: calc(100%);
			}
		}

		.pub-button {
			margin-left: 32rpx;
			margin-right: 32rpx;
		}
	}
</style>