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

import { useRouter } from "vue-router";
import {
  checkPermission,
  checkPermissionList,
  checkPermissionCreate,
} from "@/utils/permissions";
import { useTransferDataStore } from "@/modules/05_placement/store";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableProps } from "quasar";
import type { listMain } from "@/modules/05_placement/interface/response/OhterMain";

/** importcomopnents*/
import Dialogbody from "@/modules/05_placement/components/Other/DialogOrders.vue";
import DialogOrgSelect from "@/components/Dialogs/DialogOrgSelect.vue";

/** use*/
const $q = useQuasar();
const router = useRouter();
const store = useTransferDataStore();
const { statusText, filterOption } = useTransferDataStore();
const {
  showLoader,
  hideLoader,
  success,
  messageError,
  date2Thai,
  dialogRemove,
  onSearchDataTable,
  findChildNameHtml,
  findOrgName,
} = useCounterMixin();

const modal = ref<boolean>(false);
const status = ref<string>("");

/** Table*/
const rows = ref<listMain[]>([]); //รายการอื่นๆ
const rowsData = ref<listMain[]>([]); //รายการอื่นๆ
const rows2 = ref<listMain[]>([]); //รายการออกคำสั่ง
const rows2Data = ref<listMain[]>([]); //รายการออกคำสั่ง
const filterKeyword = ref<string>(""); //คำค้นหารายการอื่นๆ
const filterKeyword2 = ref<string>(""); //คำค้นหารายการออกคำสั่ง
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "positionNumberOld",
  "positionLevel",
  "organizationPositionOld",
  "organizationPositionReturn",
  "createdAt",
  "status",
]);
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",
    format(val, row) {
      return `${row.prefix === null ? "" : row.prefix}${row.firstName} ${
        row.lastName
      }`;
    },
  },

  {
    name: "positionNumberOld",
    align: "left",
    label: "เลขที่ตำแหน่งเดิม",
    sortable: true,
    field: "positionNumberOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.positionNumberOld;
    },
  },

  {
    name: "positionLevel",
    align: "left",
    label: "ตำแหน่งประเภทเดิม",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      let name = "";
      if (row.positionTypeOld && row.positionLevelOld) {
        name = `${row.positionTypeOld} (${row.positionLevelOld})`;
      } else if (row.positionTypeOld) {
        name = `${row.positionTypeOld}`;
      } else if (row.positionLevelOld) {
        name = `(${row.positionLevelOld})`;
      } else name = "-";
      return name;
    },
  },
  {
    name: "organizationPositionOld",
    align: "left",
    label: "ตำแหน่ง/สังกัดเดิม",
    sortable: true,
    field: "organizationPositionOld",
    format(val, row) {
      return row.organizationPositionOld.replace(/\n/g, " ");
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "organizationPositionReturn",
    align: "left",
    label: "ตำแหน่ง/หน่วยงานที่บรรจุกลับ",
    sortable: true,
    field: "organizationPositionReturn",
    format: (val, row) => {
      // return `${row.root} (${row.rootShortName}) ${row.nodeName} (${row.nodeShortName}${row.posMasterNo})`;
      return `${row.position !== null ? row.position : ""}${
        row.posLevelName !== null ? `${row.posLevelName}` : ""
      } ${
        row.nodeShortName !== null
          ? `(${row.nodeShortName}${row.posMasterNo})`
          : ""
      } ${findOrgName(row)}`;
    },
    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",
    format: (val) => date2Thai(val),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => statusText(val),
  },
]);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

