<template>
  <PageLayout>
    <template #header-right>
      <div class="row justify-end">
        <q-btn v-if="route.params.type !== 'customer_recharge'"
        no-wrap dense unelevated="" color="grey-3"
        class="select-btn col-shrink" align="between"
        text-color="dark" icon-right="expand_more" :label="dateStr">
          <q-popup-proxy ref="popupRef">
            <q-date v-model="dateArr"
              :options="checkDateEnabled"
              range minimal mask="YYYY-MM-DD"
              @update:model-value="onDateUpdate"
              @range-start="onRangeStart">
              <q-btn color="primary" flat class="float-right" @click="onDateSure" v-close-popup label="确定"/>
              <q-btn color="grey" flat class="float-right" @click="clearDate" v-close-popup label="清空"/>
            </q-date>
          </q-popup-proxy>
        </q-btn>
      </div>
    </template>
    <infinite-scroll :load="load" :list="list" ref="scrollRef">
      <template #prepend>
        <div v-if="route.params.type === 'customer_recharge'"
        class="q-px-md q-pb-sm row q-gutter-sm no-wrap bg-white">
          <q-btn
          dense
          unelevated
          no-wrap
          color="grey-3"
          text-color="dark"
          icon-right="expand_more"
          class="select-btn"
          align="between"
          :label="payChannelName"
          @click="showPayChannelPopup=true">
          </q-btn>
          <q-dialog v-model="showPayChannelPopup" position="bottom">
              <q-card class="full-width">
                <van-picker
                  :columns="channels"
                  @cancel="showPayChannelPopup = false"
                  @confirm="payChannelConfirm"
                />
              </q-card>
          </q-dialog>
          <q-btn
          dense
          unelevated
          no-wrap
          color="grey-3"
          text-color="dark"
          icon-right="expand_more"
          align="between"
          :label="dateStr" class="col select-btn">
            <q-popup-proxy ref="popupRef">
              <q-date v-model="dateArr"
                :options="checkDateEnabled"
                range minimal mask="YYYY-MM-DD"
                @update:model-value="onDateUpdate"
                @range-start="onRangeStart">
                <q-btn color="primary" flat class="float-right" @click="onDateSure" v-close-popup label="确定"/>
                <q-btn color="grey" flat class="float-right" @click="clearDate" v-close-popup label="清空"/>
              </q-date>
            </q-popup-proxy>
          </q-btn>
        </div>
        <q-card v-if="PAGE_CONFIG[route.params.type].position !=='bottom'" flat class="q-ma-md" :class="'bg-'+PAGE_CONFIG[route.params.type].color">
          <q-card-section>
          <div class="text-center text-white ">
            <div class="row">
              <div class="col relative-position" v-for="item,i in PAGE_CONFIG[route.params.type].props" :key="i">
                <div class="full-height q-py-md absolute-left light-dimmed"><q-separator v-if="i" vertical size="0.5px" :color="PAGE_CONFIG[route.params.type].color" class="full-height"/></div>
                <div class="text-weight-bold text-h5 q-mb-xs">{{ formatMoney(totalInfo[item.prop]) }}</div>
                <div>
                  {{ item.name }}
                </div>
              </div>
            </div>
            <div v-if="PAGE_CONFIG[route.params.type].desc" class="text-weight-bold text-caption q-mt-sm opacity-75">
              {{ PAGE_CONFIG[route.params.type].desc }}
            </div>
          </div>
          </q-card-section>
        </q-card>
        <q-tabs
          v-if="totalInfo.tabs && totalInfo.tabs.length"
          v-model="tab"
          no-caps
          dense
          active-color="primary"
          indicator-color="primary"
          class="bg-white"
        >
          <q-tab v-for="item,key in totalInfo.tabs" :name="key" :key="key">
            {{ item.name }}
          </q-tab>
        </q-tabs>
      </template>
      <template v-slot="{ item ,index}">
        <q-separator v-if="index" inset></q-separator>
        <q-item v-if="route.params.type == 'customer_recharge' || route.params.type == 'registers' || route.params.type == 'buyers' || PAGE_CONFIG[route.params.type].funcName == 'customer_bills'" class="bg-white">
          <!-- <q-item-section side>
            <q-img
              :src="item.avatar_url"
              width="32px"
              height="32px"
              no-spinner
            ></q-img>
          </q-item-section> -->
          <q-item-section>
            <q-item-label>{{ item.customer_name||item.customer_nickname||item.name||item.nickname }}</q-item-label>
            <q-item-label caption>{{ item.created_at }}</q-item-label>
          </q-item-section>
          <q-item-section side>
            <template v-if="PAGE_CONFIG[route.params.type].funcName == 'customer_bills'">
              <q-item-label class="text-red text-weight-bold">
                  {{formatMoney(item.money)}}元
              </q-item-label>
              <q-item-label class="text-caption" caption>
                {{route.params.type == 'incr_money'?'加款人':'扣款人'}}：{{ item.seller_name }}
              </q-item-label>
            </template>
            <template v-else-if="route.params.type == 'registers'">
              <q-item-label>设备：{{ item.client_type_name }}</q-item-label>
              <q-item-label>
                <template v-if="item.agentor">代理：{{ item.agentor.name || item.agentor.nickname }}</template>
              </q-item-label>
            </template>
            <template v-else-if="route.params.type == 'buyers'">
              <q-item-label>购买次数：{{ item.count }}次</q-item-label>
              <q-item-label>
                购买金额：{{ item.money }}元
              </q-item-label>
            </template>
            <q-item-label v-else-if="item.money" class="text-red text-weight-bold">
                {{formatMoney(item.money)}}元
            </q-item-label>
            <q-item-label caption v-if="route.params.type === 'customer_recharge' && !form.pay_channel_id">
              {{ item.channel_name || item.title }}
            </q-item-label>
          </q-item-section>
        </q-item>
        <q-item v-else class="bg-white">
          <!-- <q-item-section side v-if="item.order?.lottery_type?.type">
            <q-img
              :src="'/statics/lottery/' + item.order.lottery_type.type + '.png'"
              width="32px"
              height="32px"
              no-spinner
            ></q-img>
          </q-item-section> -->
          <q-item-section>
            <q-item-label>{{ item.title }}</q-item-label>
            <q-item-label caption>{{ item.created_at }}</q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-item-label v-if="route.params.type=='shop_coop_brokerage'" class="text-red text-weight-bold">
                {{formatMoney(item.cooperate_brokerage)}}元
            </q-item-label>
            <q-item-label v-else-if="item.money" class="text-red text-weight-bold">
                {{formatMoney(item.money)}}元
            </q-item-label>
            <q-item-label class="text-caption" caption v-if="item.order?.lottery_type">
              {{ item.order.lottery_type.name }}
            </q-item-label>
          </q-item-section>
        </q-item>
      </template>
    </infinite-scroll>
    <template #footer>
      <q-footer v-if="PAGE_CONFIG[route.params.type].position ==='bottom'">
        <div class="row justify-between items-center text-white q-px-md q-py-sm">
          <div class="" v-for="item,i in PAGE_CONFIG[route.params.type].props" :key="i">
            <span>
              {{ item.name }}：
            </span>
            <span class="text-weight-bold">{{ totalInfo[item.prop] }}</span>
          </div>
        </div>
      </q-footer>
    </template>
  </PageLayout>
