<template>
  <div class="columns is-multiline mx-0">
    <div class="column is-3">
      <div class="field">
        <label class="label">Từ ngày<b class="ml-1 has-text-danger">*</b></label>
        <div class="control">
          <Datepicker
            v-bind="{ record, attr: 'fdate', maxdate: new Date() }"
            @date="selected('fdate', $event)"
          ></Datepicker>
        </div>
        <p class="help is-danger" v-if="errors.issued_date">{{ errors.issued_date }}</p>
      </div>
    </div>
    <div class="column is-3">
      <div class="field">
        <label class="label">Đến ngày<b class="ml-1 has-text-danger">*</b></label>
        <div class="control">
          <Datepicker
            v-bind="{ record, attr: 'tdate', maxdate: new Date() }"
            @date="selected('tdate', $event)"
          ></Datepicker>
        </div>
        <p class="help is-danger" v-if="errors.issued_date">{{ errors.issued_date }}</p>
      </div>
    </div>
  </div>
  <DataView v-bind="vbind" v-if="vbind" />
</template>
<script setup>
const { $dayjs, $id } = useNuxtApp();
const fdate = ref($dayjs().format("YYYY-MM-DD"));
const tdate = ref($dayjs().format("YYYY-MM-DD"));
const record = ref({ fdate: fdate.value, tdate: tdate.value });
const errors = ref({});
const vbind = ref(null);

onMounted(() => {
  loadData();
})

function selected(attr, value) { 
  if (attr === "fdate") fdate.value = value;
  else tdate.value = value;
  loadData();
}

function loadData() {
  vbind.value = undefined;
  setTimeout(() => {
    vbind.value = {
      pagename: `debt-customer-${$id()}`,
      setting: "debt-customer",
      api: "internalentry",
      params: {
        values:
          "customer__code,customer__fullname,customer__type__name,customer__legal_type__name,customer__legal_code",
        distinct_values: {
          sum_sale_price: { type: "Sum", field: "product__prdbk__transaction__sale_price" },
          sum_received: { type: "Sum", field: "product__prdbk__transaction__amount_received" },
          sum_remain: { type: "Sum", field: "product__prdbk__transaction__amount_remain" },
        },
        summary: "annotate",
        filter: { 
          date__gte: fdate.value, 
          date__lte: tdate.value 
        },
        sort: "-sum_remain",
      },
    }
  });
}
</script>
