<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useQuasar } from "quasar";

import type { QTableColumn } from "quasar";
import type { PropType } from "vue";

import { useCounterMixin } from "@/stores/mixin";
import { useSalaryEmployeeListSDataStore } from "@/modules/13_salary/store/SalaryEmployeeListsStore";
import http from "@/plugins/http";
import config from "@/app.config";

/** importComponents*/
import Header from "@/components/DialogHeader.vue";

/** use*/
const $q = useQuasar();
const store = useSalaryEmployeeListSDataStore();
const {
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  findOrgNameHtml,
  onSearchDataTable,
} = useCounterMixin();

/**porps*/
const modal = defineModel<boolean>("modal", { required: true });
const columns = defineModel<QTableColumn[]>("columns", {
  required: true,
});
const visibleColumns = defineModel<string[]>("visibleColumns", {
  required: true,
});

const props = defineProps({
  fetchData: {
    type: Function,
  },
  total: {
    type: Number,
  },
  columns: {
    type: Array as PropType<QTableColumn[]>,
  },
  visibleColumns: {
    type: Array as PropType<string[]>,
  },
  isRetire: {
    type: Boolean,
  },
});

const rows = ref<any[]>([]);
const rowsMain = ref<any[]>([]);
const selectedData = ref<any[]>([]); //ตำแหน่งที่ต้องการย้าย

const type = ref<string>(""); //เลื่อนขั้น
const note = ref<string>(""); //หมายเหตุ
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const isReserve = ref<boolean>(false); // สำรองหรือไม่

const typeRangeOps = computed(() => {
  return store.roundMainCode == "OCT"
    ? [
        { id: "NONE", name: "ไม่ได้เลื่อน" },
        { id: "HAFT", name: "0.5 ขั้น" },
        { id: "FULL", name: "1 ขั้น" },
        { id: "FULLHAFT", name: "1.5 ขั้น" },
      ]
    : store.roundMainCode == "APR"
    ? [
        { id: "NONE", name: "ไม่ได้เลื่อน" },
        { id: "HAFT", name: "0.5 ขั้น" },
        { id: "FULL", name: "1 ขั้น" },
      ]
    : [
        { id: "HAFT", name: "0.5 ขั้น" },
        { id: "FULL", name: "1 ขั้น" },
      ];
});

const keyword = ref<string>("");
const pagination = ref({
  page: 1,
  rowsPerPage: 50,
});

/**
 * function เรียกข้อมูลรายชื่อ
 * @param id กลุ่ม
 */
async function fetchDataPeriod() {
  showLoader();
  let formData = {
    page: "1",
    pageSize: props.total?.toString(),
    keyword: keyword.value,
    type: store.tabType,
    isRetire: store.roundMainCode !== "OCT" ? null : props.isRetire ? "1" : "0",
  };

  await http
    .put(config.API.salaryListPeriodORGEmp(store.groupId), formData)
    .then((res) => {
      rowsMain.value = res.data.result.data;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ปิด Popup
 */
function close() {
  modal.value = false;
}

/** function ยืนยันการบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const ArrayProfileId = selectedData.value.map((e) => e.id);
    const body = {
      type: type.value,
      isReserve: isReserve.value,
      remark: type.value === "NONE" ? note.value : undefined,
      profileId: ArrayProfileId,
    };
    await http
      .post(config.API.salaryPeriodEmp() + `/change/type-multi`, body)
      .then(async () => {
        await props.fetchData?.();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        close();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function เปลี่ยนระดับ
 */
function chengType() {}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    props.columns ? props.columns : []
  );
}

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

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchDataPeriod();
    } else {
      rows.value = [];
      rowsMain.value = [];
      keyword.value = "";
      type.value = "";
      selectedData.value = [];
      pagination.value.page = 1;
      pagination.value.rowsPerPage = 50;
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 85%">
      <Header :tittle="`เลื่อนขั้น`" :close="close" />
      <q-separator />

      <q-card-section class="scroll" style="max-height: 80vh">
        <div class="q-col-gutter-sm">
          <div class="row q-col-gutter-sm jus">
            <div class="col-3">
              <q-select
                class="inputgreen"
                v-model="type"
                label="เลื่อนขั้น"
                dense
                outlined
                emit-value
                map-options
                option-label="name"
                option-value="id"
                :options="typeRangeOps"
                :rules="[(val:string) => !!val || `${'กรุณาเลือก ขั้น'}`]"
                lazy-rules
                hide-bottom-space
                @update:model-value="chengType()"
                style="min-width: 140px"
              />
            </div>

            <div class="row col-9 items-center">
              <q-checkbox
                v-if="type === 'FULL'"
                keep-color
                label="สำรอง"
                dense
                v-model="isReserve"
              />

              <q-input
                v-if="type === 'NONE'"
                outlined
                dense
                v-model="note"
                label="หมายเหตุ"
                type="textarea"
                :class="inputEdit(isReadonly)"
              />
            </div>
          </div>
          <div class="col-12">
            <q-separator class="col-12" />
          </div>

          <div class="row justify-end q-col-gutter-sm">
            <q-input
              standout
              dense
              v-model="keyword"
              ref="filterRef"
              outlined
              placeholder="ค้นหา"
              @keydown.enter.prevent="serchDataTable"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </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"
              style="min-width: 140px"
            />
          </div>

          <div class="row justify-end">ทั้งหมด {{ rows.length }} รายการ</div>

          <div class="col-12 q-mt-sm">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="id"
              flat
              bordered
              dense
              :visible-columns="visibleColumns"
              selection="multiple"
              v-model:selected="selectedData"
              v-model:pagination="pagination"
            >
              <template v-slot:header-selection="scope">
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  v-model="scope.selected"
                />
              </template>

              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td auto-width>
                    <q-checkbox
                      v-model="props.selected"
                      keep-color
                      color="primary"
                      dense
                    />
                  </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-if="col.name == 'organization'"
                      class="text-html"
                    >
                      {{ findOrgNameHtml(props.row) }}
                    </div>
                    <div v-else-if="col.name == 'amount'">
                      {{ Number(props.row.amount).toLocaleString() }}
                    </div>
                    <div v-else-if="col.name == 'isSuspension'">
                      <q-icon
                        v-if="props.row.isSuspension !== null"
                        :name="props.row.isSuspension ? 'done' : 'close'"
                        :color="props.row.isSuspension ? 'primary' : 'red'"
                        size="24px"
                      />
                      <div v-else-if="props.row.isSuspension == null">
                        {{ props.row.isSuspension == null ? "-" : "" }}
                      </div>
                    </div>

                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          :disable="selectedData.length === 0 || type === ''"
          @click="onSubmit"
          color="secondary"
          label="บันทึก"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped></style>