/** fetch รายการอื่นๆ*/
async function fecthlistOthet() {
  showLoader();
  await http
    .get(config.API.otherMain() + `?status=${status.value}`)
    .then(async (res) => {
      let response = res.data.result;
      rows.value = response;
      rowsData.value = response;
      // หารายชื่อส่งไปออกคำสั่งอื่นๆ
      const listData = rows.value.filter(
        (e: listMain) =>
          e.status !== "REPORT" &&
          e.status !== "DONE" &&
          e.organizationPositionOld &&
          e.positionTypeOld &&
          e.positionLevelOld &&
          e.positionNumberOld &&
          e.positionDate &&
          e.leaveDate !== null &&
          e.nodeId !== null
      );
      rows2.value = listData;
      rows2Data.value = listData;
      await onSearch();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เปิด popup ส่งไปออกคำสั่งอื่นๆ*/
function popup() {
  modal.value = true;
  filterKeyword2.value = "";
}

/** ปิด popup ส่งไปออกคำสั่งอื่นๆ*/
function clickClose() {
  modal.value = false;
}

/**
 * ยืนยันการลบรายการอื่นๆ
 * @param id รายการอื่นๆ
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.otherByid(id))
      .then(async () => {
        await fecthlistOthet();
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

const modalSelectOrg = ref<boolean>(false);
const type = ref<string | null>(null);
const personalId = ref<string>("");

const posType = ref<string>(""); //ตำแหน่งประเภท
const posLevel = ref<string>(""); //ระดับตำแหน่ง
const position = ref<string>(""); //ตำแหน่ง
const dataRows = ref<any>(); //ข้อมูลที่ต้องการเลือกหน่วยงานที่รับโอน

/**
 * ฟังก์ชันเปิด popup เลือกหน่วยงานที่รับโอน
 * @param id id รายการรับโอนที่เลือกหน่วยงานที่รับโอน
 * @param data ข้อมูลรายการรับโอน
 */
function onSelectOrg(data: any) {
  personalId.value = data.id;
  // personal.value = dataRecevice.value.filter((e: ResponseData) => e.id === id);
  dataRows.value = data;
  posType.value = data.posTypeId;
  posLevel.value = data.posLevelId;
  position.value = data.positionId;
  type.value = null;
  modalSelectOrg.value = true;
}

async function onSaveSelectOrg(data: any) {
  const body = {
    node: data.node,
    nodeId: data.nodeId,
    orgRevisionId: data.orgRevisionId,
    positionId: data.positionId,
    posMasterNo: data.posMasterNo ?? "",
    positionName: data.positionName ?? "",
    posTypeId: data.posTypeId,
    posTypeName: data.posTypeName ?? "",
    posLevelId: data.posLevelId,
    posLevelName: data.posLevelName ?? "",
    posExecutiveName: data.posExecutiveName ?? "",
    reportingDate: data.reportingDate,
    posmasterId: data.posmasterId,
    typeCommand: data.typeCommand,
    positionExecutiveField: data.positionExecutiveField,
    positionArea: data.positionArea,
  };

  showLoader();
  await http
    .put(config.API.otherPosition(personalId.value), body)
    .then(async () => {
      await fecthlistOthet();
      await success($q, "บันทึกข้อมูลสำเร็จ");
      modalSelectOrg.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * redialect รายละเอียดรายการอื่นๆ
 * @param id รายการอื่นๆ
 */
function nextPage(id: string) {
  router.push({
    path: `/placement/other/detail/${id}`,
  });
}

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

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">
    <div class="row q-pa-md">
      <div class="col-12">
        <div class="row">
          <div class="col-2">
            <q-select
              :model-value="status ? status : 'ทั้งหมด'"
              outlined
              dense
              label="สถานะ"
              :options="store.statusOp.filter((item:any)=> item.id !== 'PENDING' && item.id !== 'APPROVE'&& item.id !== 'REJECT')"
              emit-value
              map-options
              option-label="name"
              option-value="id"
              fill-input
              use-input
              hide-selected
              bg-color="white"
              @filter="(inputValue:any,doneFn:Function) => filterOption(inputValue, doneFn) "
              @update:model-value="(value:string)=>{(status = value),fecthlistOthet()}"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
              <template v-if="status" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="(status = ''), fecthlistOthet()"
                  class="cursor-pointer"
                  style="opacity: 0.6"
                />
              </template>
            </q-select>
          </div>
          <q-btn
            v-if="
              checkPermission($route)?.attrIsUpdate &&
              checkPermissionList(['COMMAND']) &&
              checkPermissionCreate('COMMAND')
            "
            @click="popup()"
            size="14px"
            flat
            round
            color="primary"
            icon="mdi-account-arrow-right"
          >
            <q-tooltip>ส่งไปออกคำสั่งรายการอื่นๆ</q-tooltip>
          </q-btn>
          <q-space />
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            @keydown.enter.prevent="onSearch"
          >
            <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"
            class="q-ml-sm"
          />
        </div>

        <div class="col-12 q-pt-sm">
          <d-table
            :columns="columns"
            :rows="rows"
            row-key="id"
            :visible-columns="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)?.attrIsUpdate &&
                      checkPermission($route)?.attrIsGet
                    "
                    :disable="
                      props.row.status === 'REPORT' ||
                      props.row.status === 'DONE'
                    "
                    :color="
                      props.row.status === 'REPORT' ||
                      props.row.status === 'DONE'
                        ? 'grey'
                        : 'primary'
                    "
                    flat
                    round
                    dense
                    icon="mdi-bookmark-outline"
                    @click="onSelectOrg(props.row)"
                  >
                    <q-tooltip>เลือกหน่วยงานที่บรรจุกลับ</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="checkPermission($route)?.attrIsGet"
                    flat
                    round
                    dense
                    icon="mdi-eye"
                    color="info"
                    @click.stop.prevent="nextPage(props.row.id)"
                  >
                    <q-tooltip>รายละเอียด</q-tooltip>
                  </q-btn>

                  <q-btn
                    v-if="checkPermission($route)?.attrIsDelete"
                    flat
                    :disable="
                      props.row.status == 'REPORT' || props.row.status == 'DONE'
                    "
                    round
                    dense
                    :color="
                      props.row.status == 'REPORT' || props.row.status == 'DONE'
                        ? 'grey-5'
                        : 'red'
                    "
                    icon="mdi-delete"
                    @click.stop="clickDelete(props.row.id)"
                  >
                    <q-tooltip>ลบข้อมูล</q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.id">
                  <div v-if="col.name === 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>

                  <div
                    v-else-if="col.name === 'organizationPositionOld'"
                    class="text-html"
                  >
                    {{ props.row.organizationPositionOld ?? "-" }}
                  </div>

                  <div v-else-if="col.name === 'organizationPositionReturn'">
                    {{ props.row.position !== null ? props.row.position : ""
                    }}{{
                      props.row.posLevelName !== null
                        ? `${props.row.posLevelName}`
                        : ""
                    }}
                    <!-- {{
                      (props.row.posTypeName !== null &&
                        props.row.posTypeName === "บริหาร") ||
                      props.row.posTypeName === "อำนวยการ"
                        ? `${props.row.posTypeName}`
                        : ""
                    }} -->
                    {{
                      props.row.nodeShortName !== null
                        ? `(${props.row.nodeShortName} ${props.row.posMasterNo})`
                        : ""
                    }}
                    <div>
                      {{
                        props.row.positionExecutive !== null
                          ? `${props.row.positionExecutive}${
                              props.row.positionExecutiveField
                                ? ` (${props.row.positionExecutiveField})`
                                : ""
                            }`
                          : ""
                      }}
                    </div>
                    <div class="text-html">
                      {{ findChildNameHtml(props.row) }}
                    </div>
                  </div>

                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>

  <Dialogbody
    v-model:Modal="modal"
    v-model:filter-keyword2="filterKeyword2"
    :click-close="clickClose"
    v-model:rows="rows2"
    v-model:rowsData="rows2Data"
    :fecthlistOthet="fecthlistOthet"
  />

  <DialogOrgSelect
    :title="`เลือกหน่วยงานที่บรรจุกลับ`"
    v-model:modal="modalSelectOrg"
    v-model:type="type"
    :pos-type="''"
    :pos-level="''"
    :position="''"
    :data-rows="dataRows"
    :onSubmit="onSaveSelectOrg"
  />
</template>

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