<script setup>
import useSendEmail from '@/components/debt/useSendEmail';
import { isEqual } from 'es-toolkit';

const { 
  $dayjs,
  $getdata,
  $store,
} = useNuxtApp();

const payables = ref(null);
const defaultFilter = {
  status: 1,
  to_date__gte: $dayjs().format('YYYY-MM-DD'),
  to_date__lte: undefined,
}
const filter = ref(defaultFilter);
const activeDateFilter = ref(null);
const key = ref(0);

function setDateFilter(detail) {
  activeDateFilter.value = isEqual(activeDateFilter.value, detail) ? null : detail;
}

function resetDateFilter() {
  activeDateFilter.value = null;
}

const paymentSchedules = ref([]);

onMounted(async () => {
  const payablesData = await $getdata('bizsetting', undefined, { filter: { classify: 'duepayables' }, sort: 'index' });
  payables.value = payablesData;
});

watch(activeDateFilter, (val) => {
  if (!val) {
    filter.value = defaultFilter;
  } else {
    const cutoffDate = $dayjs().add(val.time, 'day').format('YYYY-MM-DD');
    const filterField = `to_date__${val.lookup}`;
    filter.value = {
      ...defaultFilter,
      [filterField]: cutoffDate,
    }
  }
}, { deep: true })

const showmodal = ref(null);

function openConfirmModal() {
  showmodal.value = {
    component: 'dialog/Confirm',
    title: 'Xác nhận',
    width: '500px',
    height: '100px',
    vbind: {
      content: `Bạn có đồng ý gửi ${$store.selectedPaymentSchedulesForEmailInDue.length} thông báo đến hạn không?`,
    }
  }
}
watch(filter, () => {
  key.value += 1;
}, { deep: true })

watch(key, () => {
  // reset when DataView re-renders because of filter
  $store.commit('selectedPaymentSchedulesForEmailInDue', []) 
})

function toggleAll() {
  if ($store.selectedPaymentSchedulesForEmailInDue.length === 0) {
    $store.commit('selectedPaymentSchedulesForEmailInDue', paymentSchedules.value.map(p => p.id)) 
  } else {
    $store.commit('selectedPaymentSchedulesForEmailInDue', []) 
  }
}
const { contents, send, isSending } = useSendEmail(filter, 13);
</script>
<template>
  <div class="is-flex is-justify-content-space-between is-align-content-center mb-4">
    <div class="buttons m-0">
      <p>Đến hạn:</p>
      <button 
        v-for="payable in payables"
        :key="payable.id"
        @click="setDateFilter(payable.detail)"
        :class="['button', { 'is-primary': isEqual(activeDateFilter, payable.detail) }]"
      >
        {{ payable.detail.lookup === 'lte' ? '≤' : '>' }} {{ payable.detail.time }} ngày
      </button>
      <button 
        v-if="activeDateFilter"
        @click="resetDateFilter()"
        class="button is-white"
      >
        Xoá lọc
      </button>
    </div>
    <div class="buttons" v-if="$store.selectedPaymentSchedulesForEmailInDue !== undefined">
      <button
        v-if="$store.selectedPaymentSchedulesForEmailInDue.length > 0"
        @click="openConfirmModal()"
        :class="['button', 'is-light', { 'is-loading': isSending }]"
      >
        Gửi {{ $store.selectedPaymentSchedulesForEmailInDue.length }} thông báo
      </button>
      <button 
        @click="toggleAll"
        class="button"
        :disabled="paymentSchedules.length === 0"
      >
        {{ $store.selectedPaymentSchedulesForEmailInDue.length > 0 ? 'Bỏ chọn' : 'Chọn' }} tất cả
      </button>
    </div>
  </div>
  <DataView
    :key="key"
    v-bind="{
      pagename: 'payment-schedule-due',
      api: 'payment_schedule',
      setting: 'payment-schedule-debt-due',
      realtime: { time: '5', update: 'true' },
      params: {
        filter,
        sort: 'to_date',
        values: 'id,penalty_paid,penalty_remain,penalty_amount,penalty_reduce,batch_date,amount_remain,paid_amount,remain_amount,code,status,txn_detail,txn_detail__transaction__product,txn_detail__transaction__product__trade_code,txn_detail__transaction__code,txn_detail__code,txn_detail__transaction__customer__code,txn_detail__transaction__customer__fullname,txn_detail__transaction__customer__email,txn_detail__transaction__customer__type__code,txn_detail__transaction__customer__legal_code,txn_detail__transaction__customer__contact_address,txn_detail__transaction__customer__address,txn_detail__transaction__customer__phone,txn_detail__transaction__policy__code,txn_detail__phase__name,type__name,from_date,to_date,amount,cycle,cycle_days,status__name,detail,entry',
      },
      onDisplayDataChange: (values) => paymentSchedules = values
    }" 
  />
  <Modal 
    v-if="showmodal" 
    v-bind="showmodal" 
    @confirm="send" 
    @close="showmodal = undefined" 
  />
    <!-- <div class="is-flex is-gap-1">
      // debug
      <Template1
        v-if="contents"
        v-for="content in contents"
        :content="content"
        previewMode
      />
    </div> -->
</template>