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

import type { QInput, QForm } from "quasar";
import type { treeTab } from "@/modules/05_placement/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";
import type { QTableProps } from "quasar";
import type {
  ResponseOrganiz,
  ResponseCopyOrder,
  DataCopyOrder,
} from "@/modules/10_order/interface/response/Order";
import type { RequestCopyOrder } from "@/modules/05_placement/interface/request/Order";
import { useRoute } from "vue-router";
import type { DataOption } from "@/modules/10_order/interface/index/Main";
import DialogOrgSelectOneStep from "@/components/Dialogs/DialogOrgSelectOneStep.vue";
import { useOrderPlacementDataStore } from "@/modules/10_order/store";

const DataStore = useOrderPlacementDataStore();

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 = async () => {
  if (DataStore.typeOrder === "C-PM-38") {
    await props.previous();
    await props.previous();
  } else {
    props.previous();
  }
};

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const { dialogRemove, messageError, showLoader, hideLoader, success } = mixin;

const route = useRoute();

const myForm = ref<QForm | null>(null);
const filterRef = ref<QInput>();
const filter = ref<string>("");

const modal = ref<boolean>(false);

const expanded = ref<string[]>([]);
const selected = ref<string>("");
const nodesTree = ref<treeTab[]>([]);

const selectedModal = ref<ResponseOrganiz[]>([]);

const rowsModal = ref<ResponseOrganiz[]>([]);

const optionSelect = ref<DataOption[]>([
  { id: 1, name: "อีเมล" },
  { id: 2, name: "กล่องข้อความ" },
]);

