<template>
	<view class="page">
		<ul class="list">
			<uni-swipe-action>
				<uni-swipe-action-item
					v-for="(item, i) in list"
					:key="i"
					:threshold="0"
					:right-options="delOption"
					@click="del(item)"
				>
					<li>
						<uni-data-checkbox v-if="item.check" class="check" multiple :value="[1]" :localdata="item.checkData" @change="e => checkChange(e, i)"></uni-data-checkbox>
						<uni-data-checkbox v-else class="check" multiple v-model="item.check" :localdata="item.checkData" @change="e => checkChange(e, i)"></uni-data-checkbox>
						<image class="icon" :src="$util.getIcon(item)"></image>
						<view class="texts">
							<view class="name">{{ item.productName }}</view>
							<view class="price">市场建议价：{{ item.marketUnitPrice }}元/年</view>
						</view>
					</li>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</ul>
		<uni-load-more :status="status" />
		
		<view class="btn-wrap">
			<uni-data-checkbox class="check" multiple v-model="checkAll" :localdata="checkAllData" @change="allChange"></uni-data-checkbox>
			<view class="btns">
				<view class="btn del" @click="batchDel">删除</view>
				<view class="btn" @click="submit">生成订单</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { shoppingCartList, delCart, detailsOfGoods } from '@/apis/modules/product.js'
	export default {
		data() {
			return {
				reachBottom: 0, // 是否是上拉加载。0->否,1->是,-1->加载完所有数据
				status: 'more', // 上拉加载状态 more|loading|noMore
				searchTimer: null,
				list: [],
				page: 1,
				pageSize: 10,
				check: [1],
				noCheck: [],
				checkData: [{
					text: '',
					value: 1
				}],
				checkAll: [],
				checkAllData: [{
					text: '全部',
					value: 1
				}],
				checked: [], // 已经勾选的集合
				delOption: [{
					text: '删除',
					style: {
						backgroundColor: '#F56C6C'
					}
				}],
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.initList()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1500)
		},
		// 上拉加载
		onReachBottom() {
			if (this.reachBottom >= 0) {
				this.reachBottom = 1
				this.status = 'loading'
				this.getList()
			}
		},
		onShow() {
			this.checked = []
			// 清除产品缓存
			try {
				uni.removeStorageSync('orderForm')
				uni.removeStorageSync('courses')
				uni.removeStorageSync('orderEdited')
			} catch (e) {}
			this.initList()
		},
		methods: {
			// 购物车列表
			getList() {
				uni.showLoading({
					title: '加载中'
				})
				shoppingCartList({
					pageNum: this.page,
					pageSize: this.pageSize,
				}).then(({ data }) => {
					const { records } = data
					const all = this.checkAll.length // 是否勾选了全选
					const pageChange = this.reachBottom > 0 // 是否是翻页
					// 添加选择框字段
					records.forEach(e => {
						e.check = 0
						e.checkData = [{
							text: '',
							value: 1
						}]
					})
					
					// 未加载完所有数据，并且不是筛选，则拼接list，否则直接赋值
					this.list = pageChange ? [...this.list, ...records] : records
					this.page++ // 每次获取了数据后page+1
					const noMore = this.list.length === data.total // 是否加载完所有数据
					this.status = noMore ? 'noMore' : 'more' // 加载完了则设置为noMore
					this.reachBottom = noMore ? -1 : 0 // 加载完了则设置为-1
					uni.hideLoading()
				}).catch(e => {
					uni.hideLoading()
				})
			},
			initList() {
				this.page = 1
				this.reachBottom = 0
				this.getList()
			},
			// 选择框回调
			checkChange(e, i) {
				const { checked } = this
				const item = this.list[i]
				const { id } = item
				const include = checked.findIndex(e => e.id === id)
				// 选中的情况下，该产品如果没有push到已选数组里，则push
				if (e.detail.value.length) {
					include === -1 && checked.push(item)
				} else {
					// 取消选中的情况下，如果已选数组里存在该产品，则移除
					if (include !== -1) {
						checked.splice(include, 1)
						this.checkAll = []
					}
				}
				console.log(11, checked)
			},
			// 全选
			allChange(e) {
				const isCheck = !!e.detail.value.length // 是否选中
				const { list } = this
				this.checked = isCheck ? JSON.parse(JSON.stringify(list)) : []
				list.forEach(e => {
					e.check = isCheck ? 1 : 0
				})
			},
			// 生成产品参数
			createParam(e, authority, shopCartId) {
				const { orderType } = this
				const { mall, typeIds } = e
				const trial = orderType == 2 // 是否是试用
				return {
					dataOrCourseId: mall.associatedProduct, // id
					mallId: mall.mallId,
					productName: mall.productName, // 名称
					periodOfUse: '', // 使用期限
					startTime: this.$util.formatDate(new Date(), 'yyyy-MM-dd'), // 开始
					endTime: '', // 终止
					remainingPeriod: '', // 剩余期限
					marketValue: '', // 市场价
					marketPrice: mall.marketUnitPrice, // 市场单价
					finalPrice: 0, // 成交价
					finalValue: 0, // 成交单价（数据产品特有）
					discountRate: '0%', // 折扣率
					accountNum: 1, // 账号数
					totalAmount: '', // 总价
					isEnable: 0, // 启用否：1启用，0禁用
					ship: 0, // 发货否（0未发货，1已发货，默认不发货）
					authority, // 区分权限 0为数据平台权限，1为课程权限
					options: 2,
					miniProgramPictureAddress: mall.appletIcon || '', // 图标
					settlementPrice: trial ? 0 : '', // 结算价
					settlementPriceUnit: 0, // 结算单价
					serviceFee: 0, // 平台服务费（前端计算后展示，不入库）
					shopCartId, // 购物车id，订单提交后，调删除购物车的接口把这个产品删除
					typeId: typeIds && typeIds.length ? typeIds[0] : '',
				}
			},
			// 删除
			del(e) {
				const that = this
				uni.showModal({
					title: '提示',
					content: '确定要删除吗？',
					success(res) {
						if (res.confirm) {
							delCart([e.id]).then(res => {
								that.initList()
							}).catch(e => {})
						}
					}
				})
			},
			// 批量删除
			batchDel() {
				const list = this.checked // 已选产品
				if (list.length) {
					const that = this
					uni.showModal({
						title: '提示',
						content: '确定要删除吗？',
						success(res) {
							if (res.confirm) {
								delCart(list.map(e => e.id)).then(res => {
									that.checkAll = []
									that.checked = []
									that.initList()
								}).catch(e => {})
							}
						}
					})
				} else {
					this.$util.errMsg('请选择产品！')
				}
			},
			// 确定
			submit() {
				const list = this.checked // 已选产品
				if (list.length) {
					// 判断勾选的产品是否有重复的
					if (new Set(list.map(e => e.mallId)).size !== list.length) return this.$util.errMsg('所选产品存在重复，请重新选择')
					
					const promises = []
					let courses = []
					list.forEach(e => {
						promises.push(new Promise(async (resolve, reject) => {
							// 查询产品详情
							const res = await detailsOfGoods(e.mallId)
							const n = res.orderDetails
							courses.push(this.createParam(n, this.$util.getOrderType(n.classificationIds[0]), e.id))
							resolve()
						}))
					})
					Promise.all(promises).then(_ => {
						uni.setStorageSync('courses', courses)
						this.$util.to(`../orderDetail/orderDetail?shopCart=1`)
					})
				} else {
					this.$util.errMsg('请先添加产品！')
				}
			}
		}
	}