</template>
<script setup>
import { Picker } from 'vant';
import { ref, onMounted, reactive, shallowReactive,watch,onActivated,shallowRef, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSelfStore } from "stores/self";
import { api } from "boot/axios";
import { useQuasar,date } from "quasar";
import { useInfiniteScroll } from 'src/composables/infiniteScroll';
import { formatMoney } from 'src/utils/tools'
import {PAGE_CONFIG} from './const.js'
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const store = useSelfStore();
const tab = ref(0)
const dateArr = ref({
  from: route.query.date_start||date.formatDate(new Date(),'YYYY-MM-DD'),
  to: route.query.date_end || route.query.date_start||date.formatDate(new Date(),'YYYY-MM-DD')
})
const form = reactive({
  date_start: dateArr.value.from,
  date_end: dateArr.value.to,
})
const dateRangeOptions = reactive({
  start: ''
})
const totalInfo = shallowRef({})
const { list, refresh, load,scrollRef } = useInfiniteScroll((page)=>{
  return api.getReportInfo(PAGE_CONFIG[route.params.type].funcName,{
    ...form,
    seller_id:route.query.seller_id,
    ...PAGE_CONFIG[route.params.type].params,
    page
  }).then((res) => {
    const {list,...info} = res
    if(list){
      totalInfo.value = info
    }else{
      totalInfo.value = {
        total: res.total
      }
    }
    return list instanceof Array?{data:list}:(list?list:res)
  });
})

