<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__lt: $dayjs().format('YYYY-MM-DD'),
};
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 paymentSchedule = ref([]);
const paymentScheduleValues =
  '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';

async function setPaymentSheduleData() {
  const paymentScheduleData = await $getdata('payment_schedule', undefined, {
    filter: filter.value,
    sort: 'to_date',
    values: paymentScheduleValues,
  });
  paymentSchedule.value = paymentScheduleData;
}

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

watch(
  activeDateFilter,
  (val) => {
    if (!val) {
      filter.value = defaultFilter;
    } else {
      const cutoffDate = $dayjs()
        .subtract(val.time, 'day')
        .format('YYYY-MM-DD');
      const filterField = `to_date__${val.lookup === 'lte' ? 'gt' : 'lte'}`;
      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.selectedPaymentSchedulesForEmailInOverdue.length} thông báo quá hạn không?`,
    },
  };
}

watch(
  filter,
  () => {
    key.value += 1;
    setPaymentSheduleData();
  },
  { deep: true },
);

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

function toggleAll() {
  if ($store.selectedPaymentSchedulesForEmailInOverdue.length === 0) {
    $store.commit(
      'selectedPaymentSchedulesForEmailInOverdue',
      paymentSchedule.value.map((p) => p.id),
    );
  } else {
    $store.commit('selectedPaymentSchedulesForEmailInOverdue', []);
  }
}
const { contents, send, isSending } = useSendEmail(filter, 14);
</script>
<template>
  <div
    class="is-flex is-justify-content-space-between is-align-content-center mb-4"
  >
    <div class="buttons m-0">
      <p>Quá 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.selectedPaymentSchedulesForEmailInOverdue !== undefined"
    >
      <button
        v-if="$store.selectedPaymentSchedulesForEmailInOverdue.length > 0"
        @click="openConfirmModal()"
        :class="['button', 'is-light', { 'is-loading': isSending }]"
      >
        Gửi {{ $store.selectedPaymentSchedulesForEmailInOverdue.length }} thông
        báo
      </button>
      <button @click="toggleAll" class="button">
        {{
          $store.selectedPaymentSchedulesForEmailInOverdue.length > 0
            ? 'Bỏ chọn'
            : 'Chọn'
        }}
        tất cả
      </button>
    </div>
  </div>
  <DataView
    :key="key"
    v-bind="{
      pagename: 'payment-schedule-overdue',
      api: 'payment_schedule',
      setting: 'payment-schedule-debt-overdue',
      realtime: { time: '5', update: 'true' },
      params: {
        filter,
        sort: 'to_date',
        values: paymentScheduleValues,
      },
    }"
  />
  <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>
