<template>
  <div class="due-payable">
    <div class="mt-5 columns">
      <div class="column is-2">
        <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="15,30,60" v-model="record.time" autocomplete="off" />
        </p>
      </div>
      <div class="column is-2">
        <label class="label"
          >{{ isVietnamese ? "So sánh" : "Lookup Field" }} <span class="has-text-danger"> * </span>
        </label>
        <p class="control">
          <input class="input" placeholder="gt,lt,gte,lte" v-model="record.lookup" 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: "duepayables",
      code: `due-${record.lookup}-${record.time}d-${record.emailTemplate}`,
      vi: "Lịch đến 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>

<!-- <div>{{ row.detail ? JSON.parse(row.detail)?.time : '' }}</div>
<div>{{ await $getdata('Email_Template', {id:JSON.parse(row.detail)?.emailTemplate})}}</div> -->
