<template>
  <PageLayout>
    <template #header-title>
      <q-btn-dropdown flat dense :label="workerList[sellerIdx]?.nickname">
        <q-list style="min-width: 100px">
          <q-item
            v-for="(item, i) in workerList"
            :key="i"
            clickable
            v-close-popup
            @click="sellerIdx = i"
          >
            <q-item-section>{{ item.nickname }}</q-item-section>
          </q-item>
        </q-list>
      </q-btn-dropdown>
    </template>
    <template #header-right>
      <q-btn dense unelevated="" color="grey-3" 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>
      <!-- <q-btn
        dense
        unelevated=""
        color="grey-3"
        text-color="dark"
        icon-right="expand_more"
        :label="dateStr || '今日'"
      >
        <q-popup-proxy ref="popupRef">
          <q-date v-model="dateStr" minimal mask="YYYY-MM-DD"> </q-date>
        </q-popup-proxy>
      </q-btn> -->
    </template>
    <LoadingView canRefresh :refresh="load" :loading="loading">
      <div class="bg-white q-mb-sm q-pa-md">
        <div class="bg-teal-10 text-white rounded-borders-xs row relative-position">
          <router-link :to="{path:'/statistics/report/chupiao',query:{t:Date.now(),...form}}" class="col-6 q-pa-md">
            <div class="text-h5 text-weight-bold">
              {{ formatMoney(reportInfo?.chupiao_money || 0) }}
            </div>
            <span class="text-grey-3">总出票金额</span>
          </router-link>
          <router-link :to="{path:'/statistics/report/paijiang',query:{t:Date.now(),...form}}" class="col-6 q-pa-md">
            <div class="text-h5 text-weight-bold">
              {{ formatMoney(reportInfo?.send_prize || 0) }}
            </div>
            <span class="text-grey-3">派奖总金额</span>
          </router-link>
          <div class="full-height  q-py-md absolute-center "><q-separator vertical size="0.5px" color="teal-7" class="full-height" /></div>
          <div class="col-12 q-px-md"><q-separator size="0.5px" color="teal-7" /></div>
          <router-link :to="{path:'/statistics/report/win_list',query:{t:Date.now(),...form}}" class="col-6 q-pa-md">
            <div class="text-h5 text-weight-bold">
              {{ formatMoney(reportInfo?.win_prize  || 0) }}
            </div>
            <span class="text-grey-3">中奖总金额</span>
          </router-link>
          <router-link v-if="isAll" :to="{path:'/customer/wallet/draw/history',query:{title:'提现记录',t:Date.now(),...form}}" class="col-6 q-pa-md">
            <div class="text-h5 text-weight-bold">
              {{ formatMoney(info.report?.customer_withdraw || 0) }}
            </div>
            <span class="text-grey-3">提现总金额</span>
          </router-link>
          <!-- <div v-else class="col-6 q-pa-md">
            <div class="text-h5 text-weight-bold">
              {{ jiedanNum || 0 }}
            </div>
            <span class="text-grey-3">接单总量</span>
          </div> -->
        </div>
      </div>
      <div class="bg-white q-mb-sm q-pa-md" v-if="isAll">
        <div class="row q-col-gutter-sm">
          <div class="col-6">
            <router-link :to="{path:'/statistics/list/customer_recharge',query:{title:'用户充值',t:Date.now(),...form}}"
            class=" block fit text-white rounded-borders-xs q-pa-sm" :class="'bg-'+PAGE_CONFIG['customer_recharge'].color">
              <div class="text-grey-3 text-caption">用户充值</div>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.report?.customer_recharge || 0) }}
              </div>
              <!-- <div class="text-grey-3 text-caption">
                银行手续费约为0元
              </div> -->
            </router-link>
          </div>
          <div class="col-3">
            <router-link :to="{path:'/statistics/list/shop_coop_brokerage',query:{title:'合作收入',t:Date.now(),...form}}"
            class="block fit text-white rounded-borders-xs q-pa-sm" :class="'bg-'+PAGE_CONFIG['shop_coop_brokerage'].color">
              <div class="text-grey-3 text-caption">合作收入</div>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.report?.cooperate_brokerage || 0) }}
              </div>
              <div class="text-grey-3 text-caption"> </div>
            </router-link>
          </div>
          <div class="col-3">
            <router-link :to="{path:'/statistics/list/shop_bills',query:{title:'服务费支出',t:Date.now(),...form}}"
            class="block fit text-white rounded-borders-xs q-pa-sm" :class="'bg-'+PAGE_CONFIG['shop_bills'].color">
              <div class="text-grey-3 text-caption">服务费支出</div>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.report?.chupiao_fee_money || 0) }}
              </div>
              <div class="text-grey-3 text-caption"> </div>
            </router-link>
          </div>
        </div>
      </div>
      <div class="bg-white q-pa-md">
        <div class="row q-col-gutter-sm">
          <div class="col">
            <router-link :to="{path:'/statistics/list/incr_money',query:{title:'手工加款 - '+(sellerIdx?workerList[sellerIdx].nickname:'全店'),t:Date.now(),...form,seller_id: sellerId}}"
            class="block fit text-white rounded-borders-xs q-pa-sm" :class="'bg-'+PAGE_CONFIG['incr_money'].color">
              <div class="text-grey-3 text-caption">手工加款</div>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(reportInfo?.incr_money || 0) }}
              </div>
              <div class="text-grey-3 text-caption"> </div>
            </router-link>
          </div>
          <div class="col">
            <router-link :to="{path:'/statistics/list/reduce_money',query:{title:'手工扣款 - '+(sellerIdx?workerList[sellerIdx].nickname:'全店'),t:Date.now(),...form,seller_id: sellerId}}"
            class="block fit text-white rounded-borders-xs q-pa-sm" :class="'bg-'+PAGE_CONFIG['reduce_money'].color">
              <div class="text-grey-3 text-caption">手工扣款</div>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(reportInfo?.reduce_money || 0) }}
              </div>
              <div class="text-grey-3 text-caption"> </div>
            </router-link>
          </div>
        </div>
      </div>
      <template v-if="isAll">
        <q-separator size="0.5px"/>
        <div class="bg-white q-pa-md">
          <div class="text-subtitle1 q-mb-sm">用户统计</div>
          <div class="row q-col-gutter-sm">
            <div class="col-6">
              <router-link :to="{path:'/statistics/list/registers',query:{title:'注册用户数',t:Date.now(),...form}}"
              class="block bg-light-blue-1 glossy-x fit rounded-borders-xs q-pa-sm relative-position">
                <img class="absolute-bottom-right" style="width:32px;height:32px; margin:12px 8px;" src="~assets/register_user.svg"/>
                <div class="text-subtitle1 text-weight-bold">
                  {{ info.report?.register_num || 0 }}
                </div>
                <div class="text-grey text-caption">注册用户数</div>
              </router-link>
            </div>
            <div class="col-6">
              <router-link :to="{path:'/statistics/list/buyers',query:{title:'购彩用户数',t:Date.now(),...form}}"
              class="block bg-yellow-1 fit glossy-x rounded-borders-xs q-pa-sm relative-position">
                <img class="absolute-bottom-right" style="width:46px;height:46px; margin:6px 4px;" src="~assets/order_user.svg"/>
                <div class="text-subtitle1 text-weight-bold">
                  {{ info.report?.buyer_num || 0 }}
                </div>
                <div class="text-grey text-caption">购彩用户数</div>

              </router-link>
            </div>
          </div>
        </div>
      </template>
      <q-separator v-if="info.current" size="0.5px" />
      <div v-if="info.current" class="bg-white q-mb-sm q-pa-md">
        <div class="text-subtitle1 q-mb-sm">账单统计</div>
        <div class="row q-col-gutter-sm">
          <div class="col">
            <div class="q-pa-sm">
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.last?.shop_banlance || 0) }}
              </div>
              <div class="text-grey text-caption">昨日店铺余额</div>
            </div>
          </div>
          <div class="col">
            <div class="q-pa-sm">
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.current?.shop_banlance || 0) }}
              </div>
              <div class="text-grey text-caption">今日店铺余额</div>
            </div>
          </div>
          <div class="col">
            <div class="q-pa-sm">
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney((info.current?.shop_banlance||0)-(info.last?.shop_banlance||0)) }}
              </div>
              <div class="text-grey text-caption">店铺余额变动</div>
            </div>
          </div>
        </div>
          <q-separator size="0.5px"></q-separator>
          <div class="row q-col-gutter-sm">
            <div class="col">
              <div class="q-pa-sm">
                <div class="text-subtitle1 text-weight-bold">
                  {{ formatMoney(info.last?.customers_balance || 0) }}
                </div>
                <div class="text-grey text-caption">昨日托管余额</div>
              </div>
            </div>
            <div class="col">
              <div class="q-pa-sm">
                <div class="text-subtitle1 text-weight-bold">
                  {{ formatMoney(info.current?.customers_balance || 0) }}
                </div>
                <div class="text-grey text-caption">今日托管余额</div>
              </div>
            </div>
            <div class="col">
              <div class="q-pa-sm">
                <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney((info.current?.customers_balance||0)-(info.last?.customers_balance||0))}}
                </div>
                <div class="text-grey text-caption">托管余额变动</div>
              </div>
            </div>
          </div>
      </div>
      <!-- <q-separator v-if="isAll" size="0.5px" />
      <div v-if="isAll" class="bg-white q-mb-sm">
        <div class="text-subtitle1 q-pa-md">店员统计</div>
        <q-markup-table separator="cell" flat dense square bordered class="markup-table bordered-table text-center">
            <thead>
              <tr class="bg-grey-2">
                <th>店员</th>
                <th>接单总量</th>
                <th>出票总额</th>
                <th>中奖总额</th>
                <th>派奖总额</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="(item,i) in info.jiedan_list" :key="i">
                <tr v-if="item.id">
                  <td>{{ item.nickname || item.name || item.real_name }}</td>
                  <td>{{ item.jiedan_num }}</td>
                  <td>{{ formatMoney(item?.chupiao_money  || 0) }}</td>
                  <td>{{ formatMoney(item?.win_prize  || 0) }}</td>
                  <td>{{ formatMoney(item?.send_prize  || 0) }}</td>
                </tr>
              </template>
            </tbody>
          </q-markup-table>
      </div> -->
    </LoadingView>
    <template #footer>
      <MainPageFooter />
    </template>
  </PageLayout>
