<script setup lang="ts">
import type { QTableProps } from "quasar";
import { checkPermission } from "@/utils/permissions";
import { ref, onMounted } from "vue";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

import type {
  WebType,
  AddressWeb,
  DataOption,
  zipCodeOption,
  EnableType,
  CmsTable,
} from "@/modules/03_recruiting/interface/index/Main";
import type { DataLink } from "@/modules/03_recruiting/interface/request/Editor";
import type { QForm } from "quasar";

import HeaderTop from "@/modules/03_recruiting/components/top1.vue";
import ProfileTable from "@/modules/03_recruiting/components/Table1.vue";

import { useQuasar } from "quasar";

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

const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  dialogRemove,
  onSearchDataTable,
} = 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 inputNameBack = ref<string | null>("");
const editvisible = ref<boolean>(false);
const dialog = 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 provinceOptionsMain = ref<DataOption[]>([]);
const provinceOptions = ref<DataOption[]>([]);
const districtOptionsMain = ref<DataOption[]>([]);
const districtOptions = ref<DataOption[]>([]);
const subdistrictOptionsMain = ref<zipCodeOption[]>([]);
const subdistrictOptions = ref<zipCodeOption[]>([]);
const cmsGoverment = ref<CmsTable[]>([]);
const cmsGovermentData = ref<CmsTable[]>([]);
const cmsAgency = ref<CmsTable[]>([]);
const cmsAgencyData = 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" }),
  },
]);

/**
 * ฟังชั่น หน้าถัดไป ย้อนกลับหน้า page
 * @param page next/previous
 */
function 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;
}

/**
 * ฟังชั่น เปิดรายละเอียด
 * @param id
 * @param agency
 */
function 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;
    inputNameBack.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;
    inputNameBack.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;
}

/** แก้ไขข้อมูล ส่วนราชการ/หน่วยงาน */
function editDialog() {
  inputName.value = inputNameBack.value;

  editvisible.value = !editvisible.value;
}

/** ปิด dialog ส่วนราชการ/หน่วยงาน */
function clickClose() {
  dialog.value = !dialog.value;
  addDialog.value = false;
}
/**
 * เปิด dialog ส่วนราชการ/หน่วยงาน
 * @param agency true/false
 */
function clickAdd(agency: boolean) {
  dialog.value = !dialog.value;
  title.value = agency ? "เพิ่มหน่วยงาน" : "เพิ่มส่วนราชการ";
  agencyRow.value = agency;
  addDialog.value = true;
  editvisible.value = true;
  inputLink.value = "";
  inputName.value = "";
}

/** เช็คสถานะ เปิด/ปิด เพิ่มข้อมูล */
function statusHeader() {
  return Object.values(enable.value).includes(true);
}

/** ปิด dialog ข้อมูลเกี่ยวกับเรา */
async function cancelBlog() {
  await fetchData();
}
/** save ข้อมูล */
async function saveAdd() {
  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;
      }
    }
  });
}

/** ลบข้อมูล */
async function saveDelete(del: string) {
  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, del);
    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, del);
    dialog.value = false;
  }
}

/** edit */
async function saveEdit() {
  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, "");
  }
}

/** save หน่วยงาน */
async function saveDataAgency(data: DataLink[], del: string) {
  dialogform.value?.validate().then(async (result: boolean) => {
    if (result) {
      if (del) {
        dialogRemove($q, () => dataPostAgency(data));
      } else {
        dialogConfirm($q, () => dataPostAgency(data));
      }
    }
  });
}

/** save ราชการ */
async function saveDataGoverment(data: DataLink[], del: string) {
  dialogform.value?.validate().then(async (result: boolean) => {
    if (result) {
      if (del) {
        dialogRemove($q, () => dataPost(data));
      } else {
        dialogConfirm($q, () => dataPost(data));
      }
    }
  });
}

/**
 * เพิ่มข้อมูล
 * @param data ข้อมูลหน่วยงาน
 */