// 支付渠道
const channels = shallowReactive([{
  text: '全部',
  value: 0
}])
api.getPayChannels().then((res) => {
  res.forEach(item => {
    if(item.pay_type !== 'qrcode' && item.pay_channels && item.pay_channels.length){
      item.pay_channels.forEach(ch => {
        if(ch.opened == 1){
          channels.push({
          text: `${item.title}(${ch.title})`,
          value: ch.id
        })
        }
      })
    }
  })
})
const payChannelName = ref(channels[0].text)
const showPayChannelPopup = ref(false)
function payChannelConfirm({selectedOptions}){
  showPayChannelPopup.value = false
  payChannelName.value = selectedOptions[0].text
  form.pay_channel_id = selectedOptions[0].value
  refresh()
}

watch(tab,()=>{
  form.filter = totalInfo.value.tabs?.[tab.value]?.prop
})

function clearDate(){
  dateArr.value={from:'',to:''}
  dateRangeOptions.start = ''
  onDateSure()
}
function onDateSure(noRouter){
  form.date_start = typeof dateArr.value == 'string' ? dateArr.value : dateArr.value?.from,
  form.date_end = typeof dateArr.value == 'string' ? dateArr.value : dateArr.value?.to
  refresh();
  if(noRouter == 'no-router'){
    return
  }
  router.replace({
    path: route.path,
    query: {...route.query,...form}
  })
}
let enterTime = route.query.t
onActivated(()=>{
  if(route.query.t!=enterTime){
    enterTime = route.query.t
    dateArr.value = {
      from: route.query.date_start || date.formatDate(new Date(),'YYYY-MM-DD'),
      to: route.query.date_end || route.query.date_start||date.formatDate(new Date(),'YYYY-MM-DD')
    }
    onDateSure('no-router')
  }
})

const dateStr = computed(() => {
  if(form.date_start){
    if(form.date_end == form.date_start){
      return form.date_start
    }
    return form.date_start + '至' + form.date_end
  }
  return '今日'
})

// watch(dateArr,onRangeStart)
function onRangeStart(from){
  if (from) {
    dateRangeOptions.start = new Date(from.year,from.month-1,from.day)
  } else {
    dateRangeOptions.start = ''
  }
  // dateRangeOptions.max = date.formatDate(new Date(from.year,from.month),'YYYY/MM')
  // dateRangeOptions.min = date.formatDate(new Date(from.year,from.month-2),'YYYY/MM')
}
function onDateUpdate(value,reason,details){
  onRangeStart(details.from ? {
    year: details.from.year,
    month: details.from.month,
    day: details.from.day
  } : null)
}
function checkDateEnabled(val){
  if(dateRangeOptions.start){
    let startDate = dateRangeOptions.start//date.extractDate(dateRangeOptions.start,'YYYY-MM-DD')
    return val <= date.formatDate(date.addToDate(startDate,{months:1}),'YYYY/MM/DD') &&
    val >= date.formatDate(date.subtractFromDate(startDate,{months:1}),'YYYY/MM/DD')
  }
  return true
}
</script>
<style lang="scss" scoped></style>
