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

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

import type { DataOption } from "@/modules/18_command/interface/index/Main";
import type {
  ListCommandSalaryType,
  PersonInfo,
} from "@/modules/18_command/interface/request/Main";

import DialogAddPerson from "@/modules/18_command/components/Step/Dialog2_AddPerson.vue";
import DialogSalary from "@/modules/18_command/components/Step/Dialog2_Salary.vue";

const $q = useQuasar();
const route = useRoute();
const commandId = ref<string>(route.params.id.toString()); //ID คำสั่ง
const store = useCommandDetail();
const {
  dialogConfirm,
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
} = useCounterMixin();

// const isChangeData = defineModel<boolean>("isChangeData", { required: true }); //การเปลี่ยนแปลงของข้อมูล
const props = defineProps({
  onCheckChangeData: { type: Function, required: true },
  fetchDataCommandList: { type: Function, required: true },
  commandSysId: { type: String, required: true },
  formCommandList: { type: Object, required: true },
});

const ListCommandSalary = ref<ListCommandSalaryType[]>([]);
const ListCommandSalaryMain = ref<ListCommandSalaryType[]>([]);

let selectPersonData = reactive<PersonInfo>({
  id: "",
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  profileId: "",
  order: 0,
  remarkVertical: null,
  remarkHorizontal: null,
  amount: 0,
  positionSalaryAmount: 0,
  mouthSalaryAmount: 0,
});
const commandReciveId = ref<string>(""); //เก็บ id commandReciveId
const templatePos = ref<string>("");
const position = ref<string>("");

