<template>
	<div class="main">
		<div class="cart-main">
			<div class="cart-top">
				<div class="cart-num">
					图书数量<span>({{ totalLength }})</span>
				</div>
				<span @click="cartDelt">{{
					!isDeltHandle ? '管理' : '完成'
				}}</span>
			</div>
			<div class="cart-list">
        <div  v-for="(bookItem, index) in list" :key="index" >
          <div class="cart-item" v-if="bookItem.length !== 0">
            <div class="list-top">
              <van-checkbox v-model="bookItem.activeSelect" @change="handleselectedAll(index)"></van-checkbox>
              <div class="top-info" @click="toActive(bookItem[0].selectId)">
                <p class="active-name">
                  {{ bookItem[0] && bookItem[0].selectName  }}<i></i>
                </p>
                <p class="dealer">{{ bookItem[0] && bookItem[0].supplierName}}</p>
              </div>
            </div>
            <div class="product-list"  v-for="(item, i) in bookItem" :key="item.id">
              <div class="product-item">
              <!-- @change="handleSingle(index)" -->
                <van-checkbox v-model="item.checked"></van-checkbox>
                <div
                  class="product-cont"
                  @click="getOnlineBookDetail(item.bookId)"
                >
                  <div class="product-img">
                    <img
                      :src="
                        'http://192.168.99.67:8080/demoOnlineSelect/getBookCover.do?id=' +
                        item.bookId
                      "
                      alt=""
                    />
                  </div>
                  <div class="product-txt">
                    <div class="product-info">
                      <h4 class="overflow-txt-only">
                        {{ item.bookName }}
                      </h4>
                      <div class="author-date">
                        <p class="author overflow-txt-only">
                          {{ item.author }}
                        </p>
                        <p class="date overflow-txt-only">
                          {{ item.createdDate }}
                        </p>
                      </div>
                      <div class="intro overflow-txt">
                        {{ item.introduce }}
                      </div>
                    </div>
                    <div class="product-bottom">
                      <p class="product-price">
                        实付款
                        <span><i class="rmb">￥</i>0</span
                        ><i><em>￥</em>{{ item.price }}</i>
                      </p>
                      <span
                        v-if="!isDeltHandle"
                        class="product-num"
                        >x1</span
                      >
                      <span
                        v-else
                        class="item-delt"
                        @click.stop="
                          deltCurrentItem(item.id)
                        "
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
				<div class="empty-data" v-if="list.length === 0">
					<img src="@assets/images/empty.png" alt="" />
				</div>
			</div>
		</div>

		<div class="cart-pay" v-if="list.length !== 0">
			<van-checkbox v-model="allSelected">全选</van-checkbox>
			<div v-if="!isDeltHandle" class="payment-right">
				<div class="total-num">
					合计:<span><i class="rmb">￥</i>0</span>
				</div>
				<p class="pay-btn" @click="goPay">下单</p>
			</div>
			<div v-else class="payment-right">
				<p class="delt-btn" @click="confirmDelt">删除</p>
			</div>
		</div>

		<TabBar :tabCur.sync="tabCur" />

		<van-dialog v-model:show="showDetial" :show-confirm-button="false">
			<div class="bookItem-dialog-detail">
				<div class="list-top">
					<div class="top-info" @click="toActive(detailBook.listId)">
						<p class="active-name">{{ detailBook.listName }}<i></i></p>
					</div>
				</div>
				<div class="product-cont">
					<div class="product-cont-left">
						<div class="product-img">
							<img
								:src="
									$coverUrl+'/demoOnlineSelect/getBookCover.do?id=' +
									detailBook.id
								"
								alt=""
							/>
						</div>
						<div class="book-inventory">
							<p>剩余库存</p>
							<span
								><i>{{
									parseInt(detailBook.total) -
									parseInt(detailBook.purchase)
								}}</i
								>册</span
							>
						</div>
					</div>
					<div class="product-txt">
						<div class="product-info">
							<h4>{{ detailBook.bookName }}</h4>
							<div class="bookItem-txt">
								<span>著者：</span>
								<p class="author">{{ detailBook.author }}</p>
							</div>
							<div class="bookItem-txt">
								<span>出版社：</span>
								<p>{{ detailBook.publish }}</p>
							</div>
							<div class="bookItem-txt">
								<span>出版时间：</span>
								<p>{{ detailBook.createdDate }}</p>
							</div>
							<div class="bookItem-txt">
								<span class="txt-title">简介：</span>
								<p class="intro-txt">
									{{
										detailBook.introduce !== ''
											? detailBook.introduce
											: '暂无简介'
									}}
								</p>
							</div>
						</div>
					</div>
				</div>
				<div class="order-dealer">
					<p class="dealer">{{ detailBook.supplierName }}</p>
					<div class="order-pay">
						<p>
							实付款<span><i>￥</i>0</span>
						</p>
						<span class="yj-price"
							><i>￥</i><em>{{ detailBook.price }}</em></span
						>
					</div>
				</div>
			</div>
			<div class="dialog-btn">
				<span @click="showDetial = false">关闭</span>
			</div>
		</van-dialog>
	</div>
