<template>
        <!--   @tap="getPhone" -->
      <view class="filter-root">
        <text class="btn" @tap="openPopup">更多条件</text>
        <uni-search-bar
          v-model="keyword"
          @confirm="searchStore(keyword)"
          @clear="clearIpt"
          cancelButton="none"
          clearButton="auto"
          @input="changeIpt(keyword)"
          :placeholder="'请输入搜索关键字'"
        />
      </view>
    <view v-if="historyList.length">
      <scroll-view
          scroll-y
            style="height: calc(100vh - 182rpx)"
            refresher-enabled
            :refresher-triggered="triggered"
            @scrolltolower="scrolltolower"
            class="list"
            @refresherrefresh="refresherrefresh">
                <view v-for="(item,index) in historyList" :key="index" class="list_item">
                <view class="desc">
                  <view>话题:{{ item.userDescription }}</view>
                  <view>创建时间:{{ item.createdAt }}</view>
                  <view>价格:
                    <text style="font-size: 36rpx;color: red;">¥{{ (item.payMoney / 100 ).toFixed(2) }}</text>
                    <text style="text-decoration: line-through;">¥{{ (item.jxPrice / 100).toFixed(2) }}</text>
                  </view>
                </view>
                <!-- / -->
                <image :src="item.vendorDescription" alt="加载中..."  class="img" @tap="previewImg(item.vendorDescription)" @error="handleImgError(index)"></image>
              </view>
              <jx-load-more
                v-show="totalCount >= 4"
                :isLoad="isLoad"
                :size="'30rpx'"
                tip="没有更多记录"
              />
          </scroll-view>

    </view>
    
    <jx-empty v-else title="没有历史话题"></jx-empty>
    <!-- <view v-if="historyList && historyList.length >0" class="list">
        历史话题
    
    </view> -->

<uni-popup ref="popup" type="top">
    <view class="switch-filter">
      <view class="condition">查询条件</view>
      <view class="item">
        <text class="title">查询时间：</text>
        <view class="root">
          <picker
            class="value"
            mode="date"
            :value="date1"
            start="2010-01-01"
            :end="endDate"
            @change="dateChange1"
            >{{ date1 }}</picker
          >
          <text>至</text>
          <picker
            class="value"
            mode="date"
            :value="date2"
            start="2010-01-01"
            :end="endDate"
            @change="dateChange2"
            >{{ date2 }}</picker
          >
        </view>
      </view>
       <view class="item">
        <text class="title">关键字段：</text>
        <picker
          class="value"
          mode="selector"
          :value="vendor"
          :range="vendorArr"
          range-key="name"
          @change="dateChange3"
          >{{ vendorArr[vendor].name }}</picker
        >
      </view>
      <view class="item">
        <text class="title">排序方式：</text>
        <picker
          class="value"
          mode="selector"
          :value="sortIndex"
          :range="sortArr"
          range-key="name"
          @change="dateChange4"
          >{{ sortArr[sortIndex].name }}</picker
        >
      </view>
      <!--<view class="item" v-if="orderState == 6">
        <text class="title">售后方式：</text>
        <picker
          class="value"
          mode="selector"
          :value="appealTypes1"
          :range="appealTypesArr"
          range-key="name"
          @change="dateChange5"
          >{{ appealTypesArr[appealTypes1].name }}</picker
        >
      </view>
      <view class="item" v-if="orderState == 6">
        <text class="title">售后状态：</text>
        <picker
          class="value"
          mode="selector"
          :value="afsStatus1"
          :range="afsStatusArr"
          range-key="name"
          @change="dateChange6"
          >{{ afsStatusArr[afsStatus1].name }}</picker
        >
      </view> -->
      <view class="btnRoot">
        <text class="cancel" @tap="popup.close()">取消</text>
        <text class="confirm" @tap="confirm">确定</text>
      </view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import order from '@/api/https/order';
import JxEmpty from '@/components/jx-empty/jx-empty.vue';
import useGlobalFunc from '@/composables/useGlobalFunc';
import { store } from '@/store';
import toast from '@/utils/toast';
import { jx_throttles, timeFormatD } from '@/utils/tools';
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';

const historyList = ref<AnyObject[]>([])
const {
  previewImage, // 预览图片
} = useGlobalFunc()

/*************************************************
 * 预览图片
 */
 function previewImg(url:string) {
  // let arr = [skuName.img,skuName.img2,skuName.img3,skuName.img4,skuName.img5].filter(item => { return item && item.length > 0 })
  if(url.length === 0) return toast('请选择正确的图片')
  previewImage(url)
}

/**
 * 加载图片信息
 */
const defaultImg = 'https://image.jxc4.com/image/0d2cc478f955889455861fe519e02d15.png'
function handleImgError(index:number){
  // 防止无限循环：如果已经是默认图，不再替换
  if (historyList.value[index].vendorDescription !== defaultImg) {
    historyList.value[index].vendorDescription = defaultImg
  }
  // console.log('加载图片信息',e,'number',index)
}

/**
 * 筛选条件实例对象
 */
const popup = ref<any>(null)
const keyword = ref<string>('')
/**
 * 起始时间,结束时间
 */
const date1 = ref<string>(
  timeFormatD(+new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7))
  // timeFormatD(+new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2))
)
const date2 = ref<string>(timeFormatD(+new Date()))
const endDate = ref<string>('')
  type vendorArrType = {
  id: string
  name: string
}
const vendor = ref<number>(0)
const vendorArr = ref<Array<vendorArrType>>([
  { id: 'created_at', name: '创建时间' },
  { id: 'updated_at', name: '更新时间' },
  { id: 'vendor_id', name: '来源' }
])

