<template>
  <div v-if="record">
    <div class="columns is-multiline mx-0">
      <div :class="`column is-3 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("code") }}<b class="ml-1 has-text-danger">*</b></label>
          <div class="control">
            <input
              class="input has-text-black"
              disabled
              type="text"
              placeholder=""
              v-model="record.code"
            />
          </div>
          <p
            class="help is-danger"
            v-if="errors.code"
          >
            {{ errors.code }}
          </p>
        </div>
      </div>

      <div :class="`column is-6 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">Tên công ty<b class="ml-1 has-text-danger">*</b></label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.fullname"
            />
          </div>
          <p
            class="help is-danger"
            v-if="errors.fullname"
          >
            {{ errors.fullname }}
          </p>
        </div>
      </div>
      <div :class="`column is-3 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("shortname") }}</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.shortname"
            />
          </div>
          <p
            class="help is-danger"
            v-if="errors.shortname"
          >
            {{ errors.shortname }}
          </p>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("taxcode") }}</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.legal_code"
            />
          </div>
          <p
            class="help is-danger"
            v-if="errors.legal_code"
          >
            {{ errors.legal_code }}
          </p>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">Điện thoại</label>
          <div class="control">
            <InputPhone
              v-bind="{ record: record, attr: 'phone', placeholder: '' }"
              @phone="selected('phone', $event)"
            ></InputPhone>
          </div>
          <p
            class="help is-danger"
            v-if="errors.phone"
          >
            {{ errors.phone }}
            <a
              v-if="existedCustomer"
              @click="showCustomer()"
              >Chi tiết</a
            >
          </p>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">Email</label>
          <div class="control">
            <InputEmail
              v-bind="{ record: record, attr: 'email', placeholder: '' }"
              @email="selected('email', $event)"
            ></InputEmail>
          </div>
          <p
            class="help is-danger"
            v-if="errors.email"
          >
            {{ errors.email }}
          </p>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">Website</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.website"
            />
          </div>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("country") }}</label>
          <div class="control">
            <SearchBox
              v-bind="{
                vdata: store.country,
                field: 'name',
                column: ['name'],
                first: true,
                optionid: record.country,
                position: 'is-top-left',
              }"
              @option="selected('_country', $event)"
            ></SearchBox>
          </div>
        </div>
      </div>
      <div :class="`column is-4 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("province") }}</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.province"
            />
          </div>
        </div>
      </div>
      <div :class="`column is-12 ${viewport === 1 ? 'px-0 pb-1' : ''}`">
        <div class="field">
          <label class="label">{{ findLang("address") }}</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="record.address"
            />
          </div>
          <p
            class="help is-danger"
            v-if="errors.address"
          ></p>
        </div>
      </div>
    </div>
    <div class="mt-2">
      <button
        class="button is-primary has-text-white"
        @click="update()"
      >
        {{ findLang("save") }}
      </button>
    </div>
    <Modal
      @close="showmodal = undefined"
      v-bind="showmodal"
      v-if="showmodal"
    ></Modal>
  </div>
</template>
<script setup>
import InputPhone from "~/components/common/InputPhone";
import InputEmail from "~/components/common/InputEmail";
import SearchBox from "~/components/SearchBox";
var props = defineProps({
  pagename: String,
  row: Object,
});
const store = useStore();
const { $find, $getdata, $patchapi, $insertapi, $findapi, $getapi, $empty, $errPhone, $resetNull, $snackbar } =
  useNuxtApp();
const emit = defineEmits(["update", "dataevent"]);
var viewport = store.viewport;
var errors = ref({});
var record = ref();
var showmodal = undefined;
var existedCustomer = undefined;
async function initData() {
  if (props.row) {
    let conn = $findapi("company");
    conn.params.filter = {
      id: props.row.company || props.row.customer__company || props.row.id,
    };
    let rs = await $getapi([conn]);
    let found = $find(rs, { name: "company" });
    if (found.data.rows.length > 0) record.value = found.data.rows[0];
  } else {
    record.value = {};
  }
}
function findLang(code) {
  let found = $find(store.common, { code: code });
  return found ? found[store.lang] : "";
}
function showCustomer() {
  showmodal.value = {
    component: "customer/CustomerView",
    width: "60%",
    height: "600px",
    title: "Khách hàng",
    vbind: { row: existedCustomer },
  };
}
function selected(attr, obj) {
  record.value[attr] = obj;
}
function checkError() {
  existedCustomer = undefined;
  errors.value = {};
  if ($empty(record.value.fullname)) errors.value.fullname = "Họ tên không được bỏ trống";
  if (record.value.phone) {
    let text = $errPhone(record.value.phone);
    if (text) errors.value.phone = text;
  }
  return Object.keys(errors.value).length > 0;
}
async function update() {
  if (checkError()) return;
  if (!record.value.id) {
    if (record.value.phone) record.value.phone = record.value.phone.trim();
    const obj = await $getdata("company", {
      first: true,
      filter: { phone: record.value.phone },
    });
    if (obj) {
      existedCustomer = obj;
      errors.phone = "Số điện thoại đã tồn tại trong hệ thống.";
    }
  }
  record.value = $resetNull(record.value);
  if (record.value._country) record.value.country = record.value._country.id;
  if (!record.value.creator) record.value.creator = store.login.id;
  record.value.updater = store.login.id;
  record.update_time = new Date();
  let rs = record.value.id
    ? await $patchapi("company", record.value)
    : await $insertapi("company", { data: record.value });
  if (rs === "error") return;
  if (!record.value.id) $snackbar(`Khách hàng đã được khởi tạo với mã <b>${rs.code}</b>`, "Success");
  record.value.id = rs.id;
  let ele = await $getdata("company", {
    first: true,
    filter: { id: rs.id },
  });
  emit("update", ele);
  emit("modalevent", { name: "dataevent", data: ele });
}
initData();
</script>
