<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";
import { usePersonalDataStore } from "@/modules/01_metadata/stores/personalStore";
import { useQuasar } from "quasar";
import DialogForm from "@/modules/01_metadata/components/personal/DialogForm.vue";
import http from "@/plugins/http";
import config from "@/app.config";

import type { FormDistrict } from "@/modules/01_metadata/interface/response/personal/personal";

const router = useRouter();
const route = useRoute();
const id = ref<string>(route.params.id as string);
const store = usePersonalDataStore();
const mixin = useCounterMixin();
const {
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
  date2Thai,
} = mixin;
const 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: "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" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
] as const satisfies QTableProps["columns"];

const $q = useQuasar();
const editId = ref<string>("");
const filterKeyword = ref<string>("");
const dialog = ref<boolean>(false);
const district = ref<string>("");
const rows = ref<FormDistrict[]>([]);

const dialogStatus = ref<string>("");
const personalName = ref<string>("เขต/อำเภอ");
const visibleColumns = ref<string[]>([
  "name",
  "createdAt",
  "lastUpdatedAt",
  "lastUpdateFullName",
]);

async function fetchData() {
  showLoader();
  await http
    .get(config.API.orgProvince + `/${id.value}`)
    .then(async (res) => {
      const data = res.data.result.districts;
      const list = data.map((e: any) => ({
        ...e,
        createdAt: e.createdAt ? date2Thai(e.createdAt) : "",
        lastUpdatedAt: e.lastUpdatedAt ? date2Thai(e.lastUpdatedAt) : "",
      }));
      rows.value = list;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function addData() {
  await http
    .post(config.API.orgDistrict, {
      name: district.value,
      provinceId: id.value,
    })
    .then(() => {
      fetchData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function editData(id: string) {
  await http
    .put(config.API.orgDistrict + `/${id}`, {
      name: district.value,
    })
    .then(() => {
      fetchData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function deleteData(id: string) {
  await http
    .delete(config.API.orgDistrict + `/${id}`)
    .then(() => {
      fetchData();
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function nextPage(idSub: string) {
  router.push(`/master-data/personal/sub-district/${id.value}/${idSub}`);
}

onMounted(async () => {
  fetchData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.go(-1)"
    />
    เขต/อำเภอ
  </div>

  <q-card flat bordered>
    <div class="q-pa-md">
      <q-toolbar class="q-pa-none">
        <q-btn
          flat
          round
          color="primary"
          icon="add"
          @click.stop="
            () => {
              dialogStatus = 'create';
              dialog = true;
              district = '';
            }
          "
        >
          <q-tooltip> เพิ่มข้อมูล </q-tooltip>
        </q-btn>
        <q-space />
        <div class="row q-gutter-sm">
          <q-input
            outlined
            dense
            v-model="filterKeyword"
            label="ค้นหา"
          ></q-input>
          <q-select
            v-model="visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            options-cover
            style="min-width: 150px"
          />
        </div>
      </q-toolbar>

      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        :filter="filterKeyword"
        row-key="name"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        :visible-columns="visibleColumns"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width />
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td auto-width>
              <q-btn
                color="edit"
                flat
                dense
                round
                class="q-mr-xs"
                size="12px"
                icon="edit"
                clickable
                @click.stop="
                  () => {
                    dialogStatus = 'edit';
                    dialog = true;
                    editId = props.row.id;
                    district = props.row.name;
                  }
                "
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <q-btn
                color="red"
                flat
                dense
                round
                size="12px"
                icon="mdi-delete"
                clickable
                @click.stop="
                  dialogRemove($q, async () => await deleteData(props.row.id))
                "
                v-close-popup
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
            <q-td
              v-for="col in props.cols"
              :key="col.id"
              @click="nextPage(props.row.id)"
            >
              <div>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogForm
    v-model:dialog="dialog"
    v-model:data="district"
    v-model:personalName="personalName"
    v-model:dialogStatus="dialogStatus"
    v-model:editId="editId"
    :addData="addData"
    :fetch-data="fetchData"
    :edit-data="editData"
  />
</template>
