<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { QForm, useQuasar } from "quasar";
import dialogHeader from "@/components/DialogHeader.vue";
import { useCounterMixin } from "@/stores/mixin";
import type { RequestItemsObject } from "@/modules/04_registryNew/interface/request/SpecialSkill";
import type { ResponseObject } from "@/modules/04_registryNew/interface/response/SpecialSkill";
import type { QTableProps } from "quasar";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

const mixin = useCounterMixin();
const $q = useQuasar();
const mode = ref<string>("table");
const {
  dialogRemove,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
} = mixin;
const columns = ref<QTableProps["columns"]>([
  {
    name: "field",
    align: "left",
    label: "ด้าน",
    sortable: true,
    field: "field",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reference",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "reference",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const historyColumns = ref<QTableProps["columns"]>([
  {
    name: "field",
    align: "left",
    label: "ด้าน",
    sortable: true,
    field: "field",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reference",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "reference",
    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" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const historyDialog = ref<boolean>(false);
const dialog = ref<boolean>(false);
const dialogStatus = ref<string>("create");
const rows = ref<ResponseObject[]>([]);
const historyRows = ref<ResponseObject[]>([]);
const route = useRoute();
const id = ref<string>(route.params.id.toString());
const editId = ref<string>("");
const keyword = ref<string>("");
const historyKeyword = ref<string>("");

const specialSkill = reactive<RequestItemsObject>({
  field: "",
  detail: "",
  remark: "",
  reference: "",
  profileId: id.value,
  dateStart: null,
  dateEnd: null,
});

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<string[]>([
  "field",
  "detail",
  "remark",
  "reference",
]);

const historyVisibleColumns = ref<string[]>([
  "field",
  "detail",
  "remark",
  "reference",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
function closeDialog() {
  dialog.value = false;
}

function closeHistoryDialog() {
  historyDialog.value = false;
}

async function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      dialogStatus.value === "create" ? addData() : editData(editId.value);
      closeDialog();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

function clearForm() {
  specialSkill.detail = "";
  specialSkill.field = "";
  specialSkill.reference = "";
  specialSkill.remark = "";
}

function editForm(row: any) {
  dialogStatus.value = "edit";
  editId.value = row.id;
  specialSkill.detail = row.detail;
  specialSkill.field = row.field;
  specialSkill.reference = row.reference;
  specialSkill.remark = row.remark;
  dialog.value = true;
}

async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewAbilityByProfileId(id))
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchHistoryData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewAbilityHisByAbilityId(id))
    .then(async (res) => {
      historyRows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

async function editData(idData: string) {
  await http
    .patch(config.API.profileNewAbilityByAbilityId(idData), {
      ...specialSkill,
      dateStart: null,
      dateEnd: null,
      profileId: undefined,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

onMounted(async () => {
  await fetchData(id.value);
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      flat
      round
      color="primary"
      dense
      icon="add"
      @click="() => ((dialogStatus = 'create'), clearForm(), (dialog = true))"
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip>
    </q-btn>
    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา">
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>

    <q-select
      v-model="visibleColumns"
      multiple
      outlined
      v-if="mode === 'table'"
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      options-cover
      style="min-width: 150px"
    />
    <q-btn-toggle
      v-model="mode"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: mode === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: mode === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    :grid="mode === 'card'"
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    :filter="keyword"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    :visible-columns="visibleColumns"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
        <q-th auto-width />
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="mode === 'table'">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id">
          <div>{{ col.value ? col.value : "-" }}</div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @click="
              () => {
                editForm(props.row);
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="
              fetchHistoryData(props.row.id);
              historyDialog = true;
            "
          >
            <q-tooltip>ประวัติแก้ไขความสามารถพิเศษ</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div
        class="q-pa-xs col-xs-12 col-sm-6 col-md-6 col-lg-6 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              flat
              round
              color="primary"
              icon="mdi-pencil-outline"
              size="14px"
              @click="
                () => {
                  editForm(props.row);
                }
              "
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              class="no-shadow toggle-borderd"
              round
              size="14px"
              color="info"
              icon="mdi-history"
              @click="
                fetchHistoryData(props.row.id);
                historyDialog = true;
              "
            >
              <q-tooltip>ประวัติแก้ไขความสามารถพิเศษ</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <div class="row">
            <div class="col q-pa-sm label-color">ด้าน</div>
            <div class="col q-pa-sm">{{ props.cols[0].value }}</div>
            <div class="col q-pa-sm label-color">รายละเอียด</div>
            <div class="col q-pa-sm">{{ props.cols[1].value }}</div>
          </div>
          <div :class="`row bg-color`">
            <div class="col q-pa-sm label-color">หมายเหตุ</div>
            <div class="col q-pa-sm">{{ props.cols[2].value }}</div>
            <div class="col q-pa-sm label-color">เอกสารอ้างอิง</div>
            <div class="col q-pa-sm">{{ props.cols[3].value }}</div>
          </div>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="dialog" class="dialog" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <dialog-header
          :tittle="
            dialogStatus == 'edit'
              ? 'แก้ไขข้อมูลความสามารถพิเศษ'
              : 'เพิ่มข้อมูลความสามารถพิเศษ'
          "
          :close="closeDialog"
        />
        <q-separator color="grey-4" />
        <q-card-section style="max-height: 50vh" class="scroll">
          <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                outlined
                class="inputgreen"
                dense
                bg-color="white"
                v-model="specialSkill.field"
                label="ด้าน"
                hide-bottom-space
                :rules="[
                  (val) => !!val || `${'กรุณากรอกด้านความสามารถพิเศษ'}`,
                ]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                outlined
                dense
                class="inputgreen"
                bg-color="white"
                v-model="specialSkill.detail"
                label="รายละเอียด"
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="inputgreen"
                outlined
                dense
                bg-color="white"
                v-model="specialSkill.remark"
                label="หมายเหตุ"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="inputgreen"
                outlined
                dense
                bg-color="white"
                v-model="specialSkill.reference"
                label="เอกสารอ้างอิง"
              />
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>   
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="historyDialog" class="dialog" persistent>
    <q-layout
      view="lHh lpr lFf"
      container
      style="height: 500px; min-width: 80%"
      class="bg-white"
    >
      <q-header>
        <q-toolbar>
          <dialog-header
            tittle="ประวัติแก้ไขความสามารถพิเศษ"
            :close="closeHistoryDialog"
          />
        </q-toolbar>
        <q-separator color="grey-4" />
      </q-header>

      <q-page-container>
        <q-page class="q-pa-md">
          <q-toolbar style="padding: 0px" class="text-primary q-mb-sm">
            <q-space />
            <q-input
              dense
              outlined
              bg-color="white"
              v-model="historyKeyword"
              label="ค้นหา"
              class="q-mr-sm"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>

            <q-select
              v-model="historyVisibleColumns"
              multiple
              outlined
              dense
              bg-color="white"
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="historyColumns"
              option-value="name"
              options-cover
              style="min-width: 150px"
            />
          </q-toolbar>
          <d-table
            ref="table"
            :columns="historyColumns"
            :rows="historyRows"
            row-key="name"
            flat
            bordered
            :paging="true"
            dense
            :filter="historyKeyword"
            v-model:pagination="historyPagination"
            :rows-per-page-options="[20, 50, 100]"
            class="custom-header-table"
            :visible-columns="historyVisibleColumns"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
                <q-th auto-width />
              </q-tr>
            </template>
            <template v-slot:body="props" v-if="mode === 'table'">
              <q-tr :props="props" class="cursor-pointer">
                <q-td v-for="col in props.cols" :key="col.id">
                  <div>{{ col.value ? col.value : "-" }}</div>
                </q-td>
                <q-td auto-width> </q-td>
              </q-tr>
            </template>
          </d-table>
        </q-page>
      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

<style scoped>
.label-color {
  color: #747474cc;
}

.bg-color {
  background-color: #fafafa;
}
</style>