const visibleColumns = ref<String[]>([
  "no",
  "idCard",
  "name",
  "position",
  "unit",
  "send",
]);
const columns = ref<QTableProps["columns"]>([
  { name: "no", align: "center", 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: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "unit",
    align: "left",
    label: "หน่วยงาน",
    field: "unit",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "send",
    align: "left",
    label: "ช่องทางการส่งสำเนา",
    field: "send",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const rows = ref<DataCopyOrder[]>([]);

const editRows = ref<DataCopyOrder[]>([]);

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

const listModal = async (id: string) => {
  showLoader();
  await http
    .get(config.API.copyOrderPersonsId(id))
    .then((res) => {
      const data = res.data.result;
      let list: ResponseOrganiz[] = [];
      data.map((r: ResponseOrganiz) => {
        list.push({
          firstName: r.firstName ?? "",
          idCard: r.idCard ?? "",
          lastName: r.lastName ?? "",
          name: r.name ?? "",
          position: r.position ?? "",
          prefixId: r.prefixId ?? "",
          profileId: r.profileId ?? "",
          unit: r.unit ?? "",
        });
      });
      rowsModal.value = list;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};
// เช็คค่า orderid
const conditionId = async () => {
  const id = route.params.orderid
    ? route.params.orderid.toString()
    : localStorage.getItem("orderId")
    ? localStorage.getItem("orderId")
    : null;
  if (id !== null) {
    await getData(id);
    fetchOrder(id);
  }
};
// เรียก้อมูลใน Table
const getData = async (id: string) => {
  showLoader();
  await http
    .get(config.API.copyOrderId(id))
    .then((res) => {
      const data = res.data.result;
      let list: DataCopyOrder[] = [];
      data.map((r: ResponseCopyOrder) => {
        let selectCopyOrder = [];
        if (r.emailChannel) {
          selectCopyOrder.push(1);
        }
        if (r.inboxChannel) {
          selectCopyOrder.push(2);
        }
        list.push({
          personalId: r.personalId ?? "",
          name: r.name ?? "",
          idCard: r.idCard ?? "",
          position: r.position ?? "",
          unit: r.unit ?? "",
          send: "",
          mutiselect: selectCopyOrder,
        });
      });
      if (editRows.value.length > 0) {
        list.map((r: DataCopyOrder) => {
          editRows.value.map((e: DataCopyOrder) => {
            if (r.personalId == e.personalId) {
              r.mutiselect = e.mutiselect;
            }
          });
        });
      }
      rows.value = list;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};
// เลือกรายชื่อจากหน่วยงาน
const saveData = async () => {
  const id = route.params.orderid
    ? route.params.orderid.toString()
    : localStorage.getItem("orderId")
    ? localStorage.getItem("orderId")
    : null;
  if (id !== null) {
    showLoader();
    await http
      .post(config.API.copyOrderPersonsId(id), selectedModal.value)
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await conditionId();
        clickClose();
        // hideLoader();
      });
  }
};

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 clickClose = async () => {
  modal.value = false;
};
// เปิด popup เพิ่มข้อมูล
const clickAdd = async () => {
  await nodeTree();
  selected.value = "";
  rowsModal.value = [];
  selectedModal.value = [];
  modal.value = true;
  if (myForm.value !== null) {
    myForm.value.reset();
  }
};
// ยืนยันการลบข้อมูล
const clickDelete = (id: string) => {
  dialogRemove($q, () => deleteData(id));
};
// โหลดโครงสร้าง tree
const nodeTree = async () => {
  showLoader();
  await http
    .get(config.API.profileOrganizRoot)
    .then((res) => {
      const data = res.data.result;
      nodesTree.value = data;
      if (data.length > 0) {
        expanded.value = [data[0].id];
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
// เลือกหน่วยงาน
const onSelected = async (id: string) => {
  await listModal(id);
};
// ลบข้อมูลรายชื่อ
const deleteData = async (id: string) => {
  await http
    .delete(config.API.copyOrderId(id))
    .then((res) => {
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      //   hideLoader();
      await conditionId();
    });
};
// บันทึกข้อมูล step 3
const saveDataCopyOrder = async () => {
  if (myForm.value !== null) {
    myForm.value.validate().then(async (result: boolean) => {
      if (result) {
        await fetchSaveCopyOrder();
      }
    });
  }
};
// บันทึกข้อมูล step 3 API
const fetchSaveCopyOrder = async () => {
  let list: RequestCopyOrder[] = [];
  rows.value.map((r: DataCopyOrder) => {
    list.push({
      personalId: r.personalId,
      emailChannel: r.mutiselect.includes(1),
      inboxChannel: r.mutiselect.includes(2),
    });
  });

  showLoader();
  await http
    .put(config.API.copyOrder, list)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      next();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const updateData = (row: DataCopyOrder) => {
  editRows.value.push(row);
};

//เรียกรายละเอียดของคำสั่ง
const fetchOrder = async (id: string) => {
  await http
    .get(config.API.detailOrder(id))
    .then((res) => {
      let data = res.data.result;
      DataStore.typeOrder = data.orderTypeCode.toUpperCase();
    })
    .catch((err) => {
      messageError($q, err);
    });
};
</script>

<template>
  <q-card>
    <q-card-section>
      <div class="col-12 row q-py-sm items-center">
        <q-btn flat round color="primary" @click="clickAdd" 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>
      <q-form ref="myForm">
        <d-table
          :rows="rows"
          :columns="columns"
          :visible-columns="visibleColumns"
          :filter="filter"
          row-key="idCard"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <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" class="cursor-pointer">
              <q-td auto-width>
                <q-btn
                  dense
                  size="12px"
                  flat
                  round
                  color="red"
                  @click="clickDelete(props.row.personalId)"
                  icon="mdi-delete"
                >
                  <q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </q-td>

              <q-td key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="idCard" :props="props">
                {{ props.row.idCard }}
              </q-td>
              <q-td key="name" :props="props">
                {{ props.row.name }}
              </q-td>
              <q-td key="position" :props="props">
                {{ props.row.position }}
              </q-td>
              <q-td key="unit" :props="props">
                {{ props.row.unit }}
              </q-td>
              <q-td key="send" :props="props">
                <q-select
                  :class="getClass(true)"
                  hide-bottom-space
                  multiple
                  :outlined="true"
                  dense
                  v-model="props.row.mutiselect"
                  :rules="[
                    (val) => !!val || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`,
                    (val) =>
                      val.length > 0 || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`,
                  ]"
                  :label="`${'เลือกช่องทางการส่งสำเนา'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="optionSelect"
                  option-value="id"
                  input-debounce="0"
                  color="primary"
                  @update:model-value="() => updateData(props.row)"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-black">
                        ไม่พบข้อมูลที่ค้นหา
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-form>
    </q-card-section>

    <q-separator />
    <q-card-actions align="right">
      <q-btn
        outline
        color="primary"
        icon="chevron_left"
        @click="previous"
        class="q-pr-md"
        label="เลือกรายชื่อ"
      >
      </q-btn>
      <q-btn
        label="บันทึก"
        color="public"
        @click="saveDataCopyOrder"
        class="q-px-md"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
    </q-card-actions>
  </q-card>

  <DialogOrgSelectOneStep
    v-model:modal="modal"
    :title="'เลือกรายชื่อตามหน่วยงาน'"
    v-model:selectedModal="selectedModal"
    :saveData="saveData"
  />
</template>