async function dataPostAgency(data: DataLink[]) {
  showLoader();
  await http
    .post(config.API.cmsAgency, data)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      dialog.value = false;
      await fetchData();
    });
}

/**
 * เพิ่มข้อมูล
 * @param data ข้อมูลราชการ
 */
async function dataPost(data: DataLink[]) {
  showLoader();
  await http
    .post(config.API.cmsGoverment, data)
    .then((res) => {})
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      dialog.value = false;
      await fetchData();
    });
}

/** ดึงข้อมูลรายละเอียด */
async function fetchData() {
  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;
        checkFileBanner();
      }
      if (data.logoImg) {
        imageUrlLogo.value = data.logoImg.detail;
        checkFileLogo();
      }
      address.value.provinceId = data.provinceId;
      address.value.districtId = data.districtId;
      address.value.subdistrictId = data.subDistrictId;
      cmsGoverment.value = [];
      cmsGovermentData.value = [];
      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;
        cmsGovermentData.value = setData;
      }

      cmsAgency.value = [];
      cmsAgencyData.value = [];
      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;
        cmsAgencyData.value = setData;
      }
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เพิ่มโลโก้ */
async function takeLogo() {
  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();
    });
}

/** เพิ่ม banner */
async function takeBanner() {
  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();
    });
}

/** body รายละเอียด */
async function sendDataDetail() {
  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;
        });
    }
  });
}

/** body  ข้อมูลเกี่ยวกับเรา */
async function sendDataAbout() {
  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;
        });
    }
  });
}

