<script setup>
import Table from "@/components/customUI/Table.vue";
import CheckWeigherSettingAddModal from "./CheckWeigherSettingAddModal.vue";
import { postChangeGroupValue, getCheckWeigher } from "@/apis/productSetting";
import { ref, onMounted, inject } from "vue";
import dayjs from "dayjs";

const { openToast } = inject("app_toast");

const columns = [
  {
    title: "組別",
    key: "groupNum",
  },
  {
    title: "成品代號",
    key: "itemName",
  },
  {
    title: "品名",
    key: "name",
  },
  {
    title: "上限",
    key: "upperLimit",
  },
  {
    title: "下限",
    key: "lowerLimit",
  },
  {
    title: "操作",
    key: "operation",
  },
];

const dataSource = ref([]);
const updateTime = ref("");
const currentEditIndex = ref(-1);

const getDataSource = async () => {
  loading.value = true;
  const res = await getCheckWeigher();
  dataSource.value = res.data;
  updateTime.value = res?.data[0]?.callingTime
    ? dayjs(res.data[0].callingTime).format("YYYY-MM-DD HH:mm:ss")
    : dayjs().format("YYYY-MM-DD HH:mm:ss");
  loading.value = false;
};

const pushDataSource = async (data) => {
  loading.value = true;
  // 檢查是新增還是修改
  if (currentEditIndex.value >= 0) {
    // 修改
    dataSource.value[currentEditIndex.value] = data;
    openToast("success", "修改成功，請記得儲存");
  } else {
    //篩選如果 groupNum 重複則不新增
    const existingIndex = dataSource.value.findIndex(
      (item) => item.groupNum === data.groupNum
    );
    if (existingIndex !== -1) {
      openToast("error", "組別已存在，請修改組別後再新增");
    } else {
      // 新增
      dataSource.value.push(data);
      openToast("success", "新增成功，請記得儲存");
    }
  }
  currentEditIndex.value = -1; // 重置編輯索引
  loading.value = false;
};

const postChangeGroup = async () => {
  const res = await postChangeGroupValue(dataSource.value);
  if (res.isSuccess) {
    openToast("success", "儲存成功");
  } else {
    openToast("error", res.msg);
  }
};

const removeAll = () => {
  dataSource.value = [];
  openToast("success", "已清空列表，請記得儲存");
};

// 修改 onMounted
onMounted(() => {
  getDataSource();
});

const formState = ref({
  groupNum: "",
  itemName: "",
  name: "",
  upperLimit: "",
  lowerLimit: "",
});

const openModal = (record, index = -1) => {
  currentEditIndex.value = index;
  if (record) {
    formState.value = { ...record };
  } else {
    resetModalForm();
  }
  weight_check_machine_modal.showModal();
};

const resetModalForm = () => {
  formState.value = {
    groupNum: "",
    itemName: "",
    name: "",
    upperLimit: "",
    lowerLimit: "",
  };
};

const loading = ref(false);

// 新增刪除功能時也要更新 sessionStorage
const removeAccount = async (groupNum) => {
  // 找到要刪除的項目索引
  const index = dataSource.value.findIndex(
    (item) => item.groupNum === groupNum
  );

  if (index > -1) {
    dataSource.value.splice(index, 1);

    openToast("success", "刪除成功，請記得儲存");
  }
};
</script>

<template>
  <div class="flex justify-start items-center mb-3">
    <h3 class="text-xl mr-5">檢重機設備列表</h3>
    <CheckWeigherSettingAddModal
      @pushData="pushDataSource"
      :formState="formState"
      :currentEditIndex="currentEditIndex"
    />
    <button
      class="btn btn-sm btn-success mr-3"
      @click.stop.prevent="openModal(null)"
    >
      <font-awesome-icon :icon="['fas', 'plus']" />新增
    </button>
    <button
      class="btn btn-sm btn-error text-white mr-3"
      @click.stop.prevent="removeAll()"
    >
      <font-awesome-icon :icon="['fas', 'trash-alt']" />全部刪除
    </button>
    <button
      class="btn btn-sm btn-info mr-3"
      @click.stop.prevent="postChangeGroup"
    >
      <font-awesome-icon :icon="['fas', 'save']" />儲存
    </button>
  </div>
  <Table :columns="columns" :dataSource="dataSource" :loading="loading">
    <template #beforeTable>
      <p class="text-info text-xl pb-5">更新時間 : {{ updateTime }}</p>
    </template>
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => openModal(record, index)"
        >
          修改
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => removeAccount(record.groupNum)"
        >
          刪除
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

<style lang="css" scoped></style>
