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

import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { Permission } from "@/interface/index/workflow/Main";
import type { DataListState } from "@/interface/response/workflow/Main";

import DialogSelectPerson from "@/components/Workflow/DialogSelectPerson.vue";
import DialogApprove from "@/components/Workflow/DialogApprove.vue";

const $q = useQuasar();
const { dialogConfirm, showLoader, hideLoader, messageError } =
  useCounterMixin();

const isCheckData = defineModel<boolean>("isCheckData", {
  default: true,
});
const props = defineProps({
  id: { type: String, require: true },
  sysName: { type: String, require: true },
  onUpdateStatus: {
    type: Function,
    defult: () => {
      console.log("No Function");
    },
  },
});

const stateId = ref<string>(""); //id state ปัจุบัน
const state = ref<number>(1); //state ปัจุบัน
const dataUserComment = ref<any>();

const isPermission = ref<boolean>(true); //การเข้าถึง Workflow
const permission = ref<Permission>({
  isChangeState: false, //ส่งไปยังผู้บังคับบัญชา/ผู้มีอำนาจ
  isOperate: false, //เปลี่ยนสถานะ (state) เอกสารได้ ผู้บังคับบัญชา
  isView: false, //ดูเอกสารได้
  isUpdate: false, //แก้ไขเอกสารได้
  isDelete: false, //ลบเอกสารได้ (ถ้ามี)
  isCancel: false, //ลบเอกสารได้ (ถ้ามี)
  isSign: false, //ผู้มีอำนาจ
});
const itemState = ref<DataListState[]>([]);

const modalSelectPerson = ref<boolean>(false);
const modalApprove = ref<boolean>(false);
const typeSelectPerson = ref<string>("");

//รายการระบบที่ต้องการ disable step 3 หรือรองสุดท้าย
const displayArray = <string[]>[
  "REGISTRY_PROFILE",
  "SYS_RESIGN",
  "SYS_LEAVE_LIST",
  "SYS_LEAVE_EMP",
];

async function fetchCheckState() {
  await http
    .post(config.API.workflow + `check-user-now`, {
      refId: props.id,
      system: props.sysName,
    })
    .then(async (res) => {
      await fetchData();
      const data = await res.data.result;

      stateId.value = data.stateId;
      state.value =
        data.stateNo === itemState.value.length
          ? data.stateNo + 1
          : data.stateNo;
      permission.value = {
        isChangeState: data.can_change_state,
        isOperate: data.can_operate,
        isView: data.can_view,
        isUpdate: data.can_update,
        isDelete: data.can_delete,
        isCancel: data.can_cancel,
        isSign: data.can_sign,
      };
    })
    .catch(() => {
      isPermission.value = false;
    });
}

async function fetchData() {
  await http
    .post(config.API.workflow + `check-state-all`, {
      refId: props.id,
      system: props.sysName,
    })
    .then(async (res) => {
      const data = await res.data.result;
      itemState.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function onChangeState() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.workflow + `state-next`, {
        refId: props.id,
        system: props.sysName,
      })
      .then(async () => {
        await fetchCheckState();
        if (
          props.sysName === "SYS_TRANSFER_REQ" &&
          state.value === itemState.value.length - 1
        ) {
          props.onUpdateStatus?.();
        }
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

onMounted(async () => {
  await fetchCheckState();
});

defineExpose({
  permission,
});
</script>

<template>
  <q-card bordered class="row col-12" v-if="isPermission">
    <div class="bg-grey-1 q-pa-sm col-12 row items-center">
      <div class="q-pl-sm text-weight-bold text-dark">สถานะการดำเนินเรื่อง</div>
      <q-space />
    </div>
    <div class="col-12"><q-separator /></div>
    <q-card-section>
      <div class="q-px-lg q-py-md">
        <q-timeline color="primary">
          <q-timeline-entry
            v-for="(step, index) in itemState"
            :key="index"
            :title="step.stateName"
            :icon="
              state === index + 1
                ? 'mdi-pencil'
                : state > index + 1
                ? 'done'
                : `mdi-numeric-${index + 1}`
            "
            :color="state < index + 1 ? 'grey-4' : ''"
          >
            <!-- Darft -->
            <div class="row q-col-gutter-sm" v-if="state === 1 && index === 0">
              <div>
                <q-btn
                  v-if="permission.isChangeState"
                  @click.prevent="onChangeState"
                  label="ดำเนินการต่อ"
                  color="primary"
                />
              </div>
            </div>

            <!-- Operate -->
            <div
              class="q-col-gutter-sm"
              v-if="index > 0 && index < itemState.length - 1 && state > index"
            >
              <div v-if="step.stateUserComments.length !== 0">
                <q-list bordered separator style="min-width: 20vw">
                  <q-item v-for="item in step.stateUserComments">
                    <q-item-section>
                      <q-item-label>
                        {{ `${item.prefix}${item.firstName} ${item.lastName}` }}
                        <!-- {{ `(${item.position})` }} -->
                      </q-item-label>
                      <q-item-label caption lines="2">{{
                        item.isReasonSetting ? item.reason : ""
                      }}</q-item-label>
                    </q-item-section>

                    <q-item-section side top>
                      <q-item-label
                        :class="
                          !item.isApprove && !item.isAccept
                            ? 'text-red'
                            : 'text-green'
                        "
                      >
                        {{
                          item.isAcceptSetting
                            ? item.isAccept
                              ? "รับทราบ"
                              : ""
                            : item.isApproveSetting
                            ? item.isApprove === true
                              ? "อนุมัติ"
                              : item.isApprove === false
                              ? "ไม่อนุมัติ"
                              : ""
                            : ""
                        }}
                      </q-item-label>

                      <q-btn
                        v-if="
                          item.isComment &&
                          state === index + 1 &&
                          item.isAccept === null &&
                          item.reason === null &&
                          item.isApprove === null
                        "
                        unelevated
                        rounded
                        @click.prevent="
                          (dataUserComment = item), (modalApprove = true)
                        "
                        label="แสดงความเห็น"
                        color="blue"
                      />
                    </q-item-section>
                  </q-item>
                </q-list>
              </div>

              <div v-if="state === index + 1" class="row q-gutter-x-sm">
                <q-btn
                  v-if="permission.isOperate"
                  @click.prevent="
                    (modalSelectPerson = true), (typeSelectPerson = 'operate')
                  "
                  label="ส่งยังไปผู้บังคับบัญชา"
                  color="public"
                />
                <q-btn
                  v-if="permission.isSign"
                  @click.prevent="
                    (modalSelectPerson = true), (typeSelectPerson = 'sign')
                  "
                  label="ส่งไปยังผู้มีอำนาจ"
                  color="public"
                />
              </div>

              <div v-if="permission.isChangeState && state === index + 1">
                <q-btn
                  :disable="
                    props.sysName && displayArray?.includes(props.sysName)
                      ? state === itemState.length - 1
                        ? !isCheckData
                        : false
                      : !isCheckData
                  "
                  @click.prevent="onChangeState"
                  label="ดำเนินการต่อ"
                  color="primary"
                />
              </div>
            </div>
          </q-timeline-entry>
        </q-timeline>
      </div>
    </q-card-section>
  </q-card>

  <DialogSelectPerson
    v-model:modal="modalSelectPerson"
    :state-id="stateId"
    :fetch-data="fetchCheckState"
    :type="typeSelectPerson"
  />

  <DialogApprove
    v-model:modal="modalApprove"
    :data-user-comment="dataUserComment"
    :fetch-data="fetchCheckState"
  />
</template>