/** ดึงข้อมูลก่อนหน้า dialog */
async function fetchProvince() {
  showLoader();
  await http
    .get(config.API.orgProvince)
    .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;
      provinceOptionsMain.value = option;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ดึงข้อมูล อำเภอ
 * @param id id อำเภอ
 */
async function fetchDistrict(id: string | null) {
  if (id !== null && id != "") {
    showLoader();
    await http
      .get(config.API.orgProvince + `/${id}`)
      .then((res) => {
        const data = res.data.result.districts;
        let option: DataOption[] = [];
        data.map((r: any) => {
          option.push({ id: r.id.toString(), name: r.name.toString() });
        });
        districtOptions.value = option;
        districtOptionsMain.value = option;
      })
      .catch((e: any) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * ดึงข้อมูล ตำบล
 * @param id id จังหวัด
 */
async function fetchSubDistrict(id: string | null) {
  if (id !== null && id != "") {
    showLoader();
    await http
      .get(config.API.orgDistrict + `/${id}`)
      .then((res) => {
        const data = res.data.result.subDistricts;
        let option: zipCodeOption[] = [];
        data.map((r: any) => {
          option.push({
            id: r.id.toString(),
            name: r.name.toString(),
            zipCode: r.zipCode.toString(),
          });
        });
        subdistrictOptions.value = option;
        subdistrictOptionsMain.value = option;
      })
      .catch((e: any) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * ฟังชั่นเลือกจังหวัด
 * @param e id จังหวัด
 */
function selectProvince(e: string) {
  address.value.districtId = "";
  address.value.subdistrictId = "";
  address.value.code = "";
  myform.value?.resetValidation();
  fetchDistrict(e);
}

/** เลือกอำเภอ */
function selectDistrict(e: string) {
  address.value.subdistrictId = "";
  address.value.code = "";

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

/** เลือกตำบล */
function 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;
}

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

/** อัปโหลดแบนเนอร์/โลโก้ */
function clickImage() {
  if (imageFile.value !== null) {
    takeBanner();
  } else {
    inputImage.value.click();
  }
}

const checkLogoExits = ref<boolean>(false);
/** เช็คโลโก้ */
async function checkFileLogo() {
  try {
    const response = await fetch(imageUrlLogo.value, { method: "GET" });
    checkLogoExits.value = response.ok;
  } catch (error) {
    checkLogoExits.value = false;
  }
}

const checkBannerExits = ref<boolean>(false);
/** เช็คแบนเนอร์ */
async function checkFileBanner() {
  try {
    const response = await fetch(imageUrl.value, { method: "GET" });
    checkBannerExits.value = response.ok;
  } catch (error) {
    checkBannerExits.value = false;
  }
}

/** อัปโหลดโลโก้ */
function 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;
}

/** อัปโหลดแบนเนอร์*/
function 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;
}

function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

function filterSelector(val: string, update: Function, refData: string) {
  switch (refData) {
    case "province":
      update(() => {
        provinceOptions.value = provinceOptionsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "district":
      update(() => {
        districtOptions.value = districtOptionsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "subdistrict":
      update(() => {
        subdistrictOptions.value = subdistrictOptionsMain.value.filter(
          (v: zipCodeOption) => v.name.indexOf(val) > -1
        );
      });
    default:
      break;
  }
}

function onSearch(type: string) {
  if (type == "ส่วนราชการ") {
    cmsGoverment.value = onSearchDataTable(
      filter.value,
      cmsGovermentData.value,
      columns.value ? columns.value : []
    );
  } else if (type == "หน่วยงาน") {
    cmsAgency.value = onSearchDataTable(
      filterAgency.value,
      cmsAgencyData.value,
      columns.value ? columns.value : []
    );
  }
}

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

<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 && checkLogoExits
                    ? 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
              v-if="checkPermission($route)?.attrIsUpdate"
              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 && checkBannerExits
                    ? 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
              v-if="checkPermission($route)?.attrIsUpdate"
              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"
            />
            <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:string) => !!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:string) => !!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:string) => !!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:string) => !!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:string) => !!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:string) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.provinceId"
              emit-value
              map-options
              option-label="name"
              :options="provinceOptions"
              option-value="id"
              :label="`${'จังหวัด'}`"
              use-input
              hide-selected
              fill-input
              @update:model-value="(value:string) => selectProvince(value)"
              @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'province'
              )"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-italic text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </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:string) => !!val || `${'กรุณาเลือกเขต/อำเภอ'}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.districtId"
              emit-value
              map-options
              option-label="name"
              :options="districtOptions"
              option-value="id"
              :label="`${'เขต / อำเภอ'}`"
              use-input
              hide-selected
              fill-input
              @update:model-value="(value:string) => selectDistrict(value)"
              @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'district'
              )"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-italic text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </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:string) => !!val || `${'กรุณาเลือกแขวง/ตำบล '}`]"
              :outlined="enable.about"
              dense
              lazy-rules
              v-model="address.subdistrictId"
              emit-value
              map-options
              option-label="name"
              :options="subdistrictOptions"
              option-value="id"
              :label="`${'แขวง/ตำบล'}`"
              use-input
              hide-selected
              fill-input
              @update:model-value="(value:string) => selectSubDistrict(value)"
              @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'subdistrict'
              )"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-italic text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template></q-select
            >
          </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:any) => !!val || `${'กรุณากรอก เบอร์โทร'}`,
                (val:any) =>
                  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"
            v-model:filter="filter"
            :onSearch="onSearch"
            :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 auto-width>
                  <q-btn
                    v-if="checkPermission($route)?.attrIsUpdate"
                    @click="selectData(props.row.id, false)"
                    flat
                    dense
                    round
                    color="primary"
                    icon="edit"
                  >
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <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"
            :onSearch="onSearch"
            :columns="columns"
            v-model: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 auto-width>
                  <q-btn
                    v-if="checkPermission($route)?.attrIsUpdate"
                    @click="selectData(props.row.id, true)"
                    flat
                    dense
                    round
                    color="primary"
                    icon="edit"
                  >
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <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:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
            label="ชื่อ"
          />
          <q-input
            v-model="inputLink"
            :class="getClass(editvisible)"
            hide-bottom-space
            :outlined="editvisible"
            dense
            lazy-rules
            :readonly="!editvisible"
            :borderless="!editvisible"
            :rules="[(val:string) => !!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('delect')"
          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>

<style lang="scss" scoped>
.my-content {
  padding: 20px 15px;
  border: 1px solid rgba(#999, 0.2);
}
</style>
