<template>
  <div class="toptitle text-dark col-12 row items-center">
    ตั้งค่าเว็บไซต์ระบบสรรหา
  </div>
  <q-card flat bordered class="q-mt-sm q-pa-md">
    <div class="col-12 row">
      <q-card flat bordered class="col-12 q-pa-md">
        <div class="flex items-center q-pb-md">
          <q-icon
            name="mdi-image-album"
            size="1.5em"
            color="grey-5"
            class="q-mr-md"
          />
          <div class="text-bold text-subtitle2 col-12 row items-center">
            รูปภาพ
          </div>
        </div>
        <div class="row q-col-gutter-x-md">
          <div class="col-xs-12 col-sm-4">
            <q-card bordered>
              <q-img
                class="rounded-borders"
                :src="
                  imageUrlLogo !== null
                    ? imageUrlLogo
                    : 'https://cdn.quasar.dev/img/image-src.png'
                "
                style="height: 280px"
              >
                <div class="absolute-bottom text-body1 text-center">
                  โลโก้เว็บไซต์
                </div>
                <input
                  type="file"
                  style="display: none"
                  ref="inputImageLogo"
                  accept="image/*"
                  @change="uploadImageLogo"
                />
              </q-img>
            </q-card>
            <q-btn
              unelevated
              color="primary"
              size="md"
              :label="imageFileLogo !== null ? 'อัปโหลดโลโก้' : 'เพิ่มโลโก้'"
              class="full-width q-mt-sm"
              @click="clickImageLogo()"
              :icon="imageFileLogo !== null ? 'mdi-cloud-upload' : 'mdi-plus'"
              style="width: 180px"
              :disable="statusHeader()"
            />
          </div>
          <div class="col-xs-12 col-sm-8">
            <q-card bordered>
              <q-img
                class="rounded-borders full-width"
                :src="
                  imageUrl !== null
                    ? imageUrl
                    : 'https://cdn.quasar.dev/img/image-src.png'
                "
                style="height: 280px"
              >
                <div class="absolute-bottom text-body1 text-center">
                  แบนเนอร์หน้าหลัก
                </div>
                <input
                  type="file"
                  style="display: none"
                  ref="inputImage"
                  accept="image/*"
                  @change="uploadImage"
                />
              </q-img>
            </q-card>
            <q-btn
              unelevated
              color="blue"
              size="md"
              :label="imageFile !== null ? 'อัปโหลดแบนเนอร์' : 'เพิ่มแบนเนอร์'"
              class="full-width q-mt-sm"
              @click="clickImage()"
              :icon="imageFile !== null ? 'mdi-cloud-upload' : 'mdi-plus'"
              :disable="statusHeader()"
            />
          </div>
        </div>
      </q-card>
      <q-card flat bordered class="col-12 q-pa-md q-mt-md">
        <div class="col-12">
          <q-form class="col-12 q-col-gutter-y-sm" ref="webform">
            <HeaderTop
              v-model:edit="enable.web"
              header="รายละเอียดเว็บ"
              icon="public"
              :save="sendDataDetail"
              :history="false"
              :cancel="cancelBlog"
              :disable="statusHeader()"
              class="q-pt-sm"
            />
            <!-- :disable="true" -->
            <q-input
              v-model="web.thai"
              :class="getClass(enable.web)"
              hide-bottom-space
              :outlined="enable.web"
              dense
              lazy-rules
              :readonly="!enable.web"
              :borderless="!enable.web"
              :rules="[(val) => !!val || `${'กรุณากรอก ชื่อเว็บภาษาไทย'}`]"
              label="ชื่อเว็บภาษาไทย"
            />
            <q-input
              v-model="web.eng"
              :class="getClass(enable.web)"
              hide-bottom-space
              :outlined="enable.web"
              dense
              lazy-rules
              :readonly="!enable.web"
              :borderless="!enable.web"
              :rules="[(val) => !!val || `${'กรุณากรอก ชื่อเว็บภาษาอังกฤษ'}`]"
              label="ชื่อเว็บภาษาอังกฤษ"
            />
            <q-input
              v-model="web.by"
              :class="getClass(enable.web)"
              hide-bottom-space
              :outlined="enable.web"
              dense
              lazy-rules
              :readonly="!enable.web"
              :borderless="!enable.web"
              :rules="[(val) => !!val || `${'กรุณากรอก ผู้จัดโดย'}`]"
              label="ผู้จัดโดย"
            />
            <q-input
              v-model="web.descripstion"
              :class="getClass(enable.web)"
              hide-bottom-space
              :outlined="enable.web"
              dense
              autogrow
              lazy-rules
              :readonly="!enable.web"
              :borderless="!enable.web"
              :rules="[(val) => !!val || `${'กรุณากรอก ข้อมูลเว็บโดยย่อ'}`]"
              label="ข้อมูลเว็บโดยย่อ"
            />
          </q-form>
        </div>
      </q-card>

      <q-card flat bordered class="col-12 q-px-md q-pb-md q-mt-md">
        <q-form
          ref="myform"
          class="col-12 q-col-gutter-sm row rounded-borders bg-white q-mt-sm"
        >
          <HeaderTop
            v-model:edit="enable.about"
            header="ข้อมูลเกี่ยวกับเรา"
            icon="feed"
            :save="sendDataAbout"
            :history="false"
            :cancel="cancelBlog"
            :disable="statusHeader()"
          />
          <div class="col-xs-12">
            <q-editor
              v-model="qeditor"
              :dense="$q.screen.lt.md"
              :readonly="!enable.about"
              :disable="!enable.about"
              toolbar-text-color="blue-grey-10"
              toolbar-bg="blue-grey-2"
              toolbar-toggle-color="blue-grey-8"
              class="editor"
              :toolbar="[
                ['left', 'center', 'right', 'justify'],
                [
                  'bold',
                  'italic',
                  'strike',
                  'underline',
                  'subscript',
                  'superscript',
                ],
                ['token', 'hr', 'link', 'custom_btn'],
                ['print', 'fullscreen'],
                [
                  {
                    label: $q.lang.editor.formatting,
                    icon: $q.iconSet.editor.formatting,
                    list: 'no-icons',
                    options: ['p', 'h1', 'h2', 'h3'],
                  },

                  {
                    label: $q.lang.editor.defaultFont,
                    icon: $q.iconSet.editor.font,
                    fixedIcon: true,
                    list: 'no-icons',
                    options: [
                      'default_font',
                      'arial',
                      'arial_black',
                      'comic_sans',
                      'courier_new',
                      'impact',
                      'lucida_grande',
                      'times_new_roman',
                      'verdana',
                    ],
                  },
                  'removeFormat',
                ],

                ['undo', 'redo'],
                ['viewsource'],
              ]"
              :fonts="{
                arial: 'Arial',
                arial_black: 'Arial Black',
                comic_sans: 'Comic Sans MS',
                courier_new: 'Courier New',
                impact: 'Impact',
                lucida_grande: 'Lucida Grande',
                times_new_roman: 'Times New Roman',
                verdana: 'Verdana',
              }"
            />
          </div>
          <div class="col-xs-12">
            <q-separator size="3px" color="grey-2" class="q-my-sm" />
          </div>
          <div class="col-xs-12">
            <q-input
              :class="getClass(enable.about)"
              hide-bottom-space
              :outlined="enable.about"
              dense
              lazy-rules
              autogrow
              :readonly="!enable.about"
              :borderless="!enable.about"
              v-model="address.address"
              :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่'}`]"
              :label="`${'ที่อยู่'}`"
            />
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-select
              hide-bottom-space
              :class="getClass(enable.about)"
              :readonly="!enable.about"
              :borderless="!enable.about"
              :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.provinceId"
              emit-value
              map-options
              option-label="name"
              :options="provinceOptions"
              option-value="id"
              :label="`${'จังหวัด'}`"
              @update:model-value="(value) => selectProvince(value)"
            />
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-select
              hide-bottom-space
              :class="getClass(enable.about)"
              :readonly="!enable.about"
              :borderless="!enable.about"
              :rules="[(val) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.districtId"
              emit-value
              map-options
              option-label="name"
              :options="districtOptions"
              option-value="id"
              :label="`${'เขต / อำเภอ'}`"
              @update:model-value="(value) => selectDistrict(value)"
            />
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-select
              hide-bottom-space
              :class="getClass(enable.about)"
              :readonly="!enable.about"
              :borderless="!enable.about"
              :rules="[(val) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.subdistrictId"
              emit-value
              map-options
              option-label="name"
              :options="subdistrictOptions"
              option-value="id"
              :label="`${'ตำบล / แขวง'}`"
              @update:model-value="(value) => selectSubDistrict(value)"
            />
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-input
              :class="getClass(enable.about)"
              hide-bottom-space
              dense
              lazy-rules
              readonly
              borderless
              v-model="address.code"
              :style="!enable.about ? '' : 'padding:0 12px;'"
              :label="`${'รหัสไปรษณีย์'}`"
            />
          </div>
          <div class="col-12">
            <q-input
              hide-bottom-space
              :outlined="enable.about"
              dense
              type="tel"
              lazy-rules
              :class="getClass(enable.about)"
              :readonly="!enable.about"
              v-model="address.tel"
              :borderless="!enable.about"
              :rules="[
                (val) => !!val || `${'กรุณากรอก เบอร์โทร'}`,
                (val) =>
                  val.length >= 10 || `${'กรุณากรอกข้อมูลเบอร์โทรให้ครบ'}`,
              ]"
              :label="`${'เบอร์โทร'}`"
              mask="##########"
            />
          </div>
        </q-form>
      </q-card>

      <q-card flat bordered class="col-12 q-pa-md q-mt-md">
        <div class="col-12 rounded-borders bg-white">
          <ProfileTable
            :rows="cmsGoverment"
            :columns="columns"
            :filter="filter"
            :visible-columns="visibleColumns"
            v-model:inputfilter="filter"
            v-model:inputvisible="visibleColumns"
            :add="() => clickAdd(false)"
            name="ส่วนราชการ"
            icon="mdi-book"
            :statusEdit="statusHeader()"
          >
            <template #columns="props">
              <q-tr :props="props">
                <q-td
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  @click="selectData(props.row.id, false)"
                  class="cursor-pointer"
                >
                  <div v-if="col.name == 'createdAt'" class="">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else-if="col.name == 'lastUpdatedAt'" class="">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else class="">
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </ProfileTable>
        </div>
      </q-card>

      <q-card flat bordered class="col-12 q-px-md q-pb-md q-mt-md">
        <div class="col-12 rounded-borders bg-white q-mt-md">
          <ProfileTable
            :rows="cmsAgency"
            :columns="columns"
            :filter="filterAgency"
            :visible-columns="visibleColumnsAgency"
            v-model:inputfilter="filterAgency"
            v-model:inputvisible="visibleColumnsAgency"
            :add="() => clickAdd(true)"
            name="หน่วยงาน"
            icon="mdi-book"
            :statusEdit="statusHeader()"
          >
            <template #columns="props">
              <q-tr :props="props">
                <q-td
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  @click="selectData(props.row.id, true)"
                  class="cursor-pointer"
                >
                  <div v-if="col.name == 'createdAt'" class="">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else-if="col.name == 'lastUpdatedAt'" class="">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else class="">
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </ProfileTable>
        </div>
      </q-card>
    </div>
  </q-card>
  <q-dialog v-model="dialog" persistent>
    <q-card style="width: 600px">
      <q-card-section class="row items-center col-12 q-py-sm">
        <div class="row col-11">
          <div class="text-bold">{{ title }}</div>
        </div>
        <q-space />
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="clickClose"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-card-section>
      <q-separator />
      <q-card-section class="q-p-sm">
        <q-form ref="dialogform" class="q-col-gutter-md">
          <q-input
            v-model="inputName"
            :class="getClass(editvisible)"
            hide-bottom-space
            :outlined="editvisible"
            dense
            lazy-rules
            :readonly="!editvisible"
            :borderless="!editvisible"
            :rules="[(val) => !!val || `${'กรุณากรอก ฃื่อ'}`]"
            label="ฃื่อ"
          />
          <q-input
            v-model="inputLink"
            :class="getClass(editvisible)"
            hide-bottom-space
            :outlined="editvisible"
            dense
            lazy-rules
            :readonly="!editvisible"
            :borderless="!editvisible"
            :rules="[(val) => !!val || `${'กรุณากรอก ลิ้งค์'}`]"
            label="ลิ้งค์"
          />
        </q-form>
      </q-card-section>
      <q-separator />
      <q-card-actions class="text-primary q-py-sm" v-if="addDialog == false">
        <q-btn
          flat
          round
          icon="mdi-menu-left"
          @click="clickPreviousNext('next')"
          :disable="previous == false"
          :color="!previous ? 'grey-7' : 'public'"
        />
        <q-btn
          flat
          round
          icon="mdi-menu-right"
          @click="clickPreviousNext('previous')"
          :disable="next == false"
          :color="!next ? 'grey-7' : 'public'"
        />
        <q-space />
        <q-btn
          v-if="!editvisible"
          flat
          round
          :disabled="editvisible"
          :color="editvisible ? 'grey-7' : 'red'"
          @click="saveDelete()"
          icon="mdi-delete-outline"
        >
          <q-tooltip>ลบข้อมูล</q-tooltip>
        </q-btn>
        <q-btn
          v-if="!editvisible"
          flat
          round
          :disabled="editvisible"
          :color="editvisible ? 'grey-7' : 'primary'"
          @click="editDialog()"
          icon="mdi-pencil-outline"
        >
          <q-tooltip>แก้ไขข้อมูล</q-tooltip>
        </q-btn>
        <div v-else>
          <q-btn
            flat
            round
            :disabled="!editvisible"
            :outline="!editvisible"
            :color="!editvisible ? 'grey-7' : 'red'"
            @click="editDialog()"
            icon="mdi-undo"
          >
            <q-tooltip>ยกเลิก</q-tooltip>
          </q-btn>
          <q-btn
            flat
            round
            :disabled="!editvisible"
            :color="!editvisible ? 'grey-7' : 'public'"
            @click="saveEdit"
            icon="mdi-content-save-outline"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </div>
      </q-card-actions>
      <q-card-actions class="text-primary q-py-sm" v-else>
        <q-space />
        <q-btn
          flat
          round
          color="public"
          @click="saveAdd"
          icon="mdi-content-save-outline"
        >
          <q-tooltip>บันทึก</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { ref, onMounted } from "vue";