const sortIndex = ref<number>(0)
const sortArr = ref<vendorArrType[]>([
  { id: 'desc', name: '降序' },
  { id: 'asc', name: '升序' },
])
const totalCount = ref<number>(0)
onMounted(() => {
  console.log('popup',popup.value)
})
/**
 * 登录状态
 */
const isLogin = computed(() => {
  return store.getters['serveInfo/isLogin']
})
onLoad(async () => {
    if(!isLogin.value) return
  await getAccountInvoice()
})

async function getAccountInvoice(){
  try {
    let obj = {
      rank:sortArr.value[sortIndex.value].id, // desc/asc
      orderBy:vendorArr.value[vendor.value].id,
      keyword:keyword.value,
      beginTime:date1.value,
      endTime:date2.value,
      pageNum:page.value,
      pageSize:pageSize.value
    }
    let res = await order.queryAccountInvoice(obj)
    if(res.code == 0){
      console.log('查询用户的使用记录',res)
      historyList.value = historyList.value.concat(res.data.list || [])
      totalCount.value = res.data.total || 0
    }
    popup.value.close()
  } catch (error) {
    
  }

}

// const totalCount = ref<>(0)
function dataHoming(){
  historyList.value = []
  page.value = 1
   totalCount.value = 0
}

/**
 * 下拉刷新
 */
const triggered = ref<boolean>(false)
let onPullDownRefreshTimer: any = ''
function refresherrefresh() {
    triggered.value = true
    clearTimeout(onPullDownRefreshTimer)
    onPullDownRefreshTimer = setTimeout(() => {
        triggered.value = false
        dataHoming()
        // oneMenuClick(isFilter.value)
        // if (isFilter.value == 'hot') return
        // leftBarRef.value.GetStoreCategoryMap()
        getAccountInvoice()
    }, 500)
}


  /*************************************************
   * 页面触底，加载更多数据
  */
  const page = ref<number>(1)    // 第几页
  const pageSize = ref<number>(20) // 每页条数20
  const isLoad = ref<boolean>(false)  // 加载图
  function scrolltolower() {
    console.log('页面触底，加载更多数据,1111111',totalCount.value)
      page.value++
      if (pageSize.value * (page.value - 1) > totalCount.value || totalCount.value < pageSize.value) {
          isLoad.value = false
      } else {
          if (isLoad.value) return
          getAccountInvoice()
      }
  }


function dateChange4(e: AnyObject) {
  vendor.value = e.detail.value
}

function dateChange3(e: AnyObject) {
  vendor.value = e.detail.value
}

function dateChange1(e: AnyObject) {
  date1.value = e.detail.value
}
function dateChange2(e: AnyObject) {
  date2.value = e.detail.value
}

async function searchStore(keywords: string) {
    keyword.value = keywords
    historyList.value = []
    console.log('赛选的内容,,完成搜索',keyword.value)
    await getAccountInvoice()
}

function openPopup(){
  console.log('打开弹框',popup.value)
  popup.value.open()
}

/**
 * 弹框确认
 */
async function confirm(){
  historyList.value = []
  await getAccountInvoice()
}

/**
 * 清空输入框
 */
async function clearIpt() {
    keyword.value = ''
    // reset()
}

/**
 * 输入框输入值变化
 */
// let trembling = jx_trembling(getOrderAllInfo, 800)
// let trembling2 = jx_trembling(getAfsOrders, 800)
async function changeIpt(keywords: string) {
    keyword.value = keywords
    // reset()
}
</script>

<style lang="scss" scoped>
.list{
  // border: 1rpx solid red;
  // width: 750rpx;
  // box-sizing: border-box;
  padding: 10rpx 20rpx;

  .list_item{
    // .desc{
    //   display: flex;
    // }
    margin-bottom: 40rpx;
    background-color: #fff;
    border: 1rpx solid #eee;
    padding:10rpx 30rpx;
    border-radius: 15rpx;
    display: flex;

    .desc{
      width: calc(100% - 200rpx);
      height: 200rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .img{
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
    }
  }
}

.filter-root {
  box-sizing: border-box;
  height: 90rpx;
  padding: 15rpx;
  background-color: #fff;
  display: flex;
  align-items: center;

  .btn {
    padding: 8rpx 0;
    width: 160rpx;
    text-align: center;
    background-color: $jx-primary;
    color: #fff;
    font-size: 28rpx;
    border-radius: 100rpx;
    margin-right: 15rpx;
  }

  :deep(.uni-searchbar) {
    padding: 0 !important;
    width: 545rpx !important;

    .uni-searchbar__box {
      border-radius: 100rpx !important;
      height: auto !important;
    }
  }
}

.switch-filter {
    background-color: #fff;

    .condition {
        text-align: center;
        color: #999999;
    }

    box-sizing: border-box;
    border-radius: 10rpx;
    padding: 20rpx 40rpx 10rpx 40rpx;

    .item {
        display: flex;
        margin-top: 35rpx;

        .root {
            display: flex;
            align-items: center;

            text {
                padding: 0 10rpx;
            }
        }

        .title {
            color: #999999;
        }

        .value {
            padding: 5rpx 15rpx;
            border: 1rpx solid #bebebe;
            border-radius: 10rpx;
        }
    }

    .btnRoot {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;
        border-top: 1rpx solid #999999;

        .cancel,
        .confirm {
            color: #696969;
            text-align: center;
            width: 100%;
            padding: 20rpx;
        }

        .confirm {
            color: #000;
            border-left: 1rpx solid #999999;
        }
    }
}
</style>