<template>
  <PageLayout>
    <template #header-right>
      <q-btn dense flat @click="setBrokerage">修改佣金</q-btn>
    </template>
    <template #header-append>
      <q-tabs
        v-model="tab"
        dense
        no-caps
        narrow-indicator
        active-color="primary"
        indicator-color="primary"
      >
        <q-route-tab
          v-for="(item, i) in tabs"
          :key="item.value"
          :name="i"
          :label="item.name"
          :to="i === 0 ? route.path : { path: route.path, query: { tab: i } }"
          replace
        />
      </q-tabs>
    </template>
    <infinite-scroll :load="load" :list="list" ref="scrollRef" no-more="">
      <template #prepend>
        <div class="row bg-white q-pa-md items-center justify-between">
          <span v-if="tab == 0" class="q-mr-md">共邀请<span class="text-red">{{ total  }}</span>人</span>
          <span v-else class="q-mr-md">投注金额<span class="text-red">{{ total===''?'':formatMoney(total)}}</span>元</span>
          <q-btn
            color="grey-4"
            text-color="grey-8"
            unelevated
            dense
            size="md"
            class="q-pl-sm"
            icon-right="date_range"
          >
            <div class="text-center col" v-if="form.date_start">{{ form.date_start }} 至 {{ form.date_end }}</div>
            <div class="text-center col text-grey" v-else>选择时间范围</div>
            <!-- <q-icon
              v-if="datePicker.from"
              size="16px"
              color="grey"
              name="cancel"
              @click.stop="datePicker = {}"
            /> -->
            <q-popup-proxy ref="datePopupRef">
              <q-date v-model="datePicker" range minimal mask="YYYY-MM-DD">
                <q-btn color="primary" flat class="float-right" @click="onDateSure" v-close-popup label="确定"/>
                <q-btn flat class="float-right" color="grey" @click="clearDate" v-close-popup label="清空"/>
              </q-date>
            </q-popup-proxy>
          </q-btn>
        </div>
      </template>
      <template v-slot="{ item, index }">
        <q-item
          v-if="tab == 0"
          :item="item"
          :index="index"
          class="q-mt-sm bg-white"
          :to="{ path: '/customer/' + item.id }"
        >
          <q-item-section avatar>
            <UserAvatar :src="item.avatar_url||item.avatar" />
          </q-item-section>
          <q-item-section>
            <q-item-label>
              {{ item.name }}
              <span @click.stop.prevent="item.seePhone = !item.seePhone"
                >（{{ item.seePhone ? item.phone : "******" }}
                <q-icon
                  :name="!item.seePhone ? 'remove_red_eye' : 'visibility_off'"
              />）</span>
            </q-item-label>
            <q-item-label caption>
              注册时间：{{ formatDate(item.created_at) }}
            </q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-item-label caption>账户余额</q-item-label>
            <q-item-label class="text-red text-weight-bold"
              >￥{{ formatMoney(item.banlance) }}</q-item-label
            >
          </q-item-section>
        </q-item>
        <q-item
          v-else
          :item="item"
          :index="index"
          class="q-mt-sm bg-white"
          :to="{ path: '/order/' + item.order_sn }"
        >
          <q-item-section avatar>
            <UserAvatar :src="item.customer.avatar_url||item.customer.avatar" />
          </q-item-section>
          <q-item-section>
            <q-item-label>
              {{ item.customer.remark || item.customer.nickname }}
              <q-badge outline color="primary">{{ item.lottery.name }}</q-badge>
            </q-item-label>
            <q-item-label caption>
              注册时间：{{ formatDate(item.created_at) }}
            </q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-item-label caption>订单金额</q-item-label>
            <q-item-label caption>￥{{ formatMoney(item.money) }}</q-item-label>
          </q-item-section>
        </q-item>
      </template>
    </infinite-scroll>
  </PageLayout>
</template>
<script setup>
import { ref, onActivated, reactive, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSelfStore } from "stores/self";
import { api } from "boot/axios";
import { ORDER_TYPE } from "src/utils/const";
import { formatMoney, formatDate } from "src/utils/tools";
import { useInfiniteScroll } from "src/composables/infiniteScroll";
import UserAvatar from "src/components/UserAvatar.vue";
import { useQuasar,date } from "quasar";
const route = useRoute();
const router = useRouter();
const store = useSelfStore();
const $q = useQuasar();

const tabs = reactive([
  { value: "regist", name: "注册数据" },
  { value: "order", name: "投注数据" },
]);
const tab = ref(route.query.tab || 0);
const form  = reactive({
    agent_id: route.params.id,
    date_start: date.formatDate(date.startOfDate(new Date(),'month'),'YYYY-MM-DD'),
    date_end: date.formatDate(date.endOfDate(new Date(),'month'),'YYYY-MM-DD'),
  })

const total = ref('')
const { list, refresh, load, scrollRef } = useInfiniteScroll((page) => {
  total.value = ''
  return api.getAgentReportInfo(tabs[tab.value].value, {
    page,
    ...form
  }).then((res)=>{
    total.value = tab.value ==0 ? res.total : res.total_money
    return tab.value ==0 ? res : res.list
  });
},true);
watch(tab, refresh);
onActivated(() => {
  let i = route.query.tab || 0;
  if (tab.value != i || route.params.id!= form.agent_id) {
    tab.value = i;
    form.agent_id = route.params.id
    nextTick(refresh);
  }
});
function updateCustomerInfo(data) {
  return api
    .updateCustomerInfo({ customer_id: route.params.id, ...data })
    .then((res) => {
      $q.notify({type: 'positive',message: res.message || '修改成功' })
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
      return Promise.reject(e);
    });
}
function setBrokerage() {
  $q.dialog({
    title: "修改销售佣金",
    prompt: {
      model: "",
      isValid: (val) => val * 1 >= 1 && val * 1 < 100, // << here is the magic
      type: "number", // optional
      placeholder: "请输入佣金",
    },
    // options: {
    //   type: "toggle",
    //   model: [],
    //   items: [{ label: "Option 1", value: "opt1", color: "secondary" }],
    // },
    cancel: true,
  }).onOk((agent_brokerage) => {
    // console.log('>>>> OK, received', data)
    updateCustomerInfo({
      agent_brokerage,
    });
  });
}

const datePicker = ref({from:'',to:''})
// const datePopupRef = ref(null);
function onDateSure(){
  form.date_start = typeof datePicker.value == 'string' ? datePicker.value : datePicker.value?.from||''
  form.date_end = typeof datePicker.value == 'string' ? datePicker.value : datePicker.value?.to||''
  // datePopupRef.value.hide();
  refresh()
}
function clearDate(){
  datePicker.value = {from:'',to:''}
  onDateSure()
}
</script>
