<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import { useInsigniaDataStore } from "@/modules/07_insignia/store";
import { useroleUserDataStore } from "@/stores/roleUser";

import cardTop from "@/modules/07_insignia/components/2_Manage/StatCard.vue";
import tab1 from "@/modules/07_insignia/components/2_Manage/Tab1.vue";
import tab2 from "@/modules/07_insignia/components/2_Manage/Tab2.vue";
import tab3 from "@/modules/07_insignia/components/2_Manage/Tab3.vue";
import tab4 from "@/modules/07_insignia/components/2_Manage/Tab4.vue";
import DialogPopupReason from "@/components/Dialogs/PopupReason.vue";
import keycloak from "@/plugins/keycloak";

const roleUser = ref<string>("admin");

const roleDataStore = useroleUserDataStore();
const DataStore = useInsigniaDataStore();
const mixin = useCounterMixin();
const { messageError, dialogConfirm, showLoader, hideLoader, success } = mixin;
const $q = useQuasar(); //ใช้ noti quasar

const loading = ref<boolean>(false);
const loadview = ref<boolean>(false);
const hideBottom = ref<boolean>(false);
const round = ref<string>("");
const roundName = ref<string>("");
const optionRound = ref<any>([]);
const optiontypeOc = ref<any>([]);
const tab = ref<any>("");
const stat = ref<any>({
  allUserUser: 0,
  orgAllCount: 0,
  orgNoSendCount: 0,
  orgSendCount: 0,
});

onMounted(async () => {
  tab.value = DataStore.mainTab;
  await fecthlistRound();
});

const fecthlistRound = async () => {
  await http
    .get(config.API.listRoundInsignia())
    .then(async (res: any) => {
      optionRound.value = res.data.result.map((e: any) => ({
        id: e.period_id,
        year: e.period_year,
        name: e.period_name,
      }));
      if (optionRound.value.length !== 0) {
        const lastValue = optionRound.value[0];
        round.value = lastValue.id.toString();
        roundName.value = lastValue.name;
        await fecthStat(round.value);
        await fecthAgency();
      }
    })
    .catch((err) => {
      console.log(err);
      messageError($q, err);
    });
};

