<script setup lang="ts">
import { ref, onMounted } from "vue";
import router from "@/router";

import config from "@/app.config";
import http from "@/plugins/http";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";

import { useDisciplineChannelDataStore } from "@/modules/11_discipline/store/ChannelStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";

import { checkPermission } from "@/utils/permissions";
import Header from "@/components/DialogHeader.vue";

const $q = useQuasar(); //ใช้ noti quasar
const dataStore = useDisciplineChannelDataStore();
const mainStore = useDisciplineMainStore();
const route = useRoute();
const mixin = useCounterMixin();
const { dialogRemove, showLoader, messageError, hideLoader, success,onSearchDataTable } = mixin;

const modal = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const isRead = ref<boolean>(false);
const isId = ref<string>("");
const channel = ref<string>("");

/**
 * ค้นหาในตาราง
 */
const filterKeyword = ref<string>("");
const filterRef = ref<HTMLInputElement | null>(null);
const resetFilter = () => {
  filterKeyword.value = "";
  if (filterRef.value) {
    filterRef.value.focus();
  }
};

/**
 *pagination ของตาราง
 */
const pagination = ref({
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

/**
 * clickไปหน้าเพิ่มchanel
 */
function clickAdd(check: boolean) {
  modal.value = true;
  isEdit.value = check;
}
/**
 * clickไปหน้าเพิ่มchanel
 */
function clickEdit(check: boolean, id: string, name: string) {
  modal.value = true;
  isEdit.value = check;
  isId.value = id;
  channel.value = name;
}
/**
 * clickไปหน้าเพิ่มchanel
 */
function clickRead(check: boolean, name: string) {
  modal.value = true;
  isEdit.value = check;
  isRead.value = true;
  channel.value = name;
}

/** get data */
async function getComplaintChanal() {
  showLoader();
  await http
    .get(
      config.API.complaintListOp(
        mainStore.pathComplaintsChannal(route.name as string)
      )
    )
    .then((res) => {
      const data = res.data.result.data;
      dataStore.fetchData(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ลบข้อมูล
 * @param id ไอดีของข้อมูล
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => deleteData(id), `ลบข้อมูล`);
}

/**
 * ลบข้อมูล
 * @param id type
 */
async function deleteData(id: string) {
  showLoader();
  await http
    .delete(config.API.complaintChannelbyId(id))
    .then((res) => {
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await getComplaintChanal();
    });
}

/** ปิด popup */
function closeDialog() {
  modal.value = false;
  channel.value = "";
  isId.value = "";
  isRead.value = false;
}

/** class input */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** บันทึกช่องทางการร้องเรียน */
function onSubmit() {
  const url = isEdit.value
    ? config.API.complaintChannelbyId(isId.value)
    : config.API.complaintChannel();
  showLoader();
  http[isEdit.value ? "put" : "post"](url, {
    name: channel.value,
  })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      getComplaintChanal();
      closeDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSearch() {
  dataStore.rows = onSearchDataTable(
    filterKeyword.value,
    dataStore.rowsData,
    dataStore.columns ? dataStore.columns : []
  );
}

/**เมื่อเริ่มโหลดหน้า เรียกใช้ฟังชั่น*/
onMounted(() => {
  getComplaintChanal();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการช่องทางการร้องเรียน
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="row col-12 q-col-gutter-sm q-mb-sm">
      <div>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          @click="clickAdd(false)"
          dense
          flat
          round
          color="primary"
          icon="mdi-plus"
        >
          <q-tooltip>เพิ่มช่องทางการร้องเรียน</q-tooltip>
        </q-btn>
      </div>
      <q-space />

      <q-input
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        for="filterKeyword"
        outlined
        placeholder="ค้นหา"
        @keydown.enter.prevent="onSearch"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <q-select
        v-model="dataStore.visibleColumns"
        multiple
        for="visibleColumns"
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="dataStore.columns"
        option-value="name"
        style="min-width: 140px"
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>
    <div class="col-12">
      <d-table
        :columns="dataStore.columns"
        :rows="dataStore.rows"
        row-key="id"
        :visible-columns="dataStore.visibleColumns"
        v-model:pagination="pagination"
      >
        <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">
            <q-td auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                dense
                flat
                round
                color="info"
                @click="clickRead(true, props.row.name)"
                icon="mdi-eye"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-btn
                v-if="
                  checkPermission($route)?.attrIsGet &&
                  checkPermission($route)?.attrIsUpdate
                "
                dense
                flat
                round
                color="edit"
                @click="clickEdit(true, props.row.id, props.row.name)"
                icon="edit"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <q-btn
                v-if="checkPermission($route)?.attrIsDelete"
                dense
                flat
                round
                color="red"
                @click="clickDelete(props.row.id)"
                icon="mdi-delete"
              >
                <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 === 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else>
                {{ col.value ?? "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 50%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header
          :tittle="
            isRead
              ? 'รายละเอียดช่องทางการร้องเรียน'
              : isEdit
              ? 'แก้ไขช่องทางการร้องเรียน'
              : 'เพิ่มช่องทางการร้องเรียน'
          "
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <q-input
            :class="inputEdit(false)"
            dense
            outlined
            :readonly="isRead"
            v-model="channel"
            for="channel"
            hide-bottom-space
            label="ชื่อช่องทาง"
            lazy-rules
            :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อช่องทาง'}`]"
          />
        </q-card-section>
        <q-separator v-if="!isRead" />

        <q-card-actions align="right" v-if="!isRead">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scope>
.filter-card {
  background-color: #f1f1f1b0;
}

.toggle-expired-account {
  font-size: 12px;
  font-weight: 400;
  font-size: 15px;
  line-height: 150%;
  color: #35373c;
}

.icon-color {
  color: #4154b3;
}

.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
