<template>
  <div class="q-px-md q-pb-md">
    <!-- header บน table มี ค้นหา แสดงคอลัมน์ ปุ่มแก้ไข เพิ่ม เผยแพร่ข้อมูล ยกเลิก-->
    <div class="col-12 row q-py-sm q-col-gutter-sm">
      <q-btn-group flat>
        <q-btn
          :push="!editvisible"
          :outline="editvisible"
          dense
          :disabled="editvisible == true"
          :color="editvisible == true ? 'grey-7' : 'primary'"
          label="แก้ไข"
          @click="edit"
          icon="mdi-pencil-outline"
          class="q-px-sm"
        >
          <!-- <q-tooltip>แก้ไขข้อมูล</q-tooltip> -->
        </q-btn>
        <!-- <q-separator vertical /> -->
        <q-btn
          :push="editvisible"
          :outline="!editvisible"
          dense
          :disabled="editvisible == false"
          :color="editvisible == false ? 'grey-7' : 'primary'"
          label="เพิ่ม"
          @click="add"
          icon="mdi-plus"
          class="q-px-sm"
        >
          <!-- <q-tooltip>เพิ่มข้อมูล</q-tooltip> -->
        </q-btn>
      </q-btn-group>
      <q-btn-group flat>
        <!-- เผยแพร่ -->
        <q-btn
          dense
          :push="publicData == false || updateData == true"
          :outline="!(publicData == false || updateData == true)"
          :disabled="!(publicData == false || updateData == true)"
          :color="
            !(publicData == false || updateData == true) ? 'grey-7' : 'public'
          "
          label="เผยแพร่"
          @click="publishModal"
          icon="mdi-file-upload-outline"
          class="q-px-sm"
        >
          <!-- <q-tooltip>เผยแพร่</q-tooltip> -->
        </q-btn>
        <!-- บันทึกร่าง แสดงเมื่อ กดปุ่มแก้ไข ข้อมูลมีการเป็นแปลงหรือ ยังไม่เผยแพร่ข้อมูล -->
        <q-btn
          dense
          :push="
            editvisible == true && (publicData == false || updateData == true)
          "
          :outline="
            !(
              editvisible == true &&
              (publicData == false || updateData == true)
            )
          "
          :disabled="
            !(
              editvisible == true &&
              (publicData == false || updateData == true)
            )
          "
          :color="
            !(
              editvisible == true &&
              (publicData == false || updateData == true)
            )
              ? 'grey-7'
              : 'public'
          "
          label="บันทึกร่าง"
          @click="checkSave"
          icon="mdi-file-check-outline"
          class="q-px-sm"
        >
          <!-- <q-tooltip>บันทึกร่าง</q-tooltip> -->
        </q-btn>

        <!-- ลบบันทึกร่าง แสดงเมื่อ บันทึกร่างแล้ว -->
        <q-btn
          dense
          :push="!publicData"
          :disabled="publicData == true"
          :outline="publicData == true"
          label="ลบร่าง"
          :color="publicData == true ? 'grey-7' : 'public'"
          @click="deleted()"
          icon="mdi-file-remove-outline"
          class="q-px-sm"
        >
          <!-- <q-tooltip>ลบบันทึกร่าง</q-tooltip> -->
        </q-btn>
      </q-btn-group>

      <q-btn-group flat>
        <!-- ยกเลิก แสดงเมื่อ กดปุ่มแก้ไข -->
        <q-btn
          dense
          :push="editvisible"
          :disabled="editvisible == false"
          :outline="editvisible == false"
          label="ยกเลิก"
          :color="editvisible == false ? 'grey-7' : 'red'"
          @click="cancel()"
          icon="mdi-close"
          class="q-px-sm"
        >
          <!-- <q-tooltip>ยกเลิก</q-tooltip> -->
        </q-btn>
      </q-btn-group>
      <q-space />
      <div class="items-center" style="display: flex">
        <!-- ข้อความสถานะเผยแพร่ โดยใช้ parameter publicData เป็นตัวกำหนดข้อความ -->
        <!-- <div class="row items-center" style="display: flex" v-if="publicData == true">
					<q-icon cener size="20px" name="label_important" class="icon-color" />
					<div class="text-size">ข้อมูลเผยแพร่แล้ว</div>
					</div> -->
        <div
          class="row items-center"
          style="display: flex"
          v-if="publicData == false"
        >
          <q-icon cener size="15px" name="label_important" color="amber" />
          <div class="text-caption text-grey-7 text-weight-medium q-px-sm">
            ข้อมูลยังไม่เผยแพร่
          </div>
        </div>
        <!-- ค้นหาข้อความใน table -->
        <q-input
          standout
          dense
          :model-value="inputfilter"
          @update:model-value="updateInput"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          style="max-width: 200px"
          class="q-ml-sm"
        >
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
        <!-- แสดงคอลัมน์ใน table -->
        <q-select
          :model-value="inputvisible"
          @update:model-value="updateVisible"
          :display-value="$q.lang.table.columns"
          multiple
          outlined
          dense
          :options="attrs.columns"
          options-dense
          option-value="name"
          map-options
          emit-value
          style="min-width: 150px"
          class="gt-xs q-ml-sm"
        />
      </div>
    </div>
    <q-table
      ref="table"
      flat
      bordered
      class="custom-header-table"
      v-bind="attrs"
      virtual-scroll
      :rows-per-page-options="[0]"
      :virtual-scroll-sticky-size-start="48"
      dense
      ><!-- :pagination="initialPagination"
				:pagination-label="paginationLabel" -->
      <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
            v-if="editvisible == true || nextPageVisible == true"
          />
        </q-tr>
      </template>
      <!-- สำหรับเรียกใช้ template ตัวข้างนอก -->
      <template #body="props">
        <slot v-bind="props" name="columns"></slot>
      </template>
    </q-table>
  </div>
  <!-- ข้อมูลการเผยแพร่ข้อมูล -->
  <q-dialog v-model="modal" persistent>
    <q-card class="q-pa-sm">
      <q-card-section class="row">
        <div class="q-pr-md">
          <q-avatar
            icon="public"
            size="lg"
            font-size="25px"
            color="blue-1"
            text-color="public"
          />
        </div>
        <div class="col text-dark">
          <span class="text-bold">ต้องการเผยแพร่ข้อมูลนี้หรือไม่?</span>
          <br />
          <span>ข้อมูลที่กำลังถูกเผยแพร่นี้จะมีผลใช้งานทันที</span>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn label="ยกเลิก" flat color="grey-8" v-close-popup />
        <q-btn
          label="เผยแพร่"
          color="public"
          @click="publish()"
          v-close-popup
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
  <q-dialog
    :model-value="modalError"
    persistent
    @update:model-value="updateClose"
  >
    <q-card class="q-pa-sm">
      <q-card-section class="row items-center">
        <div class="q-pr-md">
          <q-avatar
            icon="mdi-alert-circle-outline"
            font-size="25px"
            size="lg"
            color="red-1"
            text-color="red"
          />
        </div>
        <div class="col text-dark">
          <span class="text-bold">{{ modalErrorTittle }}</span>
          <br />
          <span>{{ modalErrorDetail }}</span>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="ตกลง"
          color="primary"
          @click="updateClose"
          v-close-popup
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import { ref, useAttrs } from "vue";

