<template>
  <layout>
    <uv-navbar
        :fixed="false"
        title="我的收藏"
        left-arrow
        @leftClick="goBack"
    />

    <view class="top-option">
      <view />
      <view
          class="btn"
          @click="setManage(!showManage)"
      >
        {{ showManage ? '完成' : '管理' }}
      </view>
    </view>
    <container>
      <uv-swipe-action>
        <space
            direction="vertical"
            fill
        >
          <template v-if="dataList.length>0">
            <uv-checkbox-group
                v-model="selectValues"
                shape="circle"
                activeColor="#ec6e47"
            >
              <view
                  class="select-row"
                  v-for="(item) in dataList"
                  :key="item.id"
              >
                <uv-checkbox
                    v-if="showManage"
                    :customStyle="{marginBottom: '8px'}"
                    :name="item.id"
                />

                <card
                    style="width: 100%"
                    @click="handleRightSingleSelect(item)"
                >
                  <uv-swipe-action-item
                      :disabled="showManage"
                      :options="options"
                      @click="handleOpenDelete(true, item)"
                  >
                    <goods
                        list
                        :data="item"
                        :storeName="item.storeName"
                        :price="item.price"
                        :stock="item.stock"
                        interval="true"
                        desc="3"
                        showAction="true"
                        surplus="200"
                        priceMode="primary"
                        @click=" push({url: '/pages/goodsDetail/goodsDetail'}, {data: {id: item.productId}})"
                    >
                    </goods>
                  </uv-swipe-action-item>
                </card>
              </view>
            </uv-checkbox-group>
          </template>
          <Empty
              :iconSrc="emptyIcon"
              v-else
          >
            您还没有收藏的商品~
          </Empty>
        </space>
      </uv-swipe-action>
      <view class="option-height"></view>

      <!-- bar -->
      <view
          class="option-row"
          :style="{height:showManage?'100rpx':'0rpx'}"
      >
        <view class="left">
          <uv-checkbox-group
              v-model="isSelectAll"
              shape="circle"
              activeColor="#ec6e47"
              @change="handleClickSelectAll"
          >
            <uv-checkbox
                shape="circle"
                activeColor="#ec6e47"
                :name="1"
            >
              <span class="all-select">全选</span>
            </uv-checkbox>
          </uv-checkbox-group>
        </view>
        <view
            class="button"
            @click="handleOpenDelete(false)"
        >
          删除
        </view>
      </view>
    </container>
    <Modal
        ref="deleteModal"
        content="确认要删除所选内容吗？"
        @confirm="toDelete"
        @cancel="toCancelDelete"
    ></Modal>
  </layout>
</template>

<script setup>
import { computed, nextTick, ref, unref } from 'vue'
import { collectPage, unCollectByList, unCollectSingle } from '@/api/product'
import { onLoad } from '@dcloudio/uni-app'
import Modal from '@/components/Modal/index.vue'

import { usePage } from '@/hooks'
import Empty from "@/components/Empty/index.vue";
import emptyIcon from '@/static/icon/empty/收藏.png'
import { useRouter } from "@/hooks/useRouter";
import { useInterface } from "@/hooks/useInterface";

const {goBack, push} = useRouter()
const {type, refresh, dataList} = usePage(collectPage)

const {toast} = useInterface();


const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#f56c6c'
  }
}])

const showManage = ref(false) // 是否展示管理

/**
 * 设置是否展示
 * @param show
 */
function setManage(show = true) {
  selectValues.value = []
  showManage.value = show
}


const selectValues = ref([]) // 当前选中的value
// 是否全选，全选[1]非[]
const isSelectAll = computed({
  get: () => unref(selectValues).length === unref(dataList).length ? [1] : [],
  set: () => {
  }
})

/**
 * 处理点击右侧单个选择
 * @param item
 */
function handleRightSingleSelect(item) {
  if (!showManage.value) return
  nextTick(() => {
    const number = unref(selectValues).findIndex(e => e === item.id);
    if (number >= 0)
      unref(selectValues).splice(number, 1)
    else
      unref(selectValues).push(item.id)
  })
}

/**
 * 处理点击全选
 * @param e
 */
function handleClickSelectAll(e) {
  selectValues.value = e.includes(1) ? dataList.value.map(item => item.id) : []
}

// =========================== 👇 删除相关 👇========================================
const deleteModal = ref()
let toDeleteItem

/**
 * 打开删除对话框
 * @param single
 * @param item
 * @returns {*}
 */
function handleOpenDelete(single = false, item = undefined) {
  if (!single) {
    if (unref(selectValues).length <= 0) return toast({title: '请先选择商品'})
  } else {
    // 记录需要删除的
    toDeleteItem = item
  }
  unref(deleteModal).show()
}

/**
 * 确认删除
 */
function toDelete() {
  toDeleteItem ? handleUnCollectSingle() : handleUnCollectList()
}

/**
 * 取消删除
 */
function toCancelDelete() {
  toDeleteItem = undefined
}

async function handleUnCollectSingle() {
  await unCollectSingle(toDeleteItem)
  await refresh()
  await toast({title: '删除成功'})
  toDeleteItem = undefined
}

/**
 * 处理全部删除
 */
async function handleUnCollectList() {
  const delIds = []
  unref(dataList).forEach(data => {
    if (unref(selectValues).includes(data.id)) {
      delIds.push(data.productId)
    }
  })
  const data = {
    category: 'common',
    productIdList: delIds
  }
  await unCollectByList(data);
  await refresh()
  await toast({title: '删除成功'})
  selectValues.value = []
  toCancelDelete()
}

// =========================== 👆 删除相关 👆========================================
onLoad(async (option) => {
  type.value = 'collect'
  await refresh()
})


</script>

<style
    lang="scss"
    scoped
>
.select-row {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.top-option {
  width: 100%;
  height: 80rpx;
  background: #fff;
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 33rpx;
  box-sizing: border-box;
  margin-bottom: 15rpx;
}

.option-height {
  width: 100%;
  height: 120rpx;
}

.option-row {
  width: 100%;
  z-index: 99;
  height: 100rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  opacity: 1;
  overflow: hidden;
  transition: all .3s;

  .left {
    padding: 0 34rpx;
    font-size: 28rpx;
  }

  .button {
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 80rpx;
    background: #ee6d46;
    color: #fff;
    transition: all .3s;
    font-size: 34rpx;

    &:active {
      font-size: 28rpx;
    }
  }
}
</style>