const fecthStat = async (id: string) => {
  showLoader();
  await http
    .get(config.API.insigniaDashboard(id))
    .then((res) => {
      stat.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const fecthAgency = async () => {
  showLoader();
  await http
    .get(config.API.insigniaAgency())
    .then(async (res) => {
      DataStore.agency = res.data.result;
      loadview.value = true;
      if (roleDataStore.adminRole) {
        await fecthType();
      }
    })
    .catch((err) => {
      console.log(err);
      messageError($q, err);
    })
    .finally(() => {
      loading.value = true;
      hideLoader();
    });
};

const fecthType = async () => {
  await http
    .get(config.API.typeOc())
    .then((res) => {
      optiontypeOc.value = res.data.result.map((e: any) => ({
        id: e.organizationId,
        name: e.organizationName,
      }));
      DataStore.fetchOption(optiontypeOc.value);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      // loading.value = true;
    });
};

const changround = async () => {
  fecthStat(round.value);
  var organization = await (DataStore.agency != null
    ? DataStore.agency
    : DataStore.typeOc);
  fecthInsigniaByOc(round.value, organization, "officer", tab.value);
  // get round name
  const roundFilter = await optionRound.value.find(
    (x: any) => round.value === x.id
  );
  roundName.value = `รอบการเสนอขอพระราชทานเครื่องราชปี ${
    roundFilter.year + 543
  }`;
};
const requestNote = ref<string>("");
const requestStatus = ref<string>("");
const fecthInsigniaByOc = async (
  roundId: string,
  ocId: string,
  role: string,
  status: string
) => {
  showLoader();
  await http
    .get(config.API.insigniaList(roundId, ocId, role, status))
    .then(async (res) => {
      requestNote.value = res.data.result.requestNote;
      requestStatus.value = res.data.result.requestStatus;
      await DataStore.fetchData(res.data.result.items);
      await DataStore.fetchDataInsignia(res.data.result);
      loading.value = true;
      if (res.data.result.items !== null) {
        if (res.data.result.items.length !== 0) {
          hideBottom.value = true;
        } else hideBottom.value = false;
      }

      // if (res.data.result.items.length !== 0) {
      //   hideBottom.value = true;
      // }
      // DataStore.isLock = await res.data.result.isLock;
      // DataStore.requestId = await res.data.result.requestId;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const sendToDirector = async () => {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .get(config.API.insigniaSendToDirector(round.value, DataStore.agency))
      .then(async () => {
        success($q, "บันทึกสำเร็จ");
        await fecthInsigniaByOc(
          round.value,
          DataStore.agency,
          "officer",
          tab.value
        );
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
};

const modalPopupBackToEdit = ref<boolean>(false);
const popupBackToEdit = async () => {
  modalPopupBackToEdit.value = true;
};
const closeModalPopupBackToEdit = async () => {
  modalPopupBackToEdit.value = false;
};

const backToEdit = async (reason: string) => {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .put(
          config.API.insigniaDirectorBackToEdit(round.value, DataStore.agency),
          {
            reason: reason,
          }
        )
        .then(async () => {
          success($q, "บันทึกสำเร็จ");
          await fecthInsigniaByOc(
            round.value,
            DataStore.agency,
            "officer",
            tab.value
          );
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          closeModalPopupBackToEdit();
          hideLoader();
        });
    },
    "ยืนยันการตีกลับ",
    "ต้องการยืนยันการตีกลับใช่หรือไม่?"
  );
};

const directorApproved = async () => {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .get(config.API.insigniaDirectorApproved(round.value, DataStore.agency))
        .then(async () => {
          success($q, "บันทึกสำเร็จ");
          await fecthInsigniaByOc(
            round.value,
            DataStore.agency,
            "officer",
            tab.value
          );
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการอนุมัติ",
    "ต้องการยืนยันการอนุมัติใช่หรือไม่?"
  );
};

const requestSendNote = async () => {
  var organization = await (DataStore.agency != null
    ? DataStore.agency
    : DataStore.typeOc);
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.insigniaRequestSendNote(round.value), {
        name: roundName.value,
      })
      .then(async () => {
        success($q, "บันทึกสำเร็จ");
        await fecthInsigniaByOc(
          round.value,
          organization,
          "officer",
          tab.value
        );
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
};
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายชื่อข้าราชการสามัญฯ ที่มีสิทธิ์ยื่นขอพระราชทานเครื่องราชอิสริยาภรณ์
  </div>
  <q-card bordered class="row col-12 q-mt-sm" v-if="loadview">
    <div class="row col-12 items-center bg-grey-1">
      <div class="q-pl-md q-pr-sm text-weight-medium text-grey-7">รอบ</div>
      <q-select
        borderless
        dense
        v-model="round"
        :options="optionRound"
        map-options
        emit-value
        option-value="id"
        option-label="name"
        @update:model-value="changround"
      />

      <q-space />
      <!-- สกจ. Freez ข้อมูล -->
      <q-btn
        v-if="
          roleDataStore.adminRole && DataStore.isLock !== true && hideBottom
        "
        dense
        unelevated
        label="ล็อกข้อมูล"
        color="public"
        class="q-px-md q-ml-md"
        @click="requestSendNote"
      >
        <q-tooltip>ล็อกข้อมูล</q-tooltip>
      </q-btn>
    </div>
    <div class="col-12"><q-separator /></div>
    <div v-if="roleDataStore.adminRole" class="col-12 row bg-white">
      <div class="fit q-px-md q-py-sm">
        <div class="row col-12 q-col-gutter-sm fit">
          <cardTop
            :amount="stat.orgAllCount"
            label="หน่วยงานทั้งหมด"
            color="#016987"
          />
          <cardTop
            :amount="stat.orgSendCount"
            label="หน่วยงานที่ส่งรายชื่อเเล้ว"
            color="#02A998"
          />
          <cardTop
            :amount="stat.orgNoSendCount"
            label="หน่วยงานที่ยังไม่ได้ส่งรายชื่อ"
            color="#2EA0FF"
          />
          <cardTop
            :amount="stat.allUserUser"
            label="จำนวนคนที่ยื่นขอ"
            color="#4154B3"
          />
        </div>
      </div>
    </div>
  </q-card>
  <q-card v-else>
    <div class="q-pa-md q-gutter-sm">
      <q-banner inline-actions rounded class="bg-grey-1 text-center">
        ไม่มีข้อมูลรอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์
      </q-banner>
    </div>
  </q-card>

  <q-card flat bordered class="col-12 q-mt-sm" v-if="loading">
    <div
      v-if="roleDataStore.insignia1Role && requestStatus == 'st4'"
      class="q-pa-md q-gutter-sm"
    >
      <q-banner
        inline-actions
        bordered
        class="bg-orange-1 text-orange border-orange"
      >
        <q-icon name="mdi-information-outline" size="20px" /> หมายเหตุ ตีกลับ
        {{ requestNote }}
      </q-banner>
    </div>
    <div class="row col-12">
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-color="primary"
        active-class="bg-teal-1"
        indicator-color="primary"
        align="left"
      >
        <q-tab name="pending" label="คนที่ยื่นขอ" />
        <q-tab name="reject" label="คนที่ไม่ยื่นขอ" />
        <q-tab name="delete" label="คนที่ถูกลบออก" />
        <q-tab
          v-if="roleDataStore.adminRole"
          name="organization"
          label="หน่วยงานที่ยังไม่ได้ส่งรายชื่อ"
        />
      </q-tabs>
    </div>
    <q-separator />
    <q-tab-panels v-model="tab" animated>
      <q-tab-panel name="pending" class="q-pa-none">
        <tab1
          :tab="tab"
          :roundId="round"
          :roundName="roundName"
          :fecthInsigniaByOc="fecthInsigniaByOc"
          :request-status="requestStatus"
        />
      </q-tab-panel>
      <q-tab-panel name="reject" class="q-pa-none">
        <tab2
          :tab="tab"
          :roundId="round"
          :fecthInsigniaByOc="fecthInsigniaByOc"
        />
      </q-tab-panel>
      <q-tab-panel name="delete" class="q-pa-none">
        <tab3
          :tab="tab"
          :roundId="round"
          :fecthInsigniaByOc="fecthInsigniaByOc"
        />
      </q-tab-panel>
      <q-tab-panel
        v-if="roleDataStore.adminRole"
        name="organization"
        class="q-pa-none"
      >
        <tab4 :tab="tab" :roundId="round" />
      </q-tab-panel>
    </q-tab-panels>
    <!-- :role-user="roleUser" -->
    <q-toolbar class="q-py-md text-right">
      <q-space />
      <q-btn
        v-if="
          roleDataStore.insignia1Role &&
          (requestStatus == 'st1' || requestStatus == 'st4')
        "
        dense
        unelevated
        label="บันทึกข้อมูล"
        color="public"
        class="q-px-md"
        @click="sendToDirector"
      />
      <q-btn
        v-if="roleDataStore.insignia2Role && requestStatus == 'st3'"
        dense
        unelevated
        label="ตีกลับ"
        color="orange"
        class="q-px-md"
        @click="popupBackToEdit"
      />
      <q-btn
        v-if="roleDataStore.insignia2Role && requestStatus == 'st3'"
        dense
        unelevated
        label="อนุมัติ"
        color="positive"
        class="q-px-md q-ml-md"
        @click="directorApproved"
      />
    </q-toolbar>

    <DialogPopupReason
      :modal="modalPopupBackToEdit"
      title="หมายเหตุการตีกลับ"
      label="หมายเหตุ"
      :click-close="closeModalPopupBackToEdit"
      :savaForm="backToEdit"
    />
  </q-card>
</template>

<style lang="scss" scope>
.border-orange {
  border: 1px solid #ffa800;
  border-radius: 5px;
}

.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>