import type {
  WebType,
  AddressWeb,
  DataOption,
  zipCodeOption,
  EnableType,
  CmsTable,
} from "@/modules/03_recruiting/interface/index/Main";
import type { Columns } from "@/modules/03_recruiting/interface/request/Career";
import type { DataLink } from "@/modules/03_recruiting/interface/request/Editor";
import type { QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import HeaderTop from "@/modules/04_registry/components/Information/top.vue";
import ProfileTable from "@/modules/04_registry/components/Table.vue";

import { useQuasar } from "quasar";

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง

const { date2Thai, messageError, showLoader, hideLoader } = mixin;
const previous = ref<boolean>(false);
const next = ref<boolean>(false);
const addDialog = ref<boolean>(false);
const imageUrl = ref<any>(null);
const imageFile = ref<any>(null);
const inputImage = ref<any>(null);
const imageUrlLogo = ref<any>(null);
const imageFileLogo = ref<any>(null);
const inputImageLogo = ref<any>(null);
const myform = ref<QForm | null>(null);
const webform = ref<QForm | null>(null);
const dialogform = ref<QForm | null>(null);
const idRow = ref<string | null>("");
const indexRow = ref<number>(0);
const agencyRow = ref<boolean>(false);
const inputLink = ref<string | null>("");
const inputName = ref<string | null>("");
const editvisible = ref<boolean>(false);
const dialog = ref<boolean>(false);
const edit = ref<boolean>(false);
const qeditor = ref<string>("");
const title = ref<string>("");
const filter = ref<string>(""); //search data table
const filterAgency = ref<string>(""); //search data table
const provinceOptions = ref<DataOption[]>([]);
const districtOptions = ref<DataOption[]>([]);
const subdistrictOptions = ref<zipCodeOption[]>([]);
const cmsGoverment = ref<CmsTable[]>([]);
const cmsAgency = ref<CmsTable[]>([]);
const web = ref<WebType>({
  by: "",
  thai: "",
  eng: "",
  descripstion: "",
});
const address = ref<AddressWeb>({
  address: null,
  provinceId: null,
  districtId: null,
  subdistrictId: null,
  tel: null,
  code: null,
});
const enable = ref<EnableType>({
  photo: false,
  web: false,
  about: false,
});
const visibleColumns = ref<String[]>([
  "name",
  "link",
  "createdAt",
  "lastUpdatedAt",
]);
const visibleColumnsAgency = ref<String[]>([
  "name",
  "link",
  "createdAt",
  "lastUpdatedAt",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "link",
    align: "left",
    label: "ลิ้งค์",
    sortable: true,
    field: "link",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้าง",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "ว้นที่แก้ไขล่าสุด",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

onMounted(async () => {
  await fetchData();
  await fetchProvince();
  await fetchDistrict(address.value.provinceId);
  await fetchSubDistrict(address.value.districtId);
});

const clickPreviousNext = (page: string) => {
  const index: number =
    page == "next" ? indexRow.value - 1 : indexRow.value + 1;
  let length: number;
  editvisible.value = false;
  if (agencyRow.value) {
    inputLink.value = cmsAgency.value[index].link;
    inputName.value = cmsAgency.value[index].name;
    idRow.value = cmsAgency.value[index].id;
    length = cmsAgency.value.length;
  } else {
    inputLink.value = cmsGoverment.value[index].link;
    inputName.value = cmsGoverment.value[index].name;
    idRow.value = cmsGoverment.value[index].id;
    length = cmsGoverment.value.length;
  }

  previous.value = index == 0 ? false : true;
  next.value = index == length - 1 ? false : true;
  indexRow.value = index;
};

const selectData = (id: string, agency: boolean) => {
  dialog.value = !dialog.value;
  addDialog.value = false;
  editvisible.value = false;
  agencyRow.value = agency;
  title.value = agency ? "แก้ไขหน่วยงาน" : "แก้ไขส่วนราชการ";
  let length: number;
  let index: number;
  if (agency) {
    index = cmsAgency.value.findIndex((r: any) => r.id == id);
    length = cmsAgency.value.length;
    inputLink.value = cmsAgency.value[index].link;
    inputName.value = cmsAgency.value[index].name;
    idRow.value = cmsAgency.value[index].id;
  } else {
    index = cmsGoverment.value.findIndex((r: any) => r.id == id);
    length = cmsGoverment.value.length;

    inputLink.value = cmsGoverment.value[index].link;
    inputName.value = cmsGoverment.value[index].name;
    idRow.value = cmsGoverment.value[index].id;
  }
  indexRow.value = index;
  previous.value = index == 0 ? false : true;
  next.value = index == length - 1 ? false : true;
};

const editDialog = () => {
  editvisible.value = !editvisible.value;
};

const clickClose = () => {
  dialog.value = !dialog.value;
  addDialog.value = false;
};

const clickAdd = (agency: boolean) => {
  dialog.value = !dialog.value;
  title.value = agency ? "เพิ่มหน่วยงาน" : "เพิ่มส่วนราชการ";
  agencyRow.value = agency;
  addDialog.value = true;
  editvisible.value = true;
  inputLink.value = "";
  inputName.value = "";
};

const statusHeader = () => {
  return Object.values(enable.value).includes(true);
};

const cancelBlog = async () => {
  await fetchData();
};

const saveAdd = async () => {
  dialogform.value?.validate().then(async (result: boolean) => {
    if (result) {
      if (agencyRow.value) {
        let arrData: DataLink[] = [];
        cmsAgency.value.map((r: any) => {
          arrData.push({
            name: r.name,
            link: r.link,
          });
        });
        arrData.push({
          name: inputName.value,
          link: inputLink.value,
        });
        await saveDataAgency(arrData);
        dialog.value = false;
      } else {
        let arrData: DataLink[] = [];
        cmsGoverment.value.map((r: any) => {
          arrData.push({
            name: r.name,
            link: r.link,
          });
        });
        arrData.push({
          name: inputName.value,
          link: inputLink.value,
        });
        await saveDataGoverment(arrData);
        dialog.value = false;
      }
    }
  });
};

const saveDelete = async () => {
  if (agencyRow.value) {
    const filt = cmsAgency.value.filter((r: any) => r.id != idRow.value);
    let arrData: DataLink[] = [];
    filt.map((r: any) => {
      arrData.push({
        name: r.name,
        link: r.link,
      });
    });
    await saveDataAgency(arrData);
    dialog.value = false;
  } else {
    const filt = cmsGoverment.value.filter((r: any) => r.id != idRow.value);
    let arrData: DataLink[] = [];
    filt.map((r: any) => {
      arrData.push({
        name: r.name,
        link: r.link,
      });
    });
    await saveDataGoverment(arrData);
    dialog.value = false;
  }
};

const saveEdit = async () => {
  if (agencyRow.value) {
    let arrData: DataLink[] = [];
    cmsAgency.value.map((r: any) => {
      if (r.id == idRow.value) {
        arrData.push({
          name: inputName.value,
          link: inputLink.value,
        });
      } else {
        arrData.push({
          name: r.name,
          link: r.link,
        });
      }
    });
    await saveDataAgency(arrData);
    dialog.value = false;
  } else {
    let arrData: DataLink[] = [];
    cmsGoverment.value.map((r: any) => {
      if (r.id == idRow.value) {
        arrData.push({
          name: inputName.value,
          link: inputLink.value,
        });
      } else {
        arrData.push({
          name: r.name,
          link: r.link,
        });
      }
    });
    await saveDataGoverment(arrData);
    dialog.value = false;
  }
};

const saveDataAgency = async (data: DataLink[]) => {
  showLoader();
  await http
    .post(config.API.cmsAgency, data)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

const saveDataGoverment = async (data: DataLink[]) => {
  showLoader();

  await http
    .post(config.API.cmsGoverment, data)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.cms)
    .then((res) => {
      const data = res.data.result;
      web.value.eng = data.nameEn;
      web.value.thai = data.nameTh;
      web.value.by = data.shortName;
      web.value.descripstion = data.description;
      qeditor.value = data.about;
      address.value.address = data.address;
      address.value.tel = data.telephone;
      address.value.code = data.zipCode;
      if (data.bannerImg) {
        imageUrl.value = data.bannerImg.detail;
      }
      if (data.logoImg) {
        imageUrlLogo.value = data.logoImg.detail;
      }
      address.value.provinceId = data.provinceId;
      address.value.districtId = data.districtId;
      address.value.subdistrictId = data.subDistrictId;

      if (data.cmsGovernments.length > 0) {
        let setData: CmsTable[] = [];
        data.cmsGovernments.map((r: CmsTable) => {
          setData.push({
            id: r.id,
            name: r.name,
            link: r.link,
            createdAt: r.createdAt,
            lastUpdatedAt: r.lastUpdatedAt,
          });
        });
        cmsGoverment.value = setData;
      }

      if (data.cmsAgencys.length > 0) {
        let setData: CmsTable[] = [];
        data.cmsAgencys.map((r: CmsTable) => {
          setData.push({
            id: r.id,
            name: r.name,
            link: r.link,
            createdAt: r.createdAt,
            lastUpdatedAt: r.lastUpdatedAt,
          });
        });
        cmsAgency.value = setData;
      }
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const takeLogo = async () => {
  showLoader();
  const formData = new FormData();
  formData.append("FileData", imageFileLogo.value);
  await http
    .post(config.API.cmsLogo, formData)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      imageFileLogo.value = null;
      imageUrlLogo.value = null;
      await fetchData();
    });
};

const takeBanner = async () => {
  showLoader();
  const formData = new FormData();
  formData.append("FileData", imageFile.value);
  await http
    .post(config.API.cmsBanner, formData)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      imageFile.value = null;
      imageUrl.value = null;
      await fetchData();
    });
};

const sendDataDetail = async () => {
  webform.value?.validate().then(async (result: boolean) => {
    if (result) {
      const data = {
        nameTh: web.value.thai,
        nameEn: web.value.eng,
        description: web.value.descripstion,
        shortName: web.value.by,
      };
      showLoader();
      await http
        .post(config.API.cmsDeatail, data)
        .then((res) => {})
        .catch((e: any) => {
          messageError($q, e);
        })
        .finally(async () => {
          await fetchData();
          enable.value.web = false;
        });
    }
  });
};

const sendDataAbout = async () => {
  myform.value?.validate().then(async (result: boolean) => {
    if (result) {
      const data = {
        about: qeditor.value,
        address: address.value.address,
        provinceId: address.value.provinceId,
        districtId: address.value.districtId,
        subDistrictId: address.value.subdistrictId,
        zipCode: address.value.code,
        telephone: address.value.tel,
      };
      showLoader();
      await http
        .post(config.API.cmsAbout, data)
        .then((res) => {})
        .catch((e: any) => {
          messageError($q, e);
        })
        .finally(async () => {
          await fetchData();
          enable.value.about = false;
        });
    }
  });
};

const fetchProvince = async () => {
  showLoader();
  await http
    .get(config.API.province)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      provinceOptions.value = option;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchDistrict = async (id: string | null) => {
  if (id !== null && id != "") {
    showLoader();
    await http
      .get(config.API.listDistrict(id))
      .then((res) => {
        const data = res.data.result;
        let option: DataOption[] = [];
        data.map((r: any) => {
          option.push({ id: r.id.toString(), name: r.name.toString() });
        });
        districtOptions.value = option;
      })
      .catch((e: any) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const fetchSubDistrict = async (id: string | null) => {
  if (id !== null && id != "") {
    showLoader();
    await http
      .get(config.API.listSubDistrict(id))
      .then((res) => {
        const data = res.data.result;
        let option: zipCodeOption[] = [];
        data.map((r: any) => {
          option.push({
            id: r.id.toString(),
            name: r.name.toString(),
            zipCode: r.zipCode.toString(),
          });
        });
        subdistrictOptions.value = option;
      })
      .catch((e: any) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const selectProvince = (e: string) => {
  address.value.districtId = "";
  address.value.subdistrictId = "";
  address.value.code = "";
  myform.value?.resetValidation();
  fetchDistrict(e);
};

const selectDistrict = (e: string) => {
  address.value.subdistrictId = "";
  address.value.code = "";

  myform.value?.resetValidation();
  fetchSubDistrict(e);
};

const selectSubDistrict = (e: string) => {
  const findcode = subdistrictOptions.value.filter((r: any) => r.id == e);
  const namecode = findcode.length > 0 ? findcode[0].zipCode : "";
  address.value.code = namecode;
};

const clickImageLogo = () => {
  if (imageFileLogo.value !== null) {
    takeLogo();
  } else {
    inputImageLogo.value.click();
  }
};

const clickImage = () => {
  if (imageFile.value !== null) {
    takeBanner();
  } else {
    inputImage.value.click();
  }
};

const uploadImageLogo = (e: any) => {
  let input = e.target.files;
  if (input.length > 0) {
    const formData = new FormData();
    formData.append("FileData", input[0]);

    imageFileLogo.value = input[0];
    imageUrlLogo.value = URL.createObjectURL(input[0]);
    return;
  }
  return;
};

const uploadImage = (e: any) => {
  let input = e.target.files;
  if (input.length > 0) {
    const formData = new FormData();
    formData.append("FileData", input[0]);

    imageFile.value = input[0];
    imageUrl.value = URL.createObjectURL(input[0]);
    return;
  }
  return;
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<style lang="scss" scoped>
.my-content {
  padding: 20px 15px;
  border: 1px solid rgba(#999, 0.2);
}
</style>
