<template>
  <div class="over-due-payable">
    <div class="mt-5 columns">
      <div class="column">
        <label class="label"
          >{{ isVietnamese ? "Thời gian (ngày)" : "Duration (Days)" }}
          <span class="has-text-danger"> * </span>
        </label>
        <p class="control">
          <input
            class="input"
            type="number"
            placeholder=""
            v-model="record.time"
            autocomplete="off"
          />
        </p>
      </div>
      <div class="column">
        <label class="label"
          >{{ isVietnamese ? "Mẫu email" : "Email Template" }}
          <span class="has-text-danger"> * </span>
        </label>
        <SearchBox
          v-bind="{
            api: 'Email_Template',
            field: 'name',
            column: ['name'],
            first: true,
            optionid: Number(record.emailTemplate),
          }"
          @option="documentSelected('emailTemplate', $event)"
        ></SearchBox>
      </div>
    </div>
    <div class="mt-5">
      <button
        class="button is-primary has-text-white"
        @click="update()"
      >
        {{ dataTemp.id ? "Cập nhật" : "Tạo mới" }}
      </button>
    </div>
  </div>
</template>
<script setup>
const { $copy, $insertrow, $updaterow, $snackbar, $store } = useNuxtApp();

const isVietnamese = computed(() => $store.lang.toLowerCase() === "vi");

var props = defineProps({
  api: String,
  pagename: String,
  row: Object,
  prefix: String,
});
const emit = defineEmits(["close", "modalevent"]);
const dataTemp = $copy(props.row || {});
let record = $copy(props.row?.detail || {});

function documentSelected(attr, obj, v) {
  record[attr] = obj.id;
  record.name = obj.name;
}

async function update() {
  const detail = record;
  let rs;
  if (dataTemp.id) {
    const dataUpdate = {
      ...dataTemp,
      detail,
    };
    rs = await $updaterow(props.api, dataUpdate, undefined, props.pagename);
  } else {
    const dataInsert = {
      detail,
      category: "system",
      classify: "overduepayables",
      code: `overdue-${record.lookup}-${record.time}-${record.emailTemplate}`,
      vi: "Lịch quá hạn thanh toán",
    };
    rs = await $insertrow(props.api, dataInsert, undefined, props.pagename);
  }

  if (rs === "error") return $snackbar(rs);
  emit("modalevent", { name: "dataevent", data: rs });
  emit("close");
}
</script>
