<template>
  <view>
    <!-- <view class="hdbj"></view> -->
    <view class="collectionGoods" v-if="collectProductList.length">
      <view class="nav acea-row row-between-wrapper">
        <view
          >当前共 <text class="num">{{ totals }}</text
          >件商品</view
        >
        <view class="administrate acea-row row-center-wrapper" @click="manage"
          >{{ footerswitch ? "管理" : "取消" }}
        </view>
      </view>
      <view class="list">
        <up-checkbox-group
          shape="circle"
          v-model="selectValue"
          @change="checkboxChange"
          class="centent"
          activeColor="#F8C008"
        >
          <view
            v-for="(item, index) in collectProductList"
            :key="item.id"
            class="item acea-row row-middle"
            style="width: 100%"
          >
            <up-checkbox
              :name="item.id.toString()"
              :checked="item.checked"
              v-if="!footerswitch"
              style="margin-right: 10rpx"
              activeColor="#F8C008"
            />
            <view
              class="acea-row"
              style="align-items: center"
              @click="goDetail(item)"
            >
              <view class="pictrue">
                <image :src="item.image" mode="aspectFill"></image>
              </view>
              <view class="desc">
                <view class="name">{{ item.storeName }}</view>
                <view class="money"
                  >￥<view class="price">
                    {{ calcPrice(item) }} </view
                  ><view class="qi"> 起 </view>
                </view>
              </view>
            </view>
          </view>
        </up-checkbox-group>
      </view>
      <view class="loadingicon acea-row row-center-wrapper">
        <text
          class="loading iconfont icon-jiazai"
          :hidden="loading == false"
        ></text
        >{{ loadTitle }}
      </view>
      <view v-if="!footerswitch" class="footer acea-row row-between-wrapper">
        <view>
          <up-checkbox-group shape="circle" @change="checkboxAllChange">
            <up-checkbox
              value="all"
              :checked="!!isAllSelect"
              activeColor="#F8C008"
            />
            <text class="checkAll" @click="toggleSelectAll">全选</text>
          </up-checkbox-group>
        </view>
        <view class="button acea-row row-middle">
          <form @submit="delCollectionAll" report-submit="true">
            <button class="bnt" formType="submit">取消收藏</button>
          </form>
        </view>
      </view>
    </view>
    <view
      class="noCommodity"
      v-else-if="!collectProductList.length && page > 1"
    >
      <view class="pictrue">
        <image :src="HTTP_REQUEST_URL_IMG + 'noCollection.png'"></image>
      </view>
      <!--      <recommend :hostProduct="hostProduct"></recommend>-->
    </view>

    <!--    <home></home>-->
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onActivated } from "vue";
import { onLoad, onShow, onReachBottom } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import { useAppStore } from "@/stores/app.js";
import { HTTP_REQUEST_URL_IMG } from "@/config/app";
import {
  getCollectUserList,
  getProductHot,
  collectDelete,
} from "@/api/store.js";
import { toLogin } from "@/libs/login.js";
import recommend from "@/components/recommend";
// 获取实物金价
import useRealGoldPrice from "@/hooks/useRealGoldPrice";
const {
  realGoldprice, // 黄金实时销售价（基础）
  realPtprice, // 铂金实时销售价（基础）
  realAgprice, // 白银实时销售价（基础）
} = useRealGoldPrice({});
import home from "@/components/home";
import Util from "@/utils/util";

// Store
const appStore = useAppStore();
const isLogin = appStore.isLogin;

// 响应式数据
const footerswitch = ref(true);
const hostProduct = ref([]);
const loadTitle = ref("加载更多");
const loading = ref(false);
const loadend = ref(false);
const collectProductList = ref([]);
const limit = 8;
const page = ref(1);
const isAuto = ref(false);
const isShowAuth = ref(false);
const hotScroll = ref(false);
const hotPage = ref(1);
const hotLimit = 10;
const isAllSelect = ref(false);
const selectValue = ref([]);
const delBtnWidth = 80;
const totals = ref(0);
const startX = ref(0);

const goDetail = (item) => {
  if (!footerswitch.value) {
    let id = String(item.id);
    if (selectValue.value.includes(id)) {
      collectProductList.value.forEach((item) => {
        if (item.id == id) {
          item.checked = false;
        }
      });
      selectValue.value = selectValue.value.filter((n) => n != id);
    } else {
      selectValue.value.push(id);
    }
    isAllSelect.value =
      collectProductList.value.length === selectValue.value.length;
    return;
  }
  uni.navigateTo({
    url: "/pages/goods/goods_details/index?id=" + item.productId,
  });
};