</script>

<style scoped lang="scss">
.page {
	padding-bottom: 130rpx;
}
.list {
	li {
		display: flex;
		align-items: center;
		width: 100%;
		padding: 30rpx 24rpx;
		margin: 16rpx 24rpx;
		background-color: #fff;
		border-radius: 16rpx;
		box-sizing: border-box;
	}
	.name {
		margin-bottom: 10rpx;
		font-size: 30rpx;
		color: #333;
	}
	.price {
		font-size: 26rpx;
		color: #333;
	}
	.icon {
		width: 100rpx;
		min-width: 100rpx;
		height: 100rpx;
		margin: 0 20rpx;
		border-radius: 4px;
	}
}
/deep/.check {
	.checklist-box {
		margin: 0 !important;
	}
	.checkbox__inner {
		width: 40rpx !important;
		height: 40rpx !important;
		border-radius: 50% !important;
	}
	.checkbox__inner-icon {
		top: 8rpx !important;
		left: 14rpx !important;
	}
}
.btn-wrap {
	position: fixed;
	justify-content: space-between;
	.btns {
		display: inline-flex;
	}
	.btn {
		width: auto;
		padding: 0 50rpx;
	}
	.del {
		margin-right: 20rpx;
		background-color: #b5b5b5;
	}
}
</style>