</template>
<script setup>
import MainPageFooter from "src/components/MainPageFooter.vue";
import LoadingView from "src/components/LoadingView.vue";
import { ref, watch,reactive, shallowReactive,computed } from "vue";
import { api } from "boot/axios";
import { formatMoney } from 'src/utils/tools'
import { date } from 'quasar'
import { PAGE_CONFIG } from './const.js'
import { useRoute,useRouter } from "vue-router";
const route  = useRoute()
const router = useRouter()
const workerList = shallowReactive([{ nickname: "全店", id: "" }]);
const sellerIdx = ref(0);
// const dateStr = ref(""); //date.formatDate(Date.now(),'YYYY-MM-DD')
const loading = ref(false);
const info = ref({});
const sellerId = computed(()=>{
  return workerList[sellerIdx.value]?.id
})
// const popupRef = ref(null);
const isAll = computed(()=>{
  return !(sellerId.value)
})
/* const jiedanNum = computed(() => {
  if(isAll.value) {
    return null;
  }
  return info.value.jiedan_list?.find(item => item.id == sellerId.value)?.jiedan_num
}) */
api.getWorkerList().then((res) => {
  res.forEach((item) => {
    if (!item.nickname) {
      item.nickname = item.name;
    }
    workerList.push(item);
  });
});
function load() {
  loading.value = true;
  api
    .getDashboardInfo({
      ...form,
      seller_id: sellerId.value,
    })
    .then((res) => {
      loading.value = false;
      info.value = res;
    })
    .catch((e) => {
      loading.value = e.message;
    });
}

const reportInfo = computed(()=>{
  return info.value.report
  // return sellerIdx.value?info.value.seller:info.value.current
})
const dateArr = ref({
  from: route.query.date_start||date.formatDate(new Date(),'YYYY-MM-DD'),
  to: route.query.date_end || date.formatDate(new Date(),'YYYY-MM-DD')
})
const form = reactive({})
const dateRangeOptions = reactive({
  start: ''
})
function clearDate(){
  dateArr.value={from:'',to:''}
  dateRangeOptions.start = ''
  onDateSure()
}
function onDateSure(){
  updateAndLoad()
  router.replace({
    path: route.path,
    query: {...route.query,...form}
  })
}
function updateAndLoad(){
  form.date_start = typeof dateArr.value == 'string' ? dateArr.value : dateArr.value?.from,
  form.date_end = typeof dateArr.value == 'string' ? dateArr.value : dateArr.value?.to
  load();
}
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
}
// watch(dateStr, () => {
//   load();
//   popupRef.value.hide();
// });
watch(sellerIdx, load);
updateAndLoad();
</script>