const calcPrice = (product) => {
  const price = Number(product.price);
  // 2. 计算乘积
  const total = (price + product.sales) * realGoldprice.value;
  // 3. 向上取整到两位小数（先放大100倍取整，再缩小100倍）
  const roundedTotal = Math.ceil(total * 100) / 100;
  // 4. 格式化保留两位小数
  const formattedTotal = roundedTotal.toFixed(2);

  const totalLaborCost = Number(product.totalLaborCost);
  const additionalAmount = Number(product.additionalAmount);
  const totalPrice = (totalLaborCost + additionalAmount).toFixed(2);

  return totalPrice;
};

// 管理切换
const manage = () => {
  footerswitch.value = !footerswitch.value;
};

// 多选框变化
const checkboxChange = (event) => {
  console.log(event);
  const values = event;

  collectProductList.value.forEach((item) => {
    item.checked = values.includes(item.id.toString());
  });

  // selectValue.value = values.toString();
  isAllSelect.value = collectProductList.value.length === values.length;
};

// 全选变化
const checkboxAllChange = (event) => {
  if (event.length > 0) {
    setAllSelectValue(1);
  } else {
    setAllSelectValue(0);
  }
};

const toggleSelectAll = () => {
  if (isAllSelect.value) {
    setAllSelectValue(0);
  } else {
    setAllSelectValue(1);
  }
};

// 设置全选状态
const setAllSelectValue = (status) => {
  const selectValues = [];

  collectProductList.value.forEach((item) => {
    if (status) {
      item.checked = true;
      selectValues.push(String(item.id));
      isAllSelect.value = true;
    } else {
      item.checked = false;
      isAllSelect.value = false;
    }
  });
  console.log(selectValues);
  selectValue.value = selectValues;
};

// 授权回调
const onLoadFun = () => {
  get_user_collect_product();
  // get_host_product();
};

// 授权关闭
const authColse = (e) => {
  isShowAuth.value = e;
};

// 获取收藏产品
const get_user_collect_product = async () => {
  if (loading.value || loadend.value) return;

  loading.value = true;
  loadTitle.value = "";

  try {
    const res = await getCollectUserList({
      page: page.value,
      limit: limit,
    });

    res.data.list.forEach((item) => {
      item.right = 0;
    });

    totals.value = res.data.total;
    const collectProductListData = res.data.list;
    const isLoadend = collectProductListData.length < limit;

    // 重置逻辑优化
    if (page.value === 1) {
      // 第一页，清空原数组
      collectProductList.value = [...collectProductListData];
    } else {
      // 后续分页，追加数据
      collectProductList.value = [
        ...collectProductList.value,
        ...collectProductListData,
      ];
    }

    loadend.value = isLoadend;
    loadTitle.value = isLoadend ? "我是有底线的" : "加载更多";
    page.value++;
  } catch (err) {
    console.error(err);
    if (page.value === 1) {
      collectProductList.value = [];
    }
  } finally {
    loading.value = false;
  }
};

// 取消收藏多个
const delCollectionAll = () => {
  console.log(selectValue.value);
  if (!selectValue.value || selectValue.value.length === 0) {
    uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }

  del({
    ids: selectValue.value.toString(),
  }).then(() => {
    selectValue.value = [];
  });
};

// 删除操作
const del = async (data) => {
  try {
    await collectDelete(data);
    uni.showToast({
      title: "取消收藏成功",
      icon: "success",
    });

    collectProductList.value = [];
    loadend.value = false;
    page.value = 1;
    get_user_collect_product();
  } catch (err) {
    uni.showToast({
      title: err.message || "操作失败",
    });
  }
};

// 获取热门商品
const get_host_product = async () => {
  if (hotScroll.value) return;

  try {
    const res = await getProductHot(hotPage.value, hotLimit);
    hotPage.value++;
    hotScroll.value = res.data.list.length < hotLimit;
    hostProduct.value = hostProduct.value.concat(res.data.list);
  } catch (err) {
    console.error(err);
  }
};

