<template>
  <PageLayout>
    <template #header-right> </template>
    <LoadingView canRefresh :refresh="load" :loading="loading">
      <q-card class="bg-white q-ma-md q-pa-sm">
        <q-btn
          dense
          flat
          color="grey-3"
          text-color="dark"
          icon-right="expand_more"
          :label="dateStr || '本月'"
          @click="dateDialogVisible=true"
        >
            <!-- <q-date v-model="dateStr" minimal mask="YYYY-MM"> </q-date> -->
        </q-btn>
        <div class="row q-mt-none q-col-gutter-sm">
          <div class="col">
            <div class="fit rounded-borders bordered-grey q-pa-sm text-caption">
              <span class="text-grey">本月销售注册</span>
              <div class="text-subtitle1 text-weight-bold">
                {{ info.total?.register_num || 0 }}人
              </div>
            </div>
          </div>
          <div class="col">
            <div class="fit rounded-borders bordered-grey q-pa-sm text-caption">
              <span class="text-grey">本月销售金额</span>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.total?.money || 0) }}元
              </div>
            </div>
          </div>
          <div class="col">
            <div class="fit rounded-borders bordered-grey q-pa-sm text-caption">
              <span class="text-grey">本月应付佣金</span>
              <div class="text-subtitle1 text-weight-bold">
                {{ formatMoney(info.total?.brokerage || 0) }}元
              </div>
            </div>
          </div>
        </div>
      </q-card>
      <div class="q-ma-md text-weight-bold">
        销售列表{{ info.agents.length }}个
      </div>
      <q-card v-for="(item, i) in info.agents" :key="i" class="q-ma-md">
        <q-card-section
          @click="
            router.push({
              path: '/statistics/agent/'+item.id,
            })
          "
        >
          <div class="row items-center">
            <UserAvatar size="md" :src="item.avatar_url||item.avatar" />
            <span class="col q-px-sm">{{
              item.nickname || item.name || item.hide_name
            }}</span>
            <q-icon name="arrow_forward_ios" size="14px" />
          </div>
        </q-card-section>
        <q-separator />
        <q-card-section class="row text-caption text-center">
          <div class="col">
            <div class="text-grey">销售时长</div>
            {{ item.agent_days }}天
          </div>
          <div class="col">
            <div class="text-grey">销售总额</div>
            ￥{{ item.agent_money }}
          </div>
          <div class="col">
            <div class="text-grey">佣金比例</div>
            {{ item.agent_brokerage }}%
          </div>
          <div class="col">
            <div class="text-grey">状态</div>
            <q-toggle
              size="sm"
              dense
              :model-value="item.agent"
              :true-value="1"
              :false-value="0"
              @update:model-value="(val) => toggleState(val, i)"
            ></q-toggle>
          </div>
        </q-card-section>
      </q-card>
    </LoadingView>
    <template #footer>
      <MainPageFooter />
    </template>

    <q-dialog v-model="dateDialogVisible" position="bottom">
      <van-date-picker
        style="width:300px"
        v-model="currentDate"
        title="选择年月"
        :columns-type="['year', 'month']"
        @confirm="load()"
        @cancel="dateDialogVisible=false"
      />
    </q-dialog>
  </PageLayout>
</template>
<script setup>
import { DatePicker } from 'vant';
import MainPageFooter from "src/components/MainPageFooter.vue";
import LoadingView from "src/components/LoadingView.vue";
import { ref, watch, shallowReactive,computed } from "vue";
import { api } from "boot/axios";
import { formatMoney } from "src/utils/tools";
// import CascadeSelect from "src/components/CascadeSelect.vue";
import { useQuasar,format } from 'quasar';
import UserAvatar from "src/components/UserAvatar.vue";
import { useRouter } from "vue-router";
const router = useRouter();
const loading = ref(false);
const info = ref({});
const $q = useQuasar()
const dateDialogVisible = ref(true)
const currentDate = ref([new Date().getFullYear(),format.pad(new Date().getMonth()+1,2)])
const dateStr = computed(()=>{
  return currentDate.value.join('-')
})

function load() {
  loading.value = true;
  dateDialogVisible.value = false
  api
    .getAgentReport({
      date_start: dateStr.value,
    })
    .then((res) => {
      loading.value = false;
      info.value = res;
    })
    .catch((e) => {
      loading.value = e.message;
    });
}
load();
function toggleState(agent,i) {
  if (agent) {
    return $q
      .dialog({
        title: "设置销售佣金",
        prompt: {
          model: info.value.agents[i].agent_brokerage,
          isValid: (val) => val * 1 >= 1 && val * 1 < 100, // << here is the magic
          type: "number", // optional
          placeholder: "请输入佣金",
        },
        cancel: true,
      })
      .onOk((agent_brokerage) => {
        updateCustomerInfo(i,{
          agent_brokerage,
          agent,
        });
      });
  }
  $q.dialog({
    message: "确认关闭销售吗？",
    cancel: true,
  }).onOk(() => {
    updateCustomerInfo(i,{
      agent,
    });
  });
}

function updateCustomerInfo(i,data){
  return api
    .updateCustomerInfo({
      customer_id:info.value.agents[i].id,
      ...data
    })
    .then((res) => {
      for(let p in data){
        info.value.agents[i][p] = data[p]
      }
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
      return Promise.reject(e)
    });
}
</script>
