<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { getFavoriteListApi, postCancelFavoriteApi } from '@/api/favorite'
import { fullUrl, computeConversion } from '@/utils/common'
import type { favoriteItem } from '@/types/favorite'
import { onShow } from '@dcloudio/uni-app'
import { safeBottom, pageUrl } from '@/utils/constants'

// eslint-disable-next-line no-undef
const paging = ref<ZPagingInstance>()
const dataList = ref<favoriteItem[]>([])
const queryList = (page: number, page_size: number) => {
  getFavoriteListApi({ page, page_size }).then((res) => {
    paging.value?.complete(res.result.data)
  })
}

const onCancelFavorite = async (id: string | number, is_all: boolean = false) => {
  uni.showModal({
    title: '提示',
    content: '确定取消收藏吗？',
    success: (res) => {
      if (res.confirm) {
        postCancelFavoriteApi({ goods_id: id, is_all }).then(() => {
          paging.value?.refresh()
          setTimeout(() => {
            uni.showToast({
              title: '取消收藏成功',
              icon: 'none',
            })
          }, 500)
        })
      }
    },
  })
}

//全选状态
const isCheckdedAll = ref(false)
//底部按钮禁用状态
const isDisabledCancelChecked = computed(() => !dataList.value.some((item) => item.checked))

const onChecked = (index: number) => {
  const item = dataList.value[index]
  item.checked = !item.checked
}

const onCheckedAll = () => {
  const checkded = isCheckdedAll.value
  dataList.value = dataList.value.map((item) => ({ ...item, checked: !checkded }))
}

const onCancelAllFavorite = () => {
  const checkdedIds = dataList.value
    .filter((item) => item.checked)
    .map((item) => item.goods_id)
    .join(',')

  if (!checkdedIds) {
    return uni.showToast({
      title: '请先选择商品',
      icon: 'none',
    })
  }

  onCancelFavorite(checkdedIds, isCheckdedAll.value)
}

// 监听 dataList 的变化，更新全选状态
watch(
  dataList,
  (newList) => {
    if (newList.length > 0) {
      isCheckdedAll.value = newList.every((item) => item.checked)
    } else {
      isCheckdedAll.value = false
    }
  },
  { deep: true },
)

// 计算收藏后降价金额
const getPriceDiff = (item: favoriteItem) => {
  const oldPrice = Number(item.old_price)
  const minPrice = Number(item.min_price)
  return oldPrice - minPrice
}

onShow(() => {
  paging.value?.refresh()
})
</script>

<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    @query="queryList"
    :use-page-scroll="true"
    empty-view-text="暂无收藏，快去逛逛看吧"
    :safe-area-inset-bottom="true"
    :paging-style="{
      backgroundColor: '#f7f7f8',
    }"
  >
    <view class="panel">
      <uni-swipe-action class="section">
        <uni-swipe-action-item v-for="(item, index) in dataList" :key="index">
          <view class="swipe-item">
            <view class="goods-item">
              <view class="checkbox" :class="{ checked: item.checked }" @tap="onChecked(index)" />
              <navigator
                class="goods"
                hover-class="none"
                :url="`${pageUrl['goods-detail']}?id=${item.goods_id}`"
              >
                <image class="image" :src="fullUrl(item.images[0])" />
                <view class="info">
                  <view class="name ellipsis">{{ item.name }}</view>
                  <view class="price-container">
                    <view class="price">
                      <view class="now">
                        <text class="symbol">¥</text>
                        <text class="number">{{ item.min_price }}</text>
                      </view>
                      <view class="price-diff" v-if="item.old_price && getPriceDiff(item) > 0">
                        <text>收藏后降</text>
                        <text class="diff-amount"> ￥{{ getPriceDiff(item).toFixed(2) }} </text>
                      </view>
                    </view>
                    <text class="collect-count">
                      {{ computeConversion(item.collect_count) }}人收藏
                    </text>
                  </view>
                </view>
              </navigator>
            </view>
          </view>
          <template #right>
            <view class="favorite-swipe-right">
              <button class="button delete-button" @tap="onCancelFavorite(item.goods_id)">
                取消收藏
              </button>
            </view>
          </template>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    <template #bottom>
      <view class="toolbar" :style="safeBottom">
        <text class="all" :class="{ checked: isCheckdedAll }" @tap="onCheckedAll">全选</text>
        <view class="button-grounp">
          <view
            class="button sub-button"
            :class="{ disabled: isDisabledCancelChecked }"
            @tap="onCancelAllFavorite"
          >
            取消收藏
          </view>
        </view>
      </view>
    </template>
  </z-paging>
</template>

<style scoped lang="scss">
.panel {
  margin: 20rpx 20rpx;
}
.goods-item {
  padding: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #ededed;
}

.goods {
  width: 100%;
  display: flex;
  margin-left: 50rpx;
}
.image {
  width: 150rpx;
  height: 150rpx;
  margin-right: 10rpx;
}
.info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 65%;
  margin-left: 5rpx;
}
.name {
  font-size: 24rpx;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-container {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  flex-grow: 1;
}

.price {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: 10rpx;
  .origin {
    font-size: 22rpx;
    margin-right: 10rpx;
    text-decoration: line-through;
  }
  .now {
    color: red;
  }
  .symbol {
    font-size: 18rpx;
  }

  .price-diff {
    line-height: 2;
    color: orange;
    font-size: 24rpx;
  }
}

.collect-count {
  color: #a09c9c;
  font-size: 24rpx;
}

.checkbox {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 70rpx;
  height: 100%;

  &::before {
    content: '\e6cd';
    font-family: 'iconfont' !important;
    font-size: 40rpx;
  }

  &.checked::before {
    content: '\e6cc';
    color: #ff5f3c;
  }
}

.favorite-swipe-right {
  display: flex;
  height: 100%;
  border-radius: 0 20rpx 20rpx 0;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    padding: 6px;
    line-height: 1.5;
    color: #fff;
    font-size: 26rpx;
    border-radius: 0 20rpx 20rpx 0;
    border: none;
  }

  .delete-button {
    background-color: #cf4444;
  }
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 100;

  height: 100rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .all {
    margin-left: 15rpx;
    font-size: 15px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'iconfont' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6cc';
    color: #ff5f3c;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 12rpx;
    color: #444;
    font-size: 14px;
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .sub-button {
      background-color: #ff5f3c;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