</template>

<script>
import { Toast } from 'vant'
import { reactive, computed, watch, onMounted, getCurrentInstance, toRefs } from 'vue'
import TabBar from '@/components/tabBar/index.vue'

export default {
	name: 'Cart',
	components: { TabBar },
	setup() {
		const { proxy } = getCurrentInstance()
		let data = reactive({
			tabCur: 1,
			allSelected: false,
			isDeltHandle: false,
			showDetial: false,
			list: [],
      totalLength: 0,
			checkedCount: [],
			detailBook: null,
      checkedBooks:[],
      checkedBooksPay:[]
		})
    watch(data.list, () => {
      data.allSelected = allSelected;
    }, { deep: true });

		onMounted(() => {
			getMyshoppingCart()
		})

    const allSelected = computed({
      get() {
        return data.list.every(bookItem => {
          return bookItem.every(item => item.checked);
        });
      },
      set(checked) {
        data.list.forEach(bookItem => {
          bookItem.forEach(item => {
            item.checked = checked;
          });
        });
      }
    })
        
    let toActive = (id) =>{
      proxy.$router.push({
        path: '/BookList',
        query: {
          activeId: id
        }
      })
    }

		let getMyshoppingCart = () => {
			let param = {}
			proxy.$http
				.get(proxy.$API.MYSHOPPINGCART, {
					params: param,
				})
				.then((res) => {
          if(res.data.length === 0){
            data.list = []
            data.totalLength = 0
          }else{
            let allArraysEmpty = true;
            for (let i = 0; i < res.data.length; i++) {
              if (res.data[i].length !== 0) {  // 如果当前子数组不为空
                allArraysEmpty = false;   // 设置所有子数组都不为空的标记为 false
                break;
              }
            }
            if (allArraysEmpty) {
              data.list = []
              data.totalLength = 0
            } else {
              data.list = res.data
              data.list.forEach(bookItem => {
                watch(bookItem, () => {
                  bookItem.activeSelect = bookItem.every(item => item.checked);
                }, { deep: true });
              })
              data.totalLength = data.list.map(books => books.length).reduce((total, length) => total + length, 0);
            }
          }
				})
				.catch((res) => {
					console.log(res)
				})
		}

		let getOnlineBookDetail = (bookId) => {
			proxy.$http
				.post(
					proxy.$API.BOOKONLINEDETAIL,
					{
						bookId: bookId,
					},
					{
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded',
						},
					}
				)
				.then((res) => {
					data.detailBook = res.data.book
					data.showDetial = true
				})
				.catch((res) => {
					console.log(res)
				})
		}

		let deltBookShoppingCart = (ids) => {
			let param = {
				ids: ids,
			}
			proxy.$http
				.put(
					proxy.$API.DELETBOOKTOSHOPPINGCART,
					param,
					{
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
					}
				)
				.then((res) => {
          getMyshoppingCart()
          Toast("删除成功")
        })
				.catch((res) => {
					console.log(res)
				})
		}

    let confirmDelt = () => {
      data.checkedBooks = data.list
                          .flat()
                          .filter(item => item.checked === true)
                          .map(item => item.id);

      if(data.checkedBooks.length === 0){
        Toast('请选择你需要删除的书籍')
      }else{
        const ids = data.checkedBooks.join(',')
        console.log(ids)
        deltBookShoppingCart(ids)
      }
		}

		let cartDelt = () => {
			data.isDeltHandle = !data.isDeltHandle
		}

		let deltCurrentItem = (bookId) => {
      deltBookShoppingCart(bookId)
		}

		// 商品单选
		let handleSingle = (index) => {
		}

		// 全选
		let handleselectedAll = (index) => {
      data.list[index].forEach(item=>{
        item.checked = data.list[index].activeSelect
      })
		}

    let goPay = () => {
      data.checkedBooksPay = data.list
                          .flat()
                          .filter(item => item.checked === true)
                          .map(item => item);
      console.log(data.checkedBooksPay)
      if(data.checkedBooksPay.length === 0){
        Toast('请选择需要下单的书籍')
      }else{
        if(data.checkedBooksPay.length > 3){
          Toast('当前活动限选三本图书')
        }else{
          getMyAddress()
        }
      }
		}

		let addPlaceOrder = (param) => {
			proxy.$http
				.put(
					proxy.$API.PLACEORDER,
					param,
					{
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded',
						},
					}
				)
				.then((res) => {
          if(res.errCode === 0){
            proxy.$router.push({ path: '/CartResult' })
          }
        })
				.catch((res) => {
					console.log(res)
				})
		}

    let getMyAddress = () => {
			let param = {
        openid: 'ocHu-sysUQ6-xb9knAJ5mATqCOJE'
      }
			proxy.$http
				.get(proxy.$API.MYADDRESS, {
					params: param,
				})
				.then((res) => {
            if(res.data.myAddress.length !== 0){
              const defaultAddress = res.data.myAddress.find(function(address) {
                return address.isDefault === 1;
              });
              data.list.forEach((group) => {
                const checked_books = [];
                group.forEach((item) => {
                    if (item.checked) {
                      checked_books.push(item.bookId);
                    }
                });
                var book_ids = checked_books.join(',');
                let param = {
                  addressId: defaultAddress.id,
                  bookIds: book_ids
                }
                addPlaceOrder(param)
              })
            }else{
              Toast('请先添加收货地址后再下单')
            }
				})
				.catch((res) => {
					console.log(res)
				})
		}

		return {
			...toRefs(data),
      toActive,
			goPay,
			cartDelt,
			deltCurrentItem,
			handleselectedAll,
			handleSingle,
			confirmDelt,
			getMyshoppingCart,
			getOnlineBookDetail,
			deltBookShoppingCart,
			addPlaceOrder,
      allSelected,
      getMyAddress
		}
	},
}
</script>