const attrs = ref<any>(useAttrs());
const table = ref<any>(null);

const modal = ref<boolean>(false);
const initialPagination = ref<any>({
  descending: false,
  rowsPerPage: 10,
});

const props = defineProps({
  inputfilter: String,
  inputvisible: Array,
  editvisible: Boolean,
  nextPageVisible: {
    type: Boolean,
    defualt: false,
  },
  modalError: Boolean,
  modalErrorTittle: String,
  modalErrorDetail: String,
  publicData: {
    type: Boolean,
    defualt: true,
    required: true,
  },
  updateData: {
    type: Boolean,
    defualt: true,
    required: true,
  },
  add: {
    type: Function,
    default: () => console.log("not function"),
  },
  edit: {
    type: Function,
    default: () => console.log("not function"),
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  deleted: {
    type: Function,
    default: () => console.log("not function"),
  },
  cancel: {
    type: Function,
    default: () => console.log("not function"),
  },
  publish: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const emit = defineEmits([
  "update:inputfilter",
  "update:inputvisible",
  "update:editvisible",
  "update:modalError",
  "update:modalErrorTittle",
  "update:modalErrorDetail",
]);

const updateEdit = (value: any) => {
  emit("update:editvisible", value);
};
const updateInput = (value: any) => {
  emit("update:inputfilter", value);
};
const updateVisible = (value: any) => {
  emit("update:inputvisible", value);
};
const updateClose = (value: any) => {
  //   props.modalError = false;
  emit("update:modalError", false);
  emit("update:modalErrorTittle", "");
  emit("update:modalErrorDetail", "");
};

const paginationLabel = (start: string, end: string, total: string) => {
  return start + "-" + end + " ใน " + total;
};

const checkSave = () => {
  props.save();
  //   if (myForm.value !== null) {
  //     myForm.value.validate().then((success) => {
  //       if (success) {
  //       }
  //     });
  //   }
};

const publishModal = () => {
  const filter = attrs.value.rows.filter((r: any) => r.name == "");

  if (filter.length == 0 && attrs.value.rows.length !== 0) {
    modal.value = true;
  }
};

const edit = async () => {
  updateEdit(!props.editvisible);
  props.edit();
};

const add = async () => {
  //   if (myForm.value !== null) {
  //     myForm.value.validate();
  //   }
  props.add();
  await table.value.lastPage();
  await table.value.scrollTo(attrs.value.rows.length - 1);
};
</script>
<style lang="scss">
.icon-color {
  color: #4154b3;
}
.custom-header-table {
  max-height: 38vh;
  .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>
