<script setup lang="ts">
import { onMounted, reactive, ref, computed } from "vue";
import { useQuasar, type QTableProps } from "quasar";
import { useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandDetail } from "@/modules/18_command/store/DetailStore";

import type { FormDataDetail } from "@/modules/18_command/interface/request/Main";
import type { DataOperators } from "@/modules/18_command/interface/response/Main";

import Dialog1_AddOperator from "@/modules/18_command/components/Step/Dialog1_AddOperetor.vue";

const $q = useQuasar();
const route = useRoute();
const store = useCommandDetail();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  success,
  dialogConfirm,
  convertDateToAPI,
  dialogRemove,
} = useCounterMixin();

/**
 * props
 */
const isChangeData = defineModel<boolean>("isChangeData", { required: true });
const props = defineProps({
  onCheckChangeData: { type: Function, required: true },
  fetchDataCommandList: { type: Function, required: true },
  formCommandList: { type: Object, required: true },
});

const isCanDelete = computed(
  () => (role: string) =>
    rows.value.filter((row) => row.roleName === "เจ้าหน้าที่ดำเนินการ")
      .length === 1 && role === "เจ้าหน้าที่ดำเนินการ"
); //เช็คสามารถลบรายชื่อผู้ลงนามในแนบท้ายคำสั่ง ได้หรือไม่

const commandId = ref<string>(route.params.id.toString()); //ID คำสั่ง
const commandCode = ref<string>(""); //รหัสคำสั่ง
const createdUserId = ref<string>(""); //ID ผู้สร้างคำสั่ง
// ฟอร์มข้อมูล
let formData = reactive<FormDataDetail>({
  issue: null, //คำสั่งเรื่อง
  commandNo: "", //คำสั่งเลขที่
  commandYear: null, //พ.ศ.
  detailHeader: "", //เนื้อหาคำสั่งขึ้นต้น
  detailBody: "", //เนื้อหาคำสั่งหลัก
  detailFooter: "", //เนื้อหาคำสั่งลงท้าย
  commandAffectDate: null, //วันที่ลงนาม
  commandExcecuteDate: null, //วันที่คำสั่งมีผล
  isBangkok: null, //คำสั่งสำนักปลัดกรุงเทพมหานคร
});
const commandVolume = ref<string>(""); //เล่มที่
const commandChapter = ref<string>(""); //ตอนที่
const isIdofficer = ref<boolean>(false); //เช็ค สกจ.

const rows = ref<Array<DataOperators>>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "roleName",
    label: "บทบาท",
    field: "roleName",
    align: "left",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    label: "ชื่อ-นามสกุล",
    field: "name",
    align: "left",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.prefix ?? ""}${row.firstName ?? ""} ${row.lastName ?? ""}`;
    },
  },
  {
    name: "posNo",
    label: "เลขที่ตำแหน่ง",
    field: "posNo",
    align: "left",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    label: "ตำแหน่ง",
    field: "position",
    align: "left",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<Array<string>>([
  "name",
  "posNo",
  "position",
  "roleName",
]);

const modalAddOperator = ref<boolean>(false); // แสดงเพิ่มรายชื่อลงนามในแนบท้ายคำสั่ง

/** ฟังก์ชันเช็ค สกจ.*/
async function fetchCheckIdofficer() {
  await http
    .get(config.API.checkIdofficer)
    .then((res) => {
      isIdofficer.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันบันทึกข้อมูลรายละเอียดคำสั่ง
 * และกำหนด isChangeData เป็น false
 */
async function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .put(config.API.commandAction(commandId.value, "tab1"), {
        ...formData,
        commandNo:
          commandCode.value === "C-PM-47"
            ? `${commandVolume.value}/${commandChapter.value}`
            : formData.commandNo,
        commandAffectDate: convertDateToAPI(formData.commandAffectDate),
        commandExcecuteDate: convertDateToAPI(formData.commandExcecuteDate),
      })
      .then(async () => {
        await props.fetchDataCommandList();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
        isChangeData.value = false;
      });
  });
}

/** ฟังกชันดึงข้อมูลรายชื่อเจ้าหน้าที่ดำเนินการ */
async function fetchDataOperatorList() {
  try {
    const res = await http.get(
      config.API.commandOperator + `/${commandId.value}`
    );

    const data = res.data.result;
    rows.value = data;
  } catch (err) {
    messageError($q, err);
  }
}

/**
 * ฟังก์ชันเลื่อนลำดับเจ้าหน้าที่ดำเนินการ
 * @param type ประเภท UP,DOWN
 * @param id ID เจ้าหน้าที่ดำเนินการที่ต้องการแก้ไขลำดับ
 */
async function onSwapData(type: string, id: string) {
  showLoader();
  try {
    await http.get(config.API.commandOperator + `/swap/${type}/${id}`);

    await fetchDataOperatorList();
    success($q, "บันทึกข้อมูลสำเร็จ");
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

/**
 * ฟังก์ชันลบเจ้าหน้าที่ดำเนินการ
 * @param id ID ที่ต้องการลบ
 */
function onDeleteData(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.delete(
        config.API.commandOperator + `/${commandId.value}/${id}`
      );

      await fetchDataOperatorList();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(async () => {
  try {
    showLoader();
    await fetchCheckIdofficer();
    await fetchDataOperatorList();
    formData.commandNo = props.formCommandList.commandNo;
    formData.commandYear = props.formCommandList.commandYear;
    formData.detailHeader = props.formCommandList.detailHeader;
    formData.detailBody = props.formCommandList.detailBody;
    formData.detailFooter = props.formCommandList.detailFooter;
    formData.issue = props.formCommandList.issue;
    formData.commandAffectDate = props.formCommandList.commandAffectDate;
    formData.commandExcecuteDate = props.formCommandList.commandExcecuteDate;
    formData.isBangkok = !isIdofficer.value
      ? null
      : props.formCommandList.isBangkok;
    commandCode.value = props.formCommandList.commandCode;
    const [volume, chapter] = props.formCommandList.commandNo.split("/");
    commandVolume.value = volume || "";
    commandChapter.value = chapter || "";
    createdUserId.value = props.formCommandList.createdUserId || "";
  } finally {
    hideLoader();
  }
});
</script>

<template>
  <div class="q-col-gutter-sm">
    <div class="col">
      <q-card flat bordered>
        <q-form greedy @submit.prevent @validation-success="onSubmit">
          <q-card-section>
            <div class="row q-col-gutter-sm">
              <div class="col-12">
                <q-input
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  outlined
                  dense
                  v-model="formData.issue"
                  hide-bottom-space
                  :label="`${'คำสั่งเรื่อง'}`"
                  @update:model-value="onCheckChangeData()"
                />
              </div>

              <div :class="commandCode !== 'C-PM-47' ? 'col-4' : 'col-12'">
                <div class="col-12 row q-col-gutter-sm">
                  <div class="col-6" v-if="commandCode !== 'C-PM-47'">
                    <q-input
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      outlined
                      dense
                      v-model="formData.commandNo"
                      hide-bottom-space
                      :label="`${'คำสั่งเลขที่'}`"
                      @update:model-value="onCheckChangeData()"
                    />
                  </div>
                  <label
                    class="col-1 flex justify-center items-center text-bold"
                    v-if="commandCode !== 'C-PM-47'"
                  >
                    /
                  </label>
                  <div class="col-4" v-if="commandCode === 'C-PM-47'">
                    <q-input
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      outlined
                      dense
                      v-model="commandVolume"
                      hide-bottom-space
                      :label="`${'เล่มที่'}`"
                      @update:model-value="onCheckChangeData()"
                    />
                  </div>

                  <div class="col-4" v-if="commandCode === 'C-PM-47'">
                    <q-input
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      outlined
                      dense
                      v-model="commandChapter"
                      hide-bottom-space
                      :label="`${'ตอนที่'}`"
                      @update:model-value="onCheckChangeData()"
                    />
                  </div>

                  <div :class="commandCode !== 'C-PM-47' ? 'col-5' : 'col-4'">
                    <datepicker
                      v-model="formData.commandYear"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      @update:model-value="onCheckChangeData()"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          dense
                          outlined
                          hide-bottom-space
                          :class="store.classInput(!store.readonly)"
                          :readonly="store.readonly"
                          :model-value="
                            formData.commandYear == null
                              ? null
                              : formData.commandYear + 543
                          "
                          label="ปี พ.ศ."
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                </div>
              </div>

              <div class="col-4">
                <datepicker
                  clearable
                  v-model="formData.commandAffectDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  @update:model-value="onCheckChangeData()"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      clearable
                      dense
                      outlined
                      hide-bottom-space
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      :model-value="
                        formData.commandAffectDate == null
                          ? null
                          : date2Thai(formData.commandAffectDate)
                      "
                      :label="`${'วันที่ลงนาม'}`"
                      @clear="() => (formData.commandAffectDate = null)"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-4">
                <datepicker
                  clearable
                  v-model="formData.commandExcecuteDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  @update:model-value="onCheckChangeData()"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      clearable
                      dense
                      outlined
                      hide-bottom-space
                      :class="store.classInput(!store.readonly)"
                      :readonly="store.readonly"
                      :model-value="
                        formData.commandExcecuteDate == null
                          ? null
                          : date2Thai(formData.commandExcecuteDate)
                      "
                      :label="`${'วันที่คำสั่งมีผล'}`"
                      @clear="() => (formData.commandExcecuteDate = null)"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <!-- เนื้อหาคำสั่งส่วนต้น -->
              <div class="col-12" v-if="commandCode !== 'C-PM-47'">
                <q-input
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  outlined
                  dense
                  v-model="formData.detailHeader"
                  hide-bottom-space
                  :label="`${'เนื้อหาคำสั่งขึ้นต้น (optional)'}`"
                  @update:model-value="onCheckChangeData()"
                  type="textarea"
                />
              </div>

              <!-- เนื้อหาคำสั่งส่วนกลาง -->
              <div class="col-12" v-if="commandCode !== 'C-PM-47'">
                <q-input
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  outlined
                  dense
                  v-model="formData.detailBody"
                  hide-bottom-space
                  :label="`${'เนื้อหาคำสั่งหลัก'}`"
                  @update:model-value="onCheckChangeData()"
                  type="textarea"
                  :rules="[(val: string) => !!val || `${'กรุณากรอกเนื้อหาคำสั่งหลัก'}`]"
                  lazy-rules
                />
              </div>

              <!-- เนื้อหาคำสั่งส่วนท้าย -->
              <div class="col-12" v-if="commandCode !== 'C-PM-47'">
                <q-input
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  outlined
                  dense
                  v-model="formData.detailFooter"
                  hide-bottom-space
                  :label="`${'เนื้อหาคำสั่งลงท้าย (optional)'}`"
                  @update:model-value="onCheckChangeData()"
                  type="textarea"
                />
              </div>

              <div
                class="col-12 q-gutter-sm"
                v-if="isIdofficer && commandCode !== 'C-PM-47'"
              >
                <q-radio
                  :disable="store.readonly"
                  keep-color
                  color="primary"
                  dense
                  v-model="formData.isBangkok"
                  label="คำสั่งสำนักปลัดกรุงเทพมหานคร"
                  val="OFFICE"
                />

                <q-radio
                  :disable="store.readonly"
                  keep-color
                  color="primary"
                  dense
                  v-model="formData.isBangkok"
                  label="คำสั่งกรุงเทพมหานคร"
                  val="BANGKOK"
                />
              </div>
            </div>
          </q-card-section>

          <q-separator />

          <q-card-actions align="right" v-if="!store.readonly">
            <q-btn label="บันทึก" color="public" type="submit" />
          </q-card-actions>
        </q-form>
      </q-card>
    </div>

    <div class="col">
      <q-card flat bordered>
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12 text-bold" v-if="!store.readonly">
              รายชื่อผู้ลงนามในแนบท้ายคำสั่ง
              <q-btn
                icon="add"
                flat
                round
                color="primary"
                unelevated
                @click.prevent.stop="modalAddOperator = true"
              >
                <q-tooltip>เพิ่มรายชื่อลงนามในแนบท้ายคำสั่ง</q-tooltip>
              </q-btn>
            </div>
            <div class="col-12">
              <d-table
                :rows="rows"
                :columns="columns"
                :visible-columns="visibleColumns"
                row-key="name"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th auto-width v-if="!store.readonly" />

                    <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 v-if="!store.readonly">
                      <q-btn
                        icon="mdi-arrow-up-bold"
                        :color="
                          props.pageIndex === 0 || rows.length === 0
                            ? 'grey'
                            : 'green'
                        "
                        flat
                        dense
                        round
                        :disable="props.pageIndex === 0 || rows.length === 0"
                        @click.prevent.stop="onSwapData('up', props.row.id)"
                      >
                        <q-tooltip>เลื่อนขึ้น</q-tooltip>
                      </q-btn>

                      <q-btn
                        icon="mdi-arrow-down-bold"
                        :color="
                          props.pageIndex === rows.length - 1 ||
                          rows.length === 0
                            ? 'grey'
                            : 'red'
                        "
                        flat
                        dense
                        round
                        :disable="
                          props.pageIndex === rows.length - 1 ||
                          rows.length === 0
                        "
                        @click.prevent.stop="onSwapData('down', props.row.id)"
                      >
                        <q-tooltip>เลื่อนลง</q-tooltip>
                      </q-btn>

                      <q-btn
                        icon="mdi-delete"
                        :color="
                          isCanDelete(props.row.roleName) ? 'grey' : 'red'
                        "
                        flat
                        dense
                        round
                        :disable="isCanDelete(props.row.roleName)"
                        @click.prevent.stop="onDeleteData(props.row.id)"
                      >
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                      </q-btn>
                    </q-td>

                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <div>
                        {{ col.value ?? "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>
  </div>

  <Dialog1_AddOperator
    v-model:modal="modalAddOperator"
    :command-id="commandId"
    :refresh-data="fetchDataOperatorList"
    :created-user-id="createdUserId"
  />
</template>