<style scoped lang="scss">
.cart-main {
	padding: 0 0.16rem 2.2rem 0.16rem;
	color: #191a1a;
	.cart-top {
		position: fixed;
		top: 0;
		right: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 0.32rem;
		height: 1rem;
		padding: 0 0.32rem;
		background-color: #fff;
		box-shadow: 0 0.06rem 0.1rem 1px #efecec;
		z-index: 999;
		.cart-num {
			font-size: 0.32rem;
			opacity: 0.6;
			span {
				font-size: 0.3rem;
			}
		}
	}
}
.cart-list {
	padding-top: 1.2rem;
}
.cart-item {
	padding: 0.24rem;
	margin-bottom: 0.2rem;
	box-shadow: 0px 0.03rem 0.6rem 1px rgba(0, 0, 0, 0.08);
	border-radius: 0.1rem;
	background-color: #fff;
}

.product-list {
	.product-item {
		display: flex;
		justify-content: flex-start;
		margin-top: 0.3rem;
	}
}

.cart-pay {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0.98rem;
	padding: 0 0.32rem;
	height: 1rem;
	background: linear-gradient(#fff, #f1f1f1);
	display: flex;
	justify-content: space-between;
	align-items: center;
	.payment-right {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 0.28rem;
		.total-num {
			font-size: 0.28rem;
			span {
				font-size: 0.4rem;
				font-weight: bold;
				color: #ff3871;
				.rmb {
					font-style: normal;
					font-size: 0.28rem;
					text-decoration: none;
				}
			}
		}
		.pay-btn {
			width: 1.5rem;
			height: 0.6rem;
			margin-left: 0.4rem;
			line-height: 0.6rem;
			text-align: center;
			color: #fff;
			background: url('@assets/images/btn3.png') no-repeat center center;
			background-size: 100% 100%;
		}
		.delt-btn {
			width: 1.5rem;
			height: 0.6rem;
			line-height: 0.6rem;
			font-size: 0.28rem;
			color: #000;
			text-align: center;
			border: 0.02rem solid #000;
			opacity: 0.6;
			border-radius: 0.4rem;
		}
	}
}

.van-checkbox {
	margin-right: 0.2rem;
}

:deep(.van-checkbox__icon) {
	height: 0.35rem;
}
:deep(.van-checkbox__icon .van-icon) {
	width: 0.35rem;
	height: 0.35rem;
	border-color: rgba(0, 0, 0, 0.3);
}
:deep(.van-checkbox__icon--checked .van-icon) {
	border: none;
	background: url('@assets/images/selected.png') no-repeat transparent;
	background-size: 0.35rem 0.35rem;
}
:deep(.van-icon-success:before) {
	display: none;
}
:deep(.van-checkbox__label) {
	font-size: 0.28rem;
}

.bookItem-dialog-detail {
	border-bottom: none;
}
</style>
