<template>
  <view>
    <view class='searchGood'>
      <view class='search acea-row row-between-wrapper'>
        <view class='input acea-row row-between-wrapper'>
          <text class='iconfont icon-sousuo'></text>
          <input type='text' confirm-type="search" :value='searchValue' :focus="focus" placeholder='点击搜索商品' placeholder-class='placeholder'
            @input="setValue" @confirm="searchBut" />
        </view>
        <view class='bnt' @tap='searchBut'>搜索</view>
      </view>
<!--      <view class='title'>热门搜索</view>-->
<!--      <view class='list acea-row'>-->
<!--        <block v-for="(item, index) in hotSearchList" :key="index">-->
<!--          <view class='item' @tap='setHotSearchValue(item.title)'>{{ item.title }}</view>-->
<!--        </block>-->
<!--      </view>-->
      <view class='line'></view>
      <goodList :bastList="calculatedProducts" v-if="bastList.length > 0"></goodList>
      <view class='loadingicon acea-row row-center-wrapper' v-if="bastList.length > 0">
        <text class='loading iconfont icon-jiazai' :hidden='loading == false'></text>{{ loadTitle }}
      </view>
    </view>
    <view class='noCommodity'>
      <view class='pictrue' v-if="bastList.length == 0 && isbastList">
        <image :src="HTTP_REQUEST_URL_IMG+'noSearch.png'"></image>
      </view>
<!--      <recommend :hostProduct='hostProduct' v-if="bastList.length == 0"></recommend>-->
    </view>
  </view>
</template>

<script setup>
import {computed, ref} from 'vue'
import { onShow, onReachBottom,onLoad } from '@dcloudio/uni-app'
import { getSearchKeyword, getProductslist, getProductHot } from '@/api/store.js'
import goodList from '@/components/goodList'
import recommend from '@/components/recommend'
import { HTTP_REQUEST_URL_IMG } from "@/config/app";
// 获取实时金价
import useRealGoldPrice from "@/hooks/useRealGoldPrice";
import { useAppStore } from "@/stores/app";

const appStore = useAppStore();

// 响应式数据
const hostProduct = ref([])
const searchValue = ref('')
const focus = ref(true)
const bastList = ref([])
const hotSearchList = ref([])
const limit = ref(8)
const page = ref(1)
const loading = ref(false)
const loadend = ref(false)
const loadTitle = ref('加载更多')
const hotPage = ref(1)
const isScroll = ref(true)
const isbastList = ref(false)
const query = ref({})
const merchantId =  ref('')
// 实时价格处理
const {
  realGoldprice, // 黄金实时销售价（基础）
  realPtprice, // 铂金实时销售价（基础）
  realAgprice, // 白银实时销售价（基础）
} = useRealGoldPrice({});

const calculatedProducts = computed(() => {
  // 计算逻辑与原代码一致，但基于响应式数据 products
  return bastList.value.map((product) => {
    // 1. 将price字符串转为数字
    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 {
      ...product,
      calculatedTotal: formattedTotal, // 新增计算结果字段
      totalPrice
    };
  });
});

// 获取热搜
function getRoutineHotSearch() {
  getSearchKeyword().then(res => {
    hotSearchList.value = res.data
  })
}

// 获取商品列表
function getProductList() {
  if (loadend.value || loading.value) return
  loading.value = true
  loadTitle.value = ''
  getProductslist({
    ...query.value,
    keyword: searchValue.value,
    page: page.value,
    limit: limit.value,
    merchantId:merchantId.value,
  }).then(res => {
    const list = res.data.list
    const isLoadend = list.length < limit.value
    // 合并数组
    bastList.value = (bastList.value || []).concat(list)
    loading.value = false
    loadend.value = isLoadend
    loadTitle.value = isLoadend ? "我是有底线的" : "加载更多"
    page.value += 1
    isbastList.value = true
  }).catch(() => {
    loading.value = false
    loadTitle.value = '加载更多'
  })
}

// 获取热门商品
function getHostProduct() {
  if (!isScroll.value) return
  getProductHot(hotPage.value, limit.value).then(res => {
    isScroll.value = res.data.list.length >= limit.value
    hostProduct.value = hostProduct.value.concat(res.data.list)
    hotPage.value += 1
  })
}

// 设置热搜值
function setHotSearchValue(val) {
  searchValue.value = val
  page.value = 1
  loadend.value = false
  bastList.value = []
  getProductList()
}

// 输入框赋值
function setValue(event) {
  searchValue.value = event.detail.value;
}

// 搜索按钮
function searchBut() {
  focus.value = false
  if (searchValue.value.length > 0) {
    page.value = 1
    loadend.value = false
    bastList.value = []
    uni.showLoading({ title: '正在搜索中' })
    getProductList()
    uni.hideLoading()
  } else {
    // 这里假设 $util.Tips 已全局挂载
    uni.$u.toast('请输入要搜索的商品')
  }
}

// 生命周期
onShow(() => {
  getRoutineHotSearch()
  getHostProduct();

})
onLoad((options)=>{
  query.value = options || {};
  merchantId.value =query.value.merchantId || appStore.merchantId||appStore.userInfo?.merchant?.id||'';
  if(options && options.cid){
    getProductList()
  }
})

onReachBottom(() => {
  if (bastList.value.length > 0) {
    getProductList()
  } else {
    getHostProduct()
  }
})
</script>

<style lang="scss">
page {
  margin-top: var(--status-bar-height);
  background-color: #fff !important;
}

.searchGood .search {
  padding-left: 30rpx;
  background-color: #fff !important;
}

.searchGood .search {
  padding-top: 20rpx;
}

.searchGood .search .input {
  width: 598rpx;
  background-color: #f7f7f7;
  border-radius: 16rpx;
  padding: 0 35rpx;
  box-sizing: border-box;
  height: 66rpx;
}

.searchGood .search .input input {
  width: 472rpx;
  font-size: 26rpx;
}

.searchGood .search .input .placeholder {
  color: #bbb;
}

.searchGood .search .input .iconfont {
  color: #000;
  font-size: 35rpx;
}

.searchGood .search .bnt {
  width: 120rpx;
  text-align: center;
  height: 66rpx;
  line-height: 66rpx;
  font-size: 30rpx;
  color: #282828;
}

.searchGood .title {
  font-size: 28rpx;
  color: #999;
  margin: 50rpx 30rpx 25rpx 30rpx;
}

.searchGood .list {
  padding-left: 10rpx;
}

.searchGood .list .item {
  font-size: 26rpx;
  color: #454545;
  padding: 0 21rpx;
  height: 60rpx;
  border-radius: 30rpx;
  line-height: 60rpx;
  border: 1rpx solid #aaa;
  margin: 0 0 20rpx 20rpx;
}

.searchGood .line {
  border-bottom: 1rpx solid #eee;
  margin: 20rpx 30rpx 0 30rpx;
}
</style>
