<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";

import type { QInput } from "quasar";
import type { QTableProps, QForm } from "quasar";
import type { ResponseData } from "@/modules/05_placement/interface/response/Order";

import http from "@/plugins/http";
import config from "@/app.config";

import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import CurruncyInput from "@/components/CurruncyInput.vue";

const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const next = () => props.next();
const previous = () => props.previous();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  dialogMessageNotify,
  dialogConfirm,
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
} = mixin;

const route = useRoute();
const $q = useQuasar();

const routeName = ref<string>(route.name ? route.name.toString() : "");
const modalData = ref<any>({
  salaryAmount: null,
  positionSalaryAmount: null,
  monthSalaryAmount: null,
  remarkVertical: "",
  remarkHorizontal: "",
});
const myForm = ref<QForm | null>(null);
const myFormAdd = ref<QForm | null>(null);
const modal = ref<boolean>(false);
const modalAdd = ref<boolean>(false);
const titleName = ref<string>("");
const filterRef = ref<QInput>();
const filter = ref<string>("");
const visibleColumns = ref<String[]>(["no", "idCard", "name", "education"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    sortable: false,
  },
  {
    name: "idCard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "idCard",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "name",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  // {
  //   name: "education",
  //   align: "left",
  //   label: "วุฒิการศึกษาในการออกคำสั่ง",
  //   field: "education",
  //   sortable: true,
  //   sort: (a: string, b: string) =>
  //     a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  // },
]);
const rows = ref<ResponseData[]>([]);
const rows2 = ref<ResponseData[]>([]);
const selected = ref<ResponseData[]>([]);
const orderTypeCode = ref<string>("");

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

const conditionData = async () => {
  const id = route.params.id
    ? route.params.id.toString()
    : localStorage.getItem("orderId")
    ? localStorage.getItem("orderId")
    : null;
  if (id !== null) {
    await getData(id);
    await fetchOrder(id);
  }
};
// เรียกรายชื่อออกคำสั่ง
const getData = async (id: string) => {
  showLoader();
  await http
    .get(config.API.personsselectedOrder(id))
    .then((res) => {
      const data = res.data.result;
      let list: ResponseData[] = [];
      data.map((r: ResponseData) => {
        list.push({
          education: r.education ?? "",
          idCard: r.idCard ?? "",
          name: r.name ?? "",
          personalId: r.personalId ?? "",
          selectStatus: r.selectStatus !== null ? r.selectStatus : false,
          sequence: r.sequence !== null ? r.sequence : 0,
          refRecordId: r.refRecordId,
          salaryAmount: r.salaryAmount,
          positionSalaryAmount: r.positionSalaryAmount,
          monthSalaryAmount: r.monthSalaryAmount,
        });
      });
      rows.value = list;
      selected.value = rows.value;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
//เรียกรายละเอียดของคำสั่ง
const fetchOrder = async (id: string) => {
  await http
    .get(config.API.detailOrder(id))
    .then((res) => {
      let data = res.data.result;
      orderTypeCode.value = data.orderTypeCode;
    })
    .catch((err) => {
      messageError($q, err);
    });
};
// เช็คคำสั่ง
const statuscode = computed(() => {
  if (
    orderTypeCode.value === "c-pm-01" ||
    orderTypeCode.value === "c-pm-02" ||
    orderTypeCode.value === "c-pm-03" ||
    orderTypeCode.value === "c-pm-04" ||
    orderTypeCode.value === "c-pm-05" ||
    orderTypeCode.value === "c-pm-06" ||
    orderTypeCode.value === "c-pm-07" ||
    orderTypeCode.value === "c-pm-08" ||
    orderTypeCode.value === "c-pm-09" ||
    orderTypeCode.value === "c-pm-14" ||
    orderTypeCode.value === "c-pm-21" ||
    orderTypeCode.value === "c-pm-22"
  ) {
    return false;
  }
  return true;
});
// เช็คหมายเหตุ
const checkNote = computed(() => {
  if (
    orderTypeCode.value === "c-pm-01" ||
    orderTypeCode.value === "c-pm-02" ||
    orderTypeCode.value === "c-pm-03" ||
    orderTypeCode.value === "c-pm-04"
  ) {
    return true;
  }
  return false;
});
// ยืนยันลบข้อมูลรายชื่อ
const dialogDeleteData = async (id: string) => {
  dialogRemove($q, () => deleteData(id));
};
// ลบข้อมูลรายชื่อ API
const deleteData = async (id: string) => {
  await http
    .delete(config.API.personsOrder(id))
    .then(() => {
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      await conditionData();
    });
};
// ปรับรายชื่อขึ้น
const swapUp = async (id: string) => {
  await http
    .put(config.API.swapUpOrder(id))
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await conditionData();
      hideLoader();
    });
};
// ปรับรายชื่อลง
const swapDown = async (id: string) => {
  await http
    .put(config.API.swapDownOrder(id))
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await conditionData();
      hideLoader();
    });
};

const upDown = async (value: any, up: boolean = true) => {
  if (up) {
    await swapUp(value.row.personalId);
  } else {
    await swapDown(value.row.personalId);
  }
};
// บันทึกเงินเดือน
const saveModal = () => {
  if (myForm.value !== null) {
    myForm.value.validate().then(async (result: boolean) => {
      if (result) {
        putSalary(modalData.value);
      }
    });
  }
};
const personalId = ref<string>("");
// เปิด popup เงินเดือน
const selectModal = (e: any) => {
  titleName.value = e.name;
  personalId.value = e.personalId;
  modalOpenClose(e.personalId);
};
// เปิด popup เงินเดือน
const modalOpenClose = async (personalId: string) => {
  modal.value = !modal.value;
  if (modal.value) {
    await fetchSalary(personalId);
  } else {
    titleName.value = "";
  }
  myForm.value?.reset();
};
// เรียกข้อมูลเงินเดือนตาม personalId
const fetchSalary = async (personalId: string) => {
  showLoader();
  await http
    .get(config.API.salaryOrder(personalId))
    .then((res: any) => {
      const data = res.data.result;
      modalData.value = {
        salaryAmount:
          data.salaryAmount === 0 &&
          data.positionSalaryAmount === 0 &&
          data.monthSalaryAmount === 0
            ? null
            : data.salaryAmount,
        positionSalaryAmount:
          data.salaryAmount === 0 &&
          data.positionSalaryAmount === 0 &&
          data.monthSalaryAmount === 0
            ? null
            : data.positionSalaryAmount,
        monthSalaryAmount:
          data.salaryAmount === 0 &&
          data.positionSalaryAmount === 0 &&
          data.monthSalaryAmount === 0
            ? null
            : data.monthSalaryAmount,
        remarkVertical: data.remarkVertical,
        remarkHorizontal: data.remarkHorizontal,
      };
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
// ยืนยันการแก้ไขข้อมูลเงินเดือน
const putSalary = async (salary: any) => {
  dialogConfirm($q, async () => {
    showLoader();
    if (modalData.value.salaryAmount === null) {
      modalData.value.salaryAmount = 0;
    }
    if (modalData.value.positionSalaryAmount === null) {
      modalData.value.positionSalaryAmount = 0;
    }
    if (modalData.value.monthSalaryAmount === null) {
      modalData.value.monthSalaryAmount = 0;
    }
    await http
      .put(config.API.salaryOrder(personalId.value), modalData.value)
      .then(() => {
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await conditionData();
        modal.value = false;
        hideLoader();
      });
  });
};
// เปิด popup เพิ่มข้อมูลรายชื่อ
const modalAddChange = async () => {
  modalAdd.value = !modalAdd.value;
  if (modalAdd.value == true) {
    const id = route.params.id
      ? route.params.id.toString()
      : localStorage.getItem("orderId")
      ? localStorage.getItem("orderId")
      : null;
    if (id !== null) {
      await fetchaddlist(id);
    }
  } else await conditionData();
};
// เรียกข้อมูลราขชื่อที่จะเพิ่ม
const fetchaddlist = async (id: string) => {
  showLoader();
  await http
    .get(config.API.personsOrder(id))
    .then((res) => {
      const data = res.data.result;
      let list = [];
      list = data.map((r: ResponseData) => ({
        education: r.education ?? "",
        idCard: r.idCard ?? "",
        name: r.name ?? "",
        personalId: r.personalId ?? "",
        selectStatus: r.selectStatus !== null ? r.selectStatus : false,
        sequence: r.sequence !== null ? r.sequence : 0,
        refRecordId: r.refRecordId,
      }));
      rows2.value = list;
      selected.value = rows.value;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
// ยืนยันการเพิ่มรายชื่อออกคำสั่ง
const saveModalAdd = () => {
  if (myFormAdd.value !== null) {
    myFormAdd.value.validate().then(async (result: boolean) => {
      if (result && selected.value.length !== 0) {
        dialogConfirm(
          $q,
          () => {
            let data = [];
            data.push(...selected.value.map((e: any) => e.refRecordId));
            addlist(data);
          },
          "ยืนยันการเพิ่มรายชื่อออกคำสั่ง",
          "ต้องการยืนยันการเพิ่มรายชื่อออกคำสั่งนี้ใช่หรือไม่?"
        );
      }
    });
  }
};
// เพิ่มรายชื่อ API
const addlist = async (data: Object) => {
  const id = route.params.id
    ? route.params.id.toString()
    : localStorage.getItem("orderId")
    ? localStorage.getItem("orderId")
    : null;
  if (id !== null) {
    await http
      .post(config.API.personsOrder(id), data)
      .then(() => {
        success($q, "บันทึกสำเร็จ");
      })
      .catch((e: any) => {
        messageError($q, e);
      })
      .finally(() => {
        modalAddChange();
      });
  }
};
// บันทึกข้อมูล step 2
const save = async () => {
  const check = rows.value.find((x: any) => x.salaryAmount == 0);
  if (
    (selected.value.length > 0 && !check) ||
    (statuscode.value === true && selected.value.length > 0)
  ) {
    dialogConfirm($q, () => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      next();
    });
  } else if (check && statuscode.value === false) {
    dialogMessageNotify($q, "ระบุรายละเอียดการเงินไม่ครบ");
  } else {
    dialogMessageNotify($q, "กรุณาเลือกรายชื่อ");
  }
};

const refresh = async () => {
  // await conditionData();
  modalAddChange();
  selected.value = [];
};

const resetFilter = () => {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  filter.value = "";
  filterRef.value!.focus();
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
const pagination = ref({
  // sortBy: "OrderDate,OrderType",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
</script>

<template>
  <div>
    <div class="q-py-md q-pl-md" style="max-height: 68vh; overflow-y: scroll">
      <div class="col-12 row q-pb-sm items-center">
        <q-btn flat round color="primary" @click="refresh" icon="mdi-plus">
          <q-tooltip>เพิ่มข้อมูล</q-tooltip>
        </q-btn>
        <q-space />
        <div class="items-center" style="display: flex">
          <!-- ค้นหาข้อความใน table -->
          <q-input
            standout
            dense
            v-model="filter"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
            style="max-width: 200px"
            class="q-ml-sm"
          >
            <template v-slot:append>
              <q-icon v-if="filter == ''" name="search" />
              <q-icon
                v-if="filter !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              />
            </template>
          </q-input>
          <!-- แสดงคอลัมน์ใน table -->
          <q-select
            v-model="visibleColumns"
            :display-value="$q.lang.table.columns"
            multiple
            outlined
            dense
            :options="columns"
            options-dense
            option-value="name"
            map-options
            emit-value
            style="min-width: 150px"
            class="gt-xs q-ml-sm"
          />
        </div>
      </div>
      <d-table
        :rows="rows"
        :columns="columns"
        :visible-columns="visibleColumns"
        :filter="filter"
        row-key="name"
      >
        <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-th auto-width />
            <q-th auto-width v-if="statuscode !== true" />
          </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">{{
              col.name == "no" ? props.rowIndex + 1 : col.value
            }}</q-td>
            <q-td auto-width>
              <q-btn
                dense
                size="12px"
                flat
                round
                :color="props.rowIndex + 1 == 1 ? 'grey' : 'green'"
                :disable="props.rowIndex + 1 == 1"
                @click="upDown(props)"
                icon="mdi-arrow-up-bold"
              >
                <!-- <q-tooltip>เลื่อนลำดับขึ้น</q-tooltip> -->
              </q-btn>
            </q-td>
            <q-td auto-width>
              <q-btn
                dense
                size="12px"
                flat
                round
                :color="rows.length == props.rowIndex + 1 ? 'grey' : 'red'"
                :disable="rows.length == props.rowIndex + 1"
                @click="upDown(props, false)"
                icon="mdi-arrow-down-bold"
              >
                <!-- <q-tooltip>เลื่อนลำดับลง</q-tooltip> -->
              </q-btn>
            </q-td>
            <q-td auto-width v-if="statuscode !== true">
              <q-btn
                v-if="props.row.salaryAmount === 0"
                dense
                size="12px"
                flat
                round
                color="blue"
                @click="selectModal(props.row)"
                icon="mdi-cash-multiple"
              >
                <q-tooltip>เงินเดือน</q-tooltip>
              </q-btn>
              <q-btn
                v-else
                dense
                size="12px"
                flat
                round
                color="primary"
                @click="selectModal(props.row)"
                icon="mdi-information-outline"
              >
                <q-tooltip>เงินเดือน</q-tooltip>
              </q-btn>
            </q-td>

            <q-td auto-width>
              <q-btn
                dense
                size="12px"
                flat
                round
                color="red"
                @click="dialogDeleteData(props.row.personalId)"
                icon="mdi-delete"
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
    <q-separator />
    <div class="flex justify-end q-pa-sm q-gutter-sm">
      <q-btn
        dense
        outline
        color="primary"
        icon="chevron_left"
        @click="previous"
        class="q-pr-md"
        label="กรอกรายละเอียด"
      >
      </q-btn>
      <q-btn
        dense
        unelevated
        label="บันทึก"
        color="public"
        @click="save"
        class="q-px-md"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
    </div>
  </div>
  <!--********************************** เงินเดือน ********************************** -->
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 50vw; max-width: 50vw">
      <q-form ref="myForm">
        <DialogHeader :tittle="titleName" :close="modalOpenClose" />
        <q-separator />
        <q-card-section class="q-pa-sm bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12">
              <div class="col-12 row q-py-sm q-col-gutter-sm">
                <div class="col-xs-6 col-sm-6 col-md-6">
                  <CurruncyInput
                    :edit="true"
                    :dense="true"
                    v-model="modalData.salaryAmount"
                    :label="`${'เงินเดือน'}`"
                    :rules="[(val: any) => !!val || `${'กรุณากรอกเงินเดือน'}`]"
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-6">
                  <CurruncyInput
                    :edit="true"
                    :dense="true"
                    v-model="modalData.positionSalaryAmount"
                    :label="`${'เงินประจำตำแหน่ง'}`"
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-6">
                  <CurruncyInput
                    :edit="true"
                    :dense="true"
                    v-model="modalData.monthSalaryAmount"
                    :label="`${'เงินค่าตอบแทนรายเดือน'}`"
                    hide-bottom-space
                  />
                </div>
                <div class="col-xs-6 col-sm-6 col-md-12" v-if="checkNote">
                  <q-input
                    dense
                    outlined
                    v-model="modalData.remarkVertical"
                    label="หมายเหตุแนวตั้ง"
                    type="textarea"
                    rows="2"
                  />
                </div>
                <div class="col-xs-6 col-sm-6 col-md-12" v-if="checkNote">
                  <q-input
                    dense
                    outlined
                    v-model="modalData.remarkHorizontal"
                    type="textarea"
                    label="หมายเหตุแนวนอน"
                    rows="2"
                  />
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            color="public"
            @click="saveModal"
            class="q-px-md"
          >
            <!-- icon="mdi-content-save-outline" -->
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
  <!--********************************** รายชื่อ ********************************** -->
  <q-dialog v-model="modalAdd" class="dialog" persistent>
    <q-card style="width: 50vw; max-width: 50vw">
      <q-form ref="myFormAdd">
        <DialogHeader tittle="รายชื่อในการออกคำสั่ง" :close="modalAddChange" />
        <q-separator color="grey-4" />
        <q-card-section
          style="max-height: 60vh"
          class="scroll q-pa-sm bg-grey-1"
        >
          <d-table
            :rows="rows2"
            :columns="columns"
            :visible-columns="visibleColumns"
            :filter="filter"
            row-key="name"
            :selection="'multiple'"
            v-model:selected="selected"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th auto-width>
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </q-th>
                <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" class="cursor-pointer">
                <q-td>
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </q-td>
                <q-td
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  >{{ col.name == "no" ? props.rowIndex + 1 : col.value }}</q-td
                >
              </q-tr>
            </template>
          </d-table>
        </q-card-section>
        <q-separator color="grey-4" />
        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            color="public"
            @click="saveModalAdd"
            class="q-px-md"
          >
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
