div
<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-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"
              @click="selectModal(props.row)"
              >{{ 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>
              <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"
        ><!-- icon="mdi-content-save-outline"
        <q-tooltip>บันทึก</q-tooltip> -->
      </q-btn>
      <!-- <q-btn dense flat round color="primary" icon="chevron_right" @click="next">
        <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 items-center q-col-gutter-sm">
                <div class="col-xs-6 col-sm-6 col-md-6">
                  <q-input
                    outlined
                    dense
                    lazy-rules
                    v-model="modalData.salaryAmount"
                    :rules="[(val) => !!val || `${'กรุณากรอกเงินเดือน'}`]"
                    :label="`${'เงินเดือน'}`"
                    type="number"
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-6">
                  <q-input
                    outlined
                    dense
                    lazy-rules
                    v-model="modalData.positionSalaryAmount"
                    :label="`${'เงินประจำตำแหน่ง'}`"
                    type="number"
                    hide-bottom-space
                  />
                  <!-- :rules="[
                      (val) => !!val || `${'กรุณากรอกเงินประจำตำแหน่ง'}`,
                    ]" -->
                </div>

                <div class="col-xs-6 col-sm-6 col-md-6">
                  <q-input
                    outlined
                    dense
                    lazy-rules
                    v-model="modalData.mouthSalaryAmount"
                    :label="`${'เงินค่าตอบแทนรายเดือน'}`"
                    type="number"
                    hide-bottom-space
                  />
                  <!-- :rules="[
                      (val) => !!val || `${'กรุณากรอกเงินค่าตอบแทนรายเดือน'}`,
                    ]" -->
                </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>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import type { QInput } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import type { QTableProps, QForm } from "quasar";
import { useRoute } from "vue-router";
import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import type { ResponseData } from "@/modules/05_placement/interface/response/Order";

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

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 { dialogMessage, messageError, showLoader, hideLoader, success } = mixin;

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

const modalData = ref<any>({
  salaryAmount: 0,
  positionSalaryAmount: 0,
  mouthSalaryAmount: 0,
});
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 orderId = ref<string>(route.params.orderid.toString());

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);
  }
};

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,
        });
      });
      //   console.log("list", list);
      rows.value = list;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

// const saveSalary = async (id: string) => {
//   await http
//     .put(config.API.salaryOrder(id))
//     .then((res) => {
//       //   const data = res.data.result;
//       //   console.log(res);
//       success($q, "บันทึกข้อมูลสำเร็จ");
//     })
//     .catch((e) => {
//       messageError($q, e);
//     })
//     .finally(() => {
//       hideLoader();
//     });
// };

const dialogDeleteData = async (id: string) => {
  dialogMessage(
    $q,
    "ยืนยันการลบข้อมูล",
    "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
    "mdi-help-circle-outline",
    "ตกลง",
    "red",
    () => deleteData(id),
    undefined
  );
};

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);
    // rows.value[indexCurrent] = rows.value[indexCurrent - 1];
    // rows.value[indexCurrent - 1] = value.row;
  } else {
    await swapDown(value.row.personalId);
    // rows.value[indexCurrent] = rows.value[indexCurrent + 1];
    // rows.value[indexCurrent + 1] = value.row;
  }
};

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;
  // modalData.value = {
  //   salaryAmount: 0,
  //   positionSalaryAmount: 0,
  //   mouthSalaryAmount: 0,
  // };

  modalOpenClose(e.personalId);
};

const modalOpenClose = async (personalId: string) => {
  modal.value = !modal.value;
  if (!modal.value) {
    titleName.value = "";
  }
  if (modal.value == true) {
    await fetchSalary(personalId);
  }
};
const fetchSalary = async (personalId: string) => {
  console.log(personalId);
  showLoader();
  await http
    .get(config.API.salaryOrder(personalId))
    .then((res: any) => {
      console.log(res);
      let salary = res.data.result;
      modalData.value = {
        salaryAmount: salary.salaryAmount,
        positionSalaryAmount: salary.positionSalaryAmount,
        mouthSalaryAmount: salary.monthSalaryAmount,
      };
    })
    .catch((e) => {
      console.log(e);
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
const putSalary = async (salary: any) => {
  modalData.value = {
    salaryAmount: Number(salary.salaryAmount),
    positionSalaryAmount: Number(salary.positionSalaryAmount),
    monthSalaryAmount: Number(salary.mouthSalaryAmount),
  };
  $q.dialog({
    title: "ยืนยันการบันทึกข้อมูล",
    message: "ต้องการยืนยันการบันทึกข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  }).onOk(async () => {
    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;
      });
  });
};

const modalAddChange = async () => {
  modalAdd.value = !modalAdd.value;
  if (modalAdd.value == true) {
    await fetchaddlist(orderId.value);
  } 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) {
        $q.dialog({
          title: "ยืนยันการเพิ่มรายชื่อออกคำสั่ง",
          message: "ต้องการยืนยันการเพิ่มรายชื่อออกคำสั่งนี้ใช่หรือไม่?",
          cancel: {
            flat: true,
            color: "negative",
          },
          persistent: true,
        }).onOk(async () => {
          let data = [];
          data.push(...selected.value.map((e: any) => e.refRecordId));
          // console.log(data);
          addlist(data);
        });
      }
    });
  }
};
const addlist = async (data: Object) => {
  await http
    .post(config.API.personsOrder(orderId.value), data)
    .then(() => {
      success($q, "บันทึกสำเร็จ");
    })
    .catch((e: any) => {
      console.log(e);
      messageError($q, e);
    })
    .finally(() => {
      modalAddChange();
    });
};

const click = (e: any) => {
  console.log(e);
  console.log(rows.value.length);
};

const save = () => {
  $q.dialog({
    title: "ยืนยันการบันทึกข้อมูล",
    message: "ต้องการยืนยันการบันทึกข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  }).onOk(async () => {
    success($q, "บันทึกข้อมูลสำเร็จ");
    next();
  });
  // if (selected.value.length > 0) {
  //   next();
  // } else {
  //   dialogMessage(
  //     $q,
  //     "ข้อความแจ้งเตือน",
  //     "กรุณาเลือกรายชื่อ",
  //     "warning",
  //     undefined,
  //     "orange",
  //     undefined,
  //     undefined,
  //     true
  //   );
  // }
};

const selectData = (row: any) => {};

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>
<style lang="scss"></style>
