<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 modalData = ref<any>({
  salaryAmount: null,
  positionSalaryAmount: null,
  monthSalaryAmount: null,
});
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: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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.orderid
    ? route.params.orderid.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;
      // console.log(data);
      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,
        });
      });
      // console.log("list", list);
      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"
  ) {
    return false;
  }
  return true;
});
const dialogDeleteData = async (id: string) => {
  dialogRemove($q, () => deleteData(id));
};

const deleteData = async (id: string) => {
  await http
    .delete(config.API.personsOrder(id))
    .then((res) => {
      //   const data = res.data.result;
      //   console.log(res);
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      await conditionData();
    });
};

const swapUp = async (id: string) => {
  // id = personalId
  await http
    .put(config.API.swapUpOrder(id))
    .then((res) => {
      //   const data = res.data.result;
      //   console.log(res);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await conditionData();
      hideLoader();
    });
};

const swapDown = async (id: string) => {
  // id = personalId
  await http
    .put(config.API.swapDownOrder(id))
    .then((res) => {
      //   const data = res.data.result;
      //   console.log(res);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await conditionData();
      hideLoader();
    });
};

const upDown = async (value: any, up: boolean = true) => {
  const indexCurrent = value.rowIndex;
  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>("");
const selectModal = (e: any) => {
  //   console.log(e);
  titleName.value = e.name;
  personalId.value = e.personalId;
  modalOpenClose(e.personalId);
};

const modalOpenClose = async (personalId: string) => {
  modal.value = !modal.value;
  if (modal.value) {
    await fetchSalary(personalId);
  } else {
    titleName.value = "";
  }
  myForm.value?.reset();
};
const fetchSalary = async (personalId: string) => {
  //   console.log(personalId);
  showLoader();
  await http
    .get(config.API.salaryOrder(personalId))
    .then((res: any) => {
      console.log(res);
      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,
      };
      //   console.log("data", modalData.value);
    })
    .catch((e) => {
      //   console.log(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((res: any) => {
        // console.log(res);
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        // console.log(e);
        messageError($q, e);
      })
      .finally(async () => {
        await conditionData();
        modal.value = false;
        hideLoader();
      });
  });
};

const modalAddChange = async () => {
  modalAdd.value = !modalAdd.value;
  if (modalAdd.value == true) {
    const id = route.params.orderid
      ? route.params.orderid.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;
      console.log(data);
      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;
      // rows2.value = list.filter((e: any) => e.selectStatus === false);
    })
    .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);
          },
          "ยืนยันการเพิ่มรายชื่อออกคำสั่ง",
          "ต้องการยืนยันการเพิ่มรายชื่อออกคำสั่งนี้ใช่หรือไม่?"
        );
      }
    });
  }
};

const addlist = async (data: Object) => {
  const id = route.params.orderid
    ? route.params.orderid.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) => {
        console.log(e);
        messageError($q, e);
      })
      .finally(() => {
        modalAddChange();
      });
  }
};

const save = async () => {
  // console.log("save===>", rows.value);
  // console.log(statuscode.value);
  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,
  };
};
</script>

<template>
  <div>
    <div class="q-py-md q-pl-md" style="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-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 items-center 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>
            </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" persistent>
    <q-card style="width: 50vw; max-width: 50vw">
      <q-form ref="myFormAdd">
        <DialogHeader tittle="รายชื่อในการออกคำสั่ง" :close="modalAddChange" />
        <q-separator />
        <q-card-section class="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 />
        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            color="public"
            @click="saveModalAdd"
            class="q-px-md"
            ><!-- icon="mdi-content-save-outline"
        <q-tooltip>บันทึก</q-tooltip> -->
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