const filter = ref<string>("");
const rows = ref<PersonInfo[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: (row) => rows.value.indexOf(row) + 1,
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "fullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.prefix ?? ""}${row.firstName ?? ""} ${row.lastName ?? ""}`;
    },
  },
  {
    name: "amount",
    align: "left",
    label: "เงินเดือน",
    field: "amount",
    format(val) {
      return val ? val.toLocaleString() : "-";
    },
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<String[]>(["no", "citizenId", "fullName", "amount"]);

const modalSalary = ref<boolean>(false);
const titleName = ref<string>("");

const modalPerson = ref<boolean>(false);

/**
 * function เลือกต้นแบบ tamplate ตำแหน่ง
 * @param val
 */
function updatePos(val: string) {
  const data = ListCommandSalaryMain.value.find(
    (item: ListCommandSalaryType) => item.id === val
  );
  if (data) {
    position.value = data.name; // เก็บแค่ค่า name
  } else {
    position.value = "";
  }
}

async function onSawpPos(val: any, type: string) {
  showLoader();
  await http
    .get(config.API.commandSwap("tab2", type, val.id))
    .then(async () => {
      await getPersonList();
      success($q, "แก้ไขข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.commandAction(id, "tab2"))
      .then(async () => {
        await getPersonList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function selectModal(data: PersonInfo) {
  selectPersonData = data;
  titleName.value = `${data.prefix ?? ""}${data.firstName ?? ""} ${
    data.lastName ?? ""
  }`;
  modalSalary.value = true;
  commandReciveId.value = data.id;
}

/**
 * ฟิลเตอร์ข้อมูลจาก input
 * @param val ค่าที่ป้อนให้ input
 * @param update function จาก quasar
 * @param filtername type ที่กำหนด ของ input นั้นๆ
 */
function filterSelector(val: string, update: Function, filtername: string) {
  switch (filtername) {
    case "pos":
      update(() => {
        ListCommandSalary.value = ListCommandSalaryMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
}

/** บันทึกข้แมูล ตำแหน่ง */
function savePosition() {
  dialogConfirm($q, async () => {
    const body = {
      commandSalaryId: templatePos.value,
      positionDetail: position.value,
    };
    showLoader();
    await http
      .put(config.API.commandAction(commandId.value, "tab2"), body)
      .then(async () => {
        await getPersonList();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

async function getCommandSalaryList(type: string) {
  await http
    .get(config.API.commandSalaryList(type))
    .then(async (res) => {
      const data = await res.data.result;
      ListCommandSalaryMain.value = data;
      ListCommandSalary.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/** ดึงข้อมูล บุคคล */
async function getPersonList() {
  await http
    .get(config.API.commandAction(commandId.value, "tab2"))
    .then(async (res) => {
      const data = await res.data.result;
      templatePos.value = data.commandSalaryId;
      position.value = data.positionDetail;
      rows.value = data.commandRecives;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

onMounted(async () => {
  const promises = [getPersonList()];

  if (props.commandSysId) {
    promises.push(getCommandSalaryList(props.commandSysId));
  }
  showLoader();
  await Promise.all(promises).finally(() => {
    hideLoader();
  });
});
</script>

<template>
  <div class="q-col-gutter-sm">
    <div class="col">
      <q-card>
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-select
                :class="store.classInput(!store.readonly)"
                :readonly="store.readonly"
                outlined
                dense
                lazy-rules
                borderless
                clearable
                v-model="templatePos"
                :label="`${'ต้นแบบ (template) ตำแหน่ง'}`"
                option-label="name"
                :options="ListCommandSalary"
                option-value="id"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                emit-value
                map-options
                input-debounce="0"
                @update:modelValue="updatePos"
                @filter="(inputValue: string,
                  doneFn: Function) => filterSelector(inputValue, doneFn, 'pos'
                  )"
              />
            </div>
            <div class="col-12">
              <q-input
                :class="store.classInput(!store.readonly)"
                :readonly="store.readonly"
                outlined
                dense
                v-model="position"
                hide-bottom-space
                :label="`${'ตำแหน่ง'}`"
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right" v-if="!store.readonly">
          <q-btn label="บันทึก" color="public" @click="savePosition" />
        </q-card-actions>
      </q-card>
    </div>
    <div class="col">
      <q-card>
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12 row q-pb-sm items-center">
              <q-space />

              <div class="items-center" style="display: flex">
                <!-- ค้นหาข้อความใน table -->
                <q-input
                  standout
                  dense
                  v-model="filter"
                  ref="filterRef"
                  outlined
                  debounce="300"
                  placeholder="ค้นหา"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </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: 140px"
                  class="gt-xs q-ml-sm"
                />
              </div>
            </div>
            <div class="col-12">
              <d-table
                :rows="rows"
                :columns="columns"
                :visible-columns="visibleColumns"
                :filter="filter.trim()"
                row-key="name"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th auto-width />
                    <q-th auto-width />
                    <q-th auto-width />
                    <q-th auto-width />
                    <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>
                      <q-btn
                        v-if="!store.readonly"
                        dense
                        flat
                        round
                        :color="props.rowIndex + 1 == 1 ? 'grey' : 'green'"
                        :disable="props.rowIndex + 1 == 1"
                        @click="onSawpPos(props.row, 'up')"
                        icon="mdi-arrow-up-bold"
                      >
                        <q-tooltip>เลื่อนลำดับขึ้น</q-tooltip>
                      </q-btn>
                    </q-td>
                    <q-td auto-width>
                      <q-btn
                        v-if="!store.readonly"
                        dense
                        flat
                        round
                        :color="
                          rows.length == props.rowIndex + 1 ? 'grey' : 'red'
                        "
                        :disable="rows.length == props.rowIndex + 1"
                        @click="onSawpPos(props.row, 'down')"
                        icon="mdi-arrow-down-bold"
                      >
                        <q-tooltip>เลื่อนลำดับลง</q-tooltip>
                      </q-btn>
                    </q-td>
                    <!-- v-if="statuscode !== true" -->
                    <q-td auto-width>
                      <q-btn
                        v-if="!store.readonly"
                        dense
                        flat
                        round
                        color="blue"
                        @click="selectModal(props.row)"
                        icon="edit"
                      >
                        <q-tooltip>แก้ไขข้อมูลลงทะเบียนประวัติ</q-tooltip>
                      </q-btn>
                    </q-td>

                    <q-td auto-width>
                      <q-btn
                        v-if="!store.readonly"
                        dense
                        flat
                        round
                        color="red"
                        @click="onDelete(props.row.id)"
                        icon="mdi-delete"
                      >
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                      </q-btn>
                    </q-td>
                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      {{ col.value ?? "-" }}
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>
  </div>

  <DialogAddPerson v-model:modal="modalPerson" />
  <DialogSalary
    v-model:modal="modalSalary"
    :title-name="titleName"
    :command-edit-recive="commandReciveId"
    :get-data="getPersonList"
    :select-person-data="selectPersonData"
    :type="formCommandList.commandTypeName"
    :command-code="formCommandList.commandCode"
    :command-sys-id="formCommandList.commandSysId"
  />
</template>