// 页面加载
onLoad(() => {
  // if (isLogin) {
  //   loadend.value = false;
  //   page.value = 1;
  //   collectProductList.value = [];
  //   get_user_collect_product();
  // } else {
  //   // toLogin();
  // }
});

// 页面显示
onShow(() => {
  if (isLogin) {
    loadend.value = false;
    page.value = 1;
    collectProductList.value = [];
    get_user_collect_product();
  } else {
    // toLogin();
  }
});

// 页面上拉触底
onReachBottom(() => {
  get_user_collect_product();
  // get_host_product();
});
</script>

<style scoped lang="scss">
/* 样式部分保持不变 */
// .hdbj {
// 	width: 100%;
// 	height: 30rpx;
// 	background-color: #f5f5f5;
// 	z-index: 999999;
// 	position: fixed;
// 	top: 0;
// }
page {
  height: 100%;
  background-color: #f9f7f0;
}
.order-item {
  width: 100%;
  display: flex;
  position: relative;
  align-items: right;
  flex-direction: row;
}

.remove {
  width: 120rpx;
  height: 100%;
  background-color: $theme-color;
  color: white;
  position: absolute;
  top: 0;
  right: -160rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
}

.collectionGoods {
  padding-top: 80rpx;
  .nav {
    height: 80rpx;
    background-color: #f9f7f0;
    padding: 0 16rpx;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    font-size: 28rpx;
    color: #333;
    position: fixed;
    z-index: 5;
    left: 0;
    top: 0;
    right: 0;
    border-radius: 16rpx;

    .num {
      font-size: 32rpx;
      color: #f8c008;
      font-weight: bold;
    }
    .administrate {
      font-size: 28rpx;
      color: #f8c008;
      font-weight: bold;
    }
  }

  .list {
    padding: 16rpx;
    // margin-top: 110rpx;
    .desc {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      width: 434rpx;
      // flex: 1;
    }

    .name {
      width: 434rpx;
      margin-bottom: 32rpx;
    }
  }

  .centent {
    /* #ifdef H5 || MP */
    // background-color: #fff;
    /* #endif */
    border-bottom-left-radius: 14rpx;
    border-bottom-right-radius: 14rpx;
  }
}

.collectionGoods .item {
  background-color: #fff;
  // padding-left: 24rpx;
  // height: 180rpx;
  padding: 16rpx;
  margin-bottom: 20rpx;
  border-radius: 14rpx;
}

.collectionGoods .item .pictrue {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.collectionGoods .item .pictrue image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
}

.collectionGoods .item {
  width: 535rpx;
  // height: 130rpx;
  font-size: 32rpx;
  color: #333;
}

.collectionGoods .item .name {
  width: 100%;
  line-height: 48rpx;
  font-weight: bold;
}

.collectionGoods .item .money {
  display: flex;
  align-items: flex-end;
  font-size: 28rpx;
  color: #fd5f3c;

  .price {
    font-size: 36rpx;
    font-weight: bold;
    margin: 0 5rpx;
  }
  .qi {
    font-size: 20rpx;
  }
}

.collectionGoods .item .delete {
  font-size: 26rpx;
  color: #282828;
  width: 144rpx;
  height: 46rpx;
  border: 1px solid #bbb;
  border-radius: 4rpx;
  text-align: center;
  line-height: 46rpx;
}

.noCommodity {
  background-color: #fff;
  padding-top: 1rpx;
  padding-bottom: 30rpx;
  border-top: 0;
}

.footer {
  z-index: 9;
  width: 100%;
  height: 128rpx;
  background-color: #fff;
  position: fixed;
  padding: 0 30rpx;
  box-sizing: border-box;
  border-top: 1rpx solid #eee;
  border-bottom: 1px solid #eeeeee;
  /* #ifdef H5 || MP */
  bottom: 0rpx;
  padding-bottom: 32rpx;

  /* #endif */
  /* #ifndef MP */
  // bottom: 98rpx;
  // bottom: calc(98rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
  // bottom: calc(98rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
  /* #endif */
  .checkAll {
    font-size: 28rpx;
    color: #282828;
    margin-left: 16rpx;
    line-height: 56rpx;
  }

  .button .bnt {
    font-size: 28rpx;
    color: #333333;
    font-weight: bold;
    border-radius: 8rpx;
    background-color: #f8c008;
    width: 180rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    border: none;
  }
}
</style>