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

import type { QTableProps } from "quasar";
import type { DataOption } from "@/modules/15_development/interface/index/Main";
import type {
  FormIndicators,
  FormProject,
} from "@/modules/15_development/interface/request/FollowResult";
import type { DevelopmentEvaluations } from "@/modules/15_development/interface/response/FollowResult";

import DialogHeader from "@/components/DialogHeader.vue";

import { useCounterMixin } from "@/stores/mixin";

const modalDialog = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const indicatorId = ref<string>("");
const formIndicators = reactive<FormIndicators>({
  indicators: "",
  target: null,
  metricType: "",
  calculation: "",
  measuRement: "",
  results: "",
  obstacles: "",
  suggestions: "",
});

const formProject = reactive<FormProject>({
  isBudget: false,
  isNoPass: false,
  isOutBudget: false,
  isPassAllocate: false,
  isPassNoAllocate: false,
  project: "",
});

const $q = useQuasar();
const {
  showLoader,
  hideLoader,
  dialogConfirm,
  dialogRemove,
  messageError,
  success,
} = useCounterMixin();
const route = useRoute();
const projectId = ref<string>(route.params.id.toLocaleString());

/** หัวตาราง */
const rows = ref<DevelopmentEvaluations[]>([]); // ข้อมูลรายการ
const columns = ref<QTableProps["columns"]>([
  {
    name: "indicators",
    align: "left",
    label: "ชื่อตัวชี้วัด",
    sortable: true,
    field: "indicators",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ;",
  },
  {
    name: "target",
    align: "left",
    label: "ค่าเป้าหมาย",
    sortable: true,
    field: "target",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; ",
  },

  {
    name: "metricType",
    align: "left",
    label: "ประเภทตัวชี้วัด",
    sortable: true,
    field: "metricType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ;  ",
  },
  {
    name: "calculation",
    align: "left",
    label: "วิธีการคำนวณ/เครื่องมือในการใช้วัด",
    sortable: true,
    field: "calculation",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ; ",
  },
  {
    name: "measuRement",
    align: "left",
    label: "ระยะเวลา",
    sortable: true,
    field: "measuRement",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ; ",
  },
]);

const visibleColumns = ref<string[]>([
  "indicators",
  "target",
  "metricType",
  "calculation",
  "measuRement",
]);

const projectOp = ref<DataOption[]>([
  {
    id: "OFFER",
    name: "โครงการที่เสนอขอ TN",
  },
  {
    id: "NOOFFER",
    name: "โครงการที่ไม่เสนอขอ TN",
  },
]);

const metricTypeOp = ref<DataOption[]>([
  {
    id: "1",
    name: "ตัวชี้วัดความสำเร็จระดับผลผลิต (เป้าหมาย)",
  },
  {
    id: "2",
    name: "ตัวชี้วัดความสำเร็จระดับผลลัพธ์ (วัตถุประสงค์)",
  },
  {
    id: "3",
    name: "ตัวชี้วัดความสำเร็จระดับผลกระทบ (ประโยชน์ที่คาดว่าจะได้รับ)",
  },
]);

/** ดึงข้อมูลตัวชี้วัด */
function fetchData() {
  showLoader();
  http
    .get(config.API.developmentMainTab("tab4", projectId.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = data.developmentEvaluations;
      formProject.isBudget = data.isBudget;
      formProject.isNoPass = data.isNoPass;
      formProject.isOutBudget = data.isOutBudget;
      formProject.isPassAllocate = data.isPassAllocate;
      formProject.isPassNoAllocate = data.isPassNoAllocate;
      formProject.project = data.project;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เปิด dialog add/edit
 * @param statusEdit true/false
 * @param data data => EDIT
 */
function onClickAddIndicator(
  statusEdit: boolean = false,
  data: DevelopmentEvaluations | null = null
) {
  isEdit.value = statusEdit;
  if (statusEdit) {
    if (data) {
      indicatorId.value = data.id;
      formIndicators.indicators = data.indicators;
      formIndicators.target = data.target;
      formIndicators.metricType = data.metricType;
      formIndicators.calculation = data.calculation;
      formIndicators.measuRement = data.measuRement;
      formIndicators.results = data.results;
      formIndicators.obstacles = data.obstacles;
      formIndicators.suggestions = data.suggestions;
    }
  }
  modalDialog.value = true;
}

/** close Dialog and Clear */
function closeDialog() {
  modalDialog.value = false;
  formIndicators.indicators = "";
  formIndicators.target = null;
  formIndicators.metricType = "";
  formIndicators.calculation = "";
  formIndicators.measuRement = "";
  formIndicators.results = "";
  formIndicators.obstacles = "";
  formIndicators.suggestions = "";
}

/** dialog form save data  */
function onSubmitIndicators() {
  formIndicators.target = formIndicators.target
    ? Number(formIndicators.target)
    : formIndicators.target;

  const id = isEdit.value ? indicatorId.value : projectId.value;
  const path = isEdit.value ? "tab4_1_edit" : "tab4_1_add";
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.developmentMainTab(path, id), formIndicators)
      .then(() => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        fetchData();
        closeDialog();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** data delete */
function onClickDeleteIndicator(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.developmentMainTab("tab4_1", id))
      .then(() => {
        fetchData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** save Main data */
function onSubmit() {
  dialogConfirm($q, () => {
    if (formProject.project === "NOOFFER") {
      formProject.isNoPass = false;
      formProject.isPassAllocate = false;
      formProject.isPassNoAllocate = false;
    } else {
      formProject.isBudget = false;
      formProject.isOutBudget = false;
    }
    showLoader();
    http
      .put(config.API.developmentMainTab("tab4", projectId.value), formProject)
      .then(() => {
        fetchData();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** fetchData in page  */
onMounted(() => {
  fetchData();
});
</script>

<template>
  <!--CARD ตัวชี้วัดความสำเร็จ -->
  <q-card bordered style="border: 1px solid #d6dee1" class="q-mt-md">
    <div class="text-weight-medium bg-grey-1 q-py-sm q-px-md">
      ตัวชี้วัดความสำเร็จ
      <q-btn
        dense
        flat
        round
        color="primary"
        icon="add"
        @click="onClickAddIndicator()"
      >
        <q-tooltip>เพิ่มตัวชี้วัดความสำเร็จ</q-tooltip>
      </q-btn>
    </div>
    <div class="col-12"><q-separator /></div>
    <div class="col-12 q-pa-md">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        class="custom-header-table"
        :rows-per-page-options="[10, 25, 50, 100]"
        :visible-columns="visibleColumns"
      >
        <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-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <q-td>
              <q-btn
                dense
                flat
                round
                color="edit"
                icon="edit"
                @click="onClickAddIndicator(true, props.row)"
              >
                <q-tooltip>แก้ไขตัวชี้วัดความสำเร็จ</q-tooltip>
              </q-btn></q-td
            >
            <q-td>
              <q-btn
                dense
                flat
                round
                color="red"
                icon="delete"
                @click="onClickDeleteIndicator(props.row.id)"
              >
                <q-tooltip>ลบ</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <!--CARD ประเภทโครงการ -->
  <q-card bordered style="border: 1px solid #d6dee1" class="q-mt-md">
    <div class="text-weight-medium bg-grey-1 q-py-sm q-px-md">
      ประเภทโครงการ
    </div>
    <div class="col-12"><q-separator /></div>
    <q-form greedy @submit.prevent @validation-success="onSubmit">
      <div class="row q-pa-md q-col-gutter-sm">
        <div class="col-12 col-sm-6 col-md-4">
          <q-select
            dense
            outlined
            label="ประเภทโครงการ"
            v-model="formProject.project"
            :options="projectOp"
            option-label="name"
            option-value="id"
            hide-bottom-space
            map-options
            emit-value
            class="inputgreen"
          />
        </div>
        <div v-if="formProject.project !== ''" class="col-12">
          <div class="row" v-if="formProject.project == 'OFFER'">
            <div class="col-12">
              <q-checkbox
                v-model="formProject.isPassAllocate"
                label="ผ่านการพิจาณา ได้รับการจัดสรรงบประมาณตามข้อบัญญัติ"
              />
            </div>
            <div class="col-12">
              <q-checkbox
                v-model="formProject.isPassNoAllocate"
                label="ผ่านการพิจารณา ไม่ได้รับการจัดสรรงบประมาณตามข้อบัญญัติ แต่ได้รับการจัดสรรเงินนอกงบประมาณ"
              />
            </div>

            <div class="col-12">
              <q-checkbox
                v-model="formProject.isNoPass"
                label="ไม่ผ่านการพิจารณา แต่ได้รับการจัดสรรเงินนอกงบประมาณ"
              />
            </div>
          </div>
          <div class="row" v-else>
            <div class="col-12">
              <q-checkbox
                v-model="formProject.isBudget"
                label="แต่ได้รับการจัดสรรงบประมาณตามข้อบัญญัติ"
              />
            </div>
            <div class="col-12">
              <q-checkbox
                v-model="formProject.isOutBudget"
                label="แต่ได้รับการจัดสรรเงินนอกงบประมาณ"
              />
            </div>
          </div>
        </div>
      </div>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          unelevated
          label="บันทึก"
          id="onSubmit"
          type="submit"
          color="public"
          class="q-px-md"
        >
          <q-tooltip>บันทึกข้อมูล</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-form>
  </q-card>

  <q-dialog v-model="modalDialog" persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmitIndicators">
        <DialogHeader
          :tittle="isEdit ? 'แก้ไขตัวชี้วัด' : 'เพิ่มตัวชี้วัด'"
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section >
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                dense
                outlined
                class="inputgreen"
                label="ชื่อตัวชี้วัด"
                v-model="formIndicators.indicators"
                hide-bottom-space
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณากรอกชื่อตัวชี้วัด'}`,
      
                ]"
              />
            </div>
            <div class="col-6">
              <q-select
                dense
                outlined
                label="ประเภทตัวชี้วัด"
                v-model="formIndicators.metricType"
                :options="metricTypeOp"
                option-label="name"
                option-value="name"
                emit-value
                map-options
                class="inputgreen"
                hide-bottom-space
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณาเลือกประเภทตัวชี้วัด'}`,
      
                ]"
              />
            </div>


            <div class="col-6">
              <q-input
                dense
                outlined
                class="inputgreen"
                label="เป้าหมาย"
                v-model="formIndicators.target"
                mask="#"
                reverse-fill-mask
                hide-bottom-space
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณากรอกเป้าหมาย'}`,
      
                ]"
              />
            </div>
            <div class="col-12">
              <q-input
                outlined
                dense
                class="inputgreen"
                v-model="formIndicators.calculation"
                hide-bottom-space
                label="วิธีการคำนวณ/เครื่องมือ"
                type="textarea"
              />
            </div>
            <div class="col-12">
              <q-input
                outlined
                dense
                class="inputgreen"
                v-model="formIndicators.measuRement"
                hide-bottom-space
                label="ระยะเวลาวัดผล"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
