<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useTransferDataStore } from "@/modules/05_placement/store";
import type { QTableProps } from "quasar";
import type {
  listMain,
  listMainAPI,
} from "@/modules/05_placement/interface/response/OhterMain";
import type { OpType } from "@/modules/05_placement/interface/response/Main";

import http from "@/plugins/http";
import config from "@/app.config";
import Dialogbody from "@/modules/05_placement/components/Other/Dialogbody.vue";

const storeFn = useTransferDataStore();
const mixin = useCounterMixin();

const { statusText } = storeFn;
const {
  showLoader,
  hideLoader,
  success,
  messageError,
  date2Thai,
  dialogRemove,
} = mixin;

const $q = useQuasar();
const router = useRouter();
const optionsType = ref<OpType[]>([]);
const type = ref<string>("");
const modal = ref<boolean>(false);
const rows = ref<listMain[]>([]);
const rows2 = ref<listMain[]>([]);

const filterKeyword = ref<string>("");
const filterKeyword2 = ref<string>("");
const filterRef = ref<any>(null);

const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "positionPath",
  "positionLevel",
  "organizationPositionOld",
  "createdAt",
  "statustext",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionPath",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "positionPath",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizationPositionOld",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organizationPositionOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ดำเนินการ",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statustext",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "statustext",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

//----(ดึงข้อมูลจาก API)------//
const fecthlistOthet = async () => {
  showLoader();
  await http
    .get(config.API.otherMain())
    .then((res) => {
      let response = res.data.result;
      rows.value = response.map((r: listMainAPI) => ({
        createdAt: date2Thai(r.createdAt),
        date: new Date(),
        firstName: r.firstname ?? "-",
        personalId: r.id ?? "-",
        isActive: r.isActive ? r.isActive : false,
        lastName: r.lastname ?? "-",
        organization: r.organization ?? "-",
        organizationPositionOld: r.organizationPositionOld ?? "-",
        posNo: r.posNo ?? "-",
        position: r.position ?? "-",
        positionPath: r.positionPath ?? "-",
        positionLevel: r.positionLevel ?? "-",
        positionLevelOld: r.positionLevelOld ?? "-",
        positionNumberOld: r.positionNumberOld ?? "-",
        positionTypeOld: r.positionTypeOld ?? "-",
        prefix: r.prefix ?? "-",
        reason: r.reason ?? "-",
        salary: r.salary ? r.salary : 0,
        status: r.status ?? "-",
        statustext: statusText(r.status ?? ""),
        fullname: `${r.prefix ?? ""}${r.firstname ?? ""} ${r.lastname ?? ""}`,
      }));
      rows2.value = rows.value.filter(
        (e: listMain) => e.status !== "REPORT" && e.status !== "DONE"
      );
    })
    .catch((e) => {
      messageError($q);
    })
    .finally(() => {
      hideLoader();
    });
};
//----(ดึงข้อมูลประเภทคำสั่ง)------//
const fecthTypeOption = async () => {
  showLoader();
  type.value = "";
  await http
    .get(config.API.typeOrder())
    .then((res) => {
      optionsType.value = res.data.result.filter(
        (e: OpType) =>
          e.commandCode === "C-PM-08" || e.commandCode === "C-PM-09"
      );
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

//----(ลบข้อมูลจากไอดี)------//
const deleteOther = async (id: string) => {
  showLoader();
  await http
    .delete(config.API.otherByid(id))
    .then(() => {
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      fecthlistOthet();
    });
};

//----(รีเซ็ตข้อมูลในช่อง input)------//
const resetFilter = () => {
  filterKeyword.value = "";
  filterKeyword2.value = "";
  filterRef.value.focus();
};

//----(เปิด Dialog)------//
const popup = () => {
  modal.value = true;
  filterKeyword2.value = "";
  fecthTypeOption();
  type.value = "";
};

//----(ปิด modal)------//
const clickClose = () => {
  modal.value = false;
};
//----(เปิด Dialog ลบข้อมูล)------//
const clickDelete = (id: string) => {
  dialogRemove($q, () => deleteOther(id));
};
//----(เปิดหน้าถัดไป)------//
const nextPage = (id: string) => {
  router.push({
    path: `/other/detail/${id}`,
  });
};

onMounted(() => {
  fecthlistOthet();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">รายการอื่นๆ</div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <q-separator />
    <div class="row q-pa-md">
      <div class="col-12">
        <div class="row col-12">
          <q-btn
            @click="popup()"
            size="14px"
            flat
            round
            color="add"
            icon="mdi-account-arrow-right"
          >
            <q-tooltip>ส่งไปออกคำสั่งรายการอื่นๆ</q-tooltip>
          </q-btn>
          <q-space />
          <q-input
            class="col-xs-12 col-sm-3 col-md-2"
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon v-if="filterKeyword == ''" name="search" />
              <q-icon
                v-if="filterKeyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              />
            </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"
            options-cover
            style="min-width: 150px"
            class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
          />
        </div>

        <div class="col-12 q-pt-sm">
          <d-table
            :columns="columns"
            :rows="rows"
            :filter="filterKeyword"
            row-key="id"
            :visible-columns="visibleColumns"
            v-model:pagination="pagination"
          >
            <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">
              <q-tr
                :props="props"
                class="cursor-pointer"
                @click="nextPage(props.row.personalId)"
              >
                <q-td key="no" :props="props">
                  {{ props.rowIndex + 1 }}
                </q-td>
                <q-td key="fullname" :props="props">
                  {{ props.row.fullname }}
                </q-td>
                <q-td key="positionPath" :props="props">
                  {{ props.row.positionPath }}
                </q-td>
                <q-td key="positionLevel" :props="props">
                  {{ props.row.positionLevel }}
                </q-td>
                <q-td key="organizationPositionOld" :props="props">
                  <div class="table_ellipsis">
                    {{ props.row.organizationPositionOld }}
                  </div>
                </q-td>
                <q-td key="organization" :props="props">
                  <div class="table_ellipsis">
                    {{ props.row.organization }}
                  </div>
                </q-td>
                <q-td key="createdAt" :props="props">
                  {{ props.row.createdAt }}
                </q-td>
                <q-td key="statustext" :props="props">
                  {{ props.row.statustext }}
                </q-td>

                <q-td auto-width>
                  <q-btn
                    v-if="
                      props.row.status !== 'DONE' &&
                      props.row.status !== 'REPORT'
                    "
                    flat
                    round
                    class="text-red-14"
                    icon="mdi-delete"
                    dense
                    @click.stop="clickDelete(props.row.personalId)"
                    ><q-tooltip>ลบข้อมูล</q-tooltip></q-btn
                  >
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>
  <Dialogbody
    v-model:Modal="modal"
    :clickClose="clickClose"
    :optionsType="optionsType"
    :rows2="rows2"
    v-model:filterKeyword2="filterKeyword2"
    v-model:type="type"
    :fecthlistOthet="fecthlistOthet"
  />
</template>
<style scoped lang="scss"></style>
