text: import { useState } from "react";
  import axios from "axios";
  import Swal from "sweetalert2";
  import LogHelper from "../../../../log/LogHelper";
  import { useSelector } from "react-redux";
  import { useModal } from "../../../../hooks/customHooks";
  import moment from "moment";
  
  const PengembalianBarangHelper = () => {
    const { writeActivityLog } = LogHelper();
    const currentUser = useSelector((state) => state.currentUser);
    const baseUrl = process.env.REACT_APP_LARAVEL_URL;
    const fields = [
      {
        key: "no_pengembalian",
        label: "No",
        _style: { textAlign: "center", width: "10%" },
      },
      {
        key: "no_service",
        label: "No Service",
        _style: { textAlign: "center" },
      },
      {
        key: "nama_pelanggan",
        label: "Nama Pelanggan",
        _style: { textAlign: "center" },
      },
      {
        key: "bj",
        label: "Barang/Jasa",
        _style: { textAlign: "center" },
      },
      {
        key: "merek_tipe",
        label: "Merek Tipe",
        _style: { textAlign: "center" },
      },
      {
        key: "biaya_service",
        label: "Total Biaya",
        _style: { textAlign: "center" },
      },
      {
        key: "jumlah_bayar",
        label: "Jumlah Bayar",
        _style: { textAlign: "center" },
      },
      {
        key: "hutang_piutang",
        label: "Piutang/Hutang",
        _style: { textAlign: "center" },
      },
      {
        key: "status_pembayaran",
        label: "Status Pembayaran",
        _style: { textAlign: "center" },
      },
      {
        key: "show_details",
        label: "",
        _style: { width: "1%" },
        sorter: false,
        filter: false,
      },
    ];
  
    const statusPembayaran = (item) => {
      switch (item.toString()) {
        case "0":
          return "Belum Lunas";
        case "1":
          return "Lunas";
        default:
          return "";
      }
    };
  
    const statusPengerjaan = (item) => {
      switch (item.toString()) {
        case "0":
          return "Belum Dikerjakan";
        case "1":
          return "Cancel";
        case "2":
          return "Sedang Dikerjakan";
        case "3":
          return "Selesai";
        default:
          return "";
      }
    };
  
    const stiker = (item) => {
      switch (item.toString()) {
        case "0":
          return "Belum Ditempel";
        case "1":
          return "Sudah Ditempel";
        default:
          return "Belum Ditempel";
      }
    };
  
    const hitungTotalBiaya = (biaya_service, total_pembayaran, diskon) => {
      let total;
  
      if (diskon) {
        diskon = diskon.replace(/[^0-9]+/g, "");
  
        if (diskon.includes("Rp")) {
          diskon = parseInt(biaya_service) - parseInt(diskon);
        } else if (diskon.includes("%")) {
          diskon = (parseInt(biaya_service) * parseInt(diskon)) / 100;
        }
      }
  
      // tidak ada pembayaran tapi ada diskon
      if (!total_pembayaran && diskon) {
        diskon = diskon.replace(/[^0-9]+/g, "");
        total = parseInt(biaya_service) - parseInt(diskon);
      }
  
      // ada pembayaran dan ada diskon
      if (total_pembayaran && diskon) {
        diskon = diskon.replace(/[^0-9]+/g, "");
        total =
          parseInt(biaya_service) - parseInt(total_pembayaran) - parseInt(diskon);
      }
  
      // tidak ada pembayaran dan tidak ada diskon
      if (!total_pembayaran && !diskon) {
        total = parseInt(biaya_service);
      }
  
      // ada pembayaran tapi tidak ada diskon
      if (total_pembayaran && !diskon) {
        total = parseInt(biaya_service) - parseInt(total_pembayaran);
      }
  
      return total;
    };
  
    const [successToggle, success] = useModal();
    const [infoToggle, info] = useModal();
    const [openModalKembalikanBarangToggle, openModalKembalikanBarang] =
      useModal();
    const [openCancelModalToggle, openCancelModal] = useModal();
    const [openBayarModalToggle, openBayarModal] = useModal();
    const [openModalTambahPengembalianToggle, openModalTambahPengembalian] =
      useModal();
    const [dataPengembalian, setDataPengembalian] = useState([]);
    const [dataPengembalianCadangan, setDataPengembalianCadangan] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [currentPengembalian, setCurrentPengembalian] = useState({});
    const [loadDataPengembalian, setLoadDataPengembalian] = useState(true);
    const [dataRekening, setDataRekening] = useState({});
    const [rekeningVisibility, setRekeningVisibility] = useState("d-none");
    const [nominalVisibility, setNominalVisibility] = useState("d-none");
    const [sandiTransaksi, setSandiTransaksi] = useState({});
    const [dataCabang, setDataCabang] = useState([]);
    const [dataCabangCetakList, setDataCabangCetakList] = useState([]);
    const [loadDataCabang, setLoadDataCabang] = useState(true);
    const [adminOptions, setAdminOptions] = useState([]);
    const [listNoService, setListNoService] = useState([]);
    const [loadVideo, setLoadVideo] = useState(false);
    const [currentAdmin, setCurrentAdmin] = useState({
      name: "",
    });
    const [input, setInput] = useState({
      biaya_service: "",
      norekening: "",
      kas: "",
      keterangan: "",
      id_sandi: "",
      cek_stiker: "",
      id_admin: "",
      diskon: "",
      no_service: "",
    });
    const [filter, setFilter] = useState({
      shift: "",
      status_pembayaran: "",
      cabang: "",
      dari: "",
      sampai: "",
      cari: "",
    });
    const [details, setDetails] = useState([]);
  
    const toggleDetails = (index) => {
      const position = details.indexOf(index);
      let newDetails = details.slice();
      if (position !== -1) {
        newDetails.splice(position, 1);
      } else {
        newDetails = [...details, index];
      }
      setDetails(newDetails);
    };
  
    const changeHandler = (event) => {
      setInput({
        ...input,
        [event.target.name]: event.target.value,
      });
  
      if (event.target.name === "kas" && event.target.value === "1") {
        setRekeningVisibility("d-block");
      } else if (event.target.name === "kas" && event.target.value === "0") {
        setRekeningVisibility("d-none");
      }
  
      if (event.target.name === "value" && event.target.value === "1") {
        setInput({
          ...input,
          diskon: "1",
        });
      } else if (event.target.name === "value" && event.target.value === "0") {
        setInput({
          ...input,
          diskon: "0",
        });
      }
    };
  
    const submitHandler = (action) => {
      if (action === "Tambah") {
        kembalikan();
      } else if (action === "Kembalikan" || action === "Cancel") {
        updateDataPengembalian(currentPengembalian.no_pengembalian, action);
      } else if (action === "Bayar") {
        bayarSisaKekuranganPembayaran(currentPengembalian.no_pengembalian);
      }
    };
  
    const closeModalHandler = (action) => {
      if (action === "Tambah") {
        openModalTambahPengembalianToggle();
      } else if (action === "Cancel") {
        openCancelModalToggle();
      } else if (action === "Kembalikan") {
        openModalKembalikanBarangToggle();
      } else if (action === "View") {
        infoToggle();
      } else if (action === "Bayar") {
        openBayarModalToggle();
      }
  
      setInput({
        no_service: "",
        biaya_service: "",
        norekening: "",
        kas: "",
        keterangan: "",
        id_sandi: "",
        cek_stiker: "",
        id_admin: "",
        diskon: "",
      });
  
      setCurrentAdmin({
        name: "",
      });
      setCurrentPengembalian({});
    };
  
    const getPengerjaanSelesai = async () => {
      await axios
        .get(`${baseUrl}/pengerjaan/status-pengerjaan/selesai`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data.filter((item) => {
            if (currentUser.jabatan === "sales") {
              const serahTerima = item.serah_terima.find((o) => {
                return o.halaman === "penerimaan" && parseInt(o.status) > 0;
              });
  
              return (
                !item.pengembalian &&
                item.penerimaan.jenis_penerimaan === "Persiapan Barang & QC" &&
                serahTerima
              );
            } else {
              return (
                !item.pengembalian &&
                item.penerimaan.jenis_penerimaan !== "Jasa Lain-lain"
              );
            }
          });
          setListNoService(result);
        })
        .catch((error) => {
          console.log(error);
        });
    };
  
    const getDataPengembalian = async () => {
      await axios
        .get(`${baseUrl}/pengembalian`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data;
          setDataPengembalian(result);
          setDataPengembalianCadangan(result);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setIsLoading(false);
    };
  
    const getDetailPengerjaan = async (no_service) => {
      await axios
        .get(`${baseUrl}/pengerjaan/no-service/${no_service}`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          setCurrentPengembalian(response.data.data);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setLoadDataPengembalian(false);
    };
  
    const getDataPengembalianById = async (no_pengembalian, actionModal) => {
      await axios
        .get(`${baseUrl}/pengembalian/${no_pengembalian}`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          if (actionModal !== "delete") {
            setCurrentPengembalian(response.data.data);
            setLoadDataPengembalian(false);
          }
        })
        .catch((error) => {
          console.log(error);
        });
  
      if (actionModal === "view") {
        infoToggle();
      } else if (actionModal === "kembalikan") {
        openModalKembalikanBarangToggle();
      } else if (actionModal === "cancel") {
        openCancelModalToggle();
      } else if (actionModal === "bayar") {
        openBayarModalToggle();
      } else if (actionModal === "delete") {
        Swal.fire({
          title: "Are you sure?",
          text: "You won't be able to revert this!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Yes, delete it!",
        }).then((result) => {
          if (result.isConfirmed) {
            deleteDataPengembalian(no_pengembalian);
          }
        });
      }
    };
  
    const uploadVideo = async (video) => {
      setLoadVideo(true);
      let formData = new FormData();
      formData.append("file", video[0]);
  
      await axios({
        method: "post",
        url: `${baseUrl}/pengembalian/upload-video/${input.no_service}`,
        data: formData,
        headers: {
          Accept: "Application/json",
          ContentType: "multipart/form-data",
          Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
        },
      })
        .then(() => {
          Swal.fire("Berhasil", "Video berhasil diupload", "success");
  
          getDataPengembalian();
          writeActivityLog(
            currentUser.id,
            currentUser.jabatan,
            "Pengembalian",
            "UPDATE",
            `Upload video untuk data ${input.no_service}`
          );
          closeModalHandler("Tambah");
        })
        .catch((error) => {
          Swal.fire("Gagal", "Video gagal diupload", "error");
        });
  
      setLoadVideo(false);
    };
  
    const kembalikan = async () => {
      let message = "";
      if (!input.no_service) message = "Nomor service harus diisi!";
      else if (!input.biaya_service) message = "Biaya service harus diisi!";
      else if (!input.kas) message = "Kas harus dipilih salah satu!";
      else if (input.kas == "1" && !input.norekening)
        message = "Nomor rekening harus dipilih salah satu!";
      else if (!input.cek_stiker)
        message = "Cek stiker harus dipilih salah satu!";
      else if (!input.id_sandi)
        message = "Sandi transaksi harus dipilih salah satu!";
  
      if (message) {
        Swal.fire("Gagal", message, "error");
      } else {
        await axios
          .post(
            `${baseUrl}/pengembalian`,
            {
              no_service: input.no_service,
              id_admin: currentUser.id,
              cek_stiker: input.cek_stiker || currentPengembalian.cek_stiker,
              status_pengembalian: 1,
              total: input.biaya_service.replace(/[^0-9]+/g, "") || 0,
              diskon: input.diskon || 0,
              id_rekening: input.norekening || 0,
              id_sandi: input.id_sandi,
              keterangan: input.keterangan,
            },
            {
              headers: {
                Accept: "Application/json",
                Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
              },
            }
          )
          .then((response) => {
            Swal.fire("Berhasil", "Data berhasil ditambahkan", "success");
            getDataPengembalian();
  
            writeActivityLog(
              currentUser.id,
              currentUser.jabatan,
              "Pengembalian Barang",
              "UPDATE",
              `Membuat data baru, nomor pengembalian ${response.data.data.no_pengembalian}`
            );
          })
          .catch((error) => {
            Swal.fire("Gagal", error.response.data.message, "error");
          });
  
        closeModalHandler("Tambah");
      }
    };
  
    const updateDataPengembalian = async (no_pengembalian, actionHandler) => {
      let message = "";
      if (!input.biaya_service) message = "Biaya service harus diisi!";
      else if (!input.kas) message = "Kas harus dipilih salah satu!";
      else if (input.kas == "1" && !input.norekening)
        message = "Nomor rekening harus dipilih salah satu!";
      else if (!input.cek_stiker)
        message = "Cek stiker harus dipilih salah satu!";
      else if (!input.id_sandi)
        message = "Sandi transaksi harus dipilih salah satu!";
      else if (!input.id_admin) message = "Admin harus diisi!";
  
      if (message) {
        Swal.fire("Gagal", message, "error");
      } else {
        await axios
          .put(
            `${baseUrl}/pengembalian/${no_pengembalian}`,
            {
              cek_stiker: input.cek_stiker,
              diskon: input.diskon || 0,
              status_pengembalian: 1,
              id_admin: currentUser.id,
              total: input.biaya_service.replace(/[^0-9]+/g, "") || 0,
              status_pengerjaan: currentPengembalian.pengerjaan.status_pengerjaan,
              id_rekening: input.norekening || 0,
              id_sandi: input.id_sandi,
              keterangan: input.keterangan,
            },
            {
              headers: {
                Accept: "Application/json",
                Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
              },
            }
          )
          .then((response) => {
            Swal.fire("Berhasil", "Data berhasil diupdate", "success");
            getDataPengembalian();
  
            writeActivityLog(
              currentUser.id,
              currentUser.jabatan,
              "Pengembalian Barang",
              "UPDATE",
              `Mengubah data nomor pengembalian ${currentPengembalian.no_pengembalian}`
            );
          })
          .catch((error) => {
            Swal.fire("Gagal", error.response.data.message, "error");
          });
  
        closeModalHandler(actionHandler);
      }
    };
  
    const getDataRekening = async () => {
      await axios
        .get(`${baseUrl}/rekening`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          setDataRekening(response.data.data);
        })
        .catch((error) => {
          console.log(error);
        });
    };
  
    const getSandiTransaksi = async () => {
      await axios
        .get(`${baseUrl}/sandi-transaksi/jenis/1`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          setSandiTransaksi(response.data.data);
        })
        .catch((error) => {
          console.log(error);
        });
    };
  
    const getDataAdmin = async () => {
      await axios
        .get(`${baseUrl}/user/role/admin service`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          let data = [];
          response.data.data.map((item) => data.push(item));
          setAdminOptions(data);
        })
        .catch((error) => {
          console.log(error);
        });
    };
  
    const getDataCabang = async () => {
      await axios
        .get(`${baseUrl}/cabang`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data;
          setDataCabang(result);
  
          const data = result.filter((cabang) => {
            return cabang.nama_cabang.toLowerCase().match("twincom");
          });
          setDataCabangCetakList(data);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setLoadDataCabang(false);
    };
  
    const bayarSisaKekuranganPembayaran = async (no_pengembalian) => {
      let inputBiaya;
      if (input.biaya_service != currentPengembalian.pengerjaan.biaya_service) {
        if (
          input.biaya_service.indexOf(",") !== -1 ||
          input.biaya_service.indexOf(".") !== -1
        ) {
          inputBiaya = input.biaya_service.replace(/[^0-9]+/g, "");
        } else {
          inputBiaya = input.biaya_service;
        }
      } else {
        inputBiaya = input.biaya_service;
      }
  
      let total = parseInt(currentPengembalian.nominal) + parseInt(inputBiaya);
      let status_pembayaran = 0;
      if (total <= parseInt(currentPengembalian.pengerjaan.biaya_service)) {
        status_pembayaran = 1;
      }
  
      await axios
        .put(
          `${baseUrl}/pengembalian/${no_pengembalian}`,
          {
            nominal: total,
            status_pembayaran: status_pembayaran,
          },
          {
            headers: {
              Accept: "Application/json",
              Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
            },
          }
        )
        .then((response) => {
          updateLunasDataAruskas();
          writeActivityLog(
            currentUser.id,
            currentUser.jabatan,
            "Pengembalian Barang",
            "UPDATE",
            `Mengubah data nomor pengembalian ${currentPengembalian.no_pengembalian}`
          );
        })
        .catch((error) => {
          Swal.fire("Gagal", error.response.data.message, "error");
        });
    };
  
    const updateLunasDataAruskas = async () => {
      let inputBiaya;
      if (input.biaya_service != currentPengembalian.pengerjaan.biaya_service) {
        if (
          input.biaya_service.indexOf(",") !== -1 ||
          input.biaya_service.indexOf(".") !== -1
        ) {
          inputBiaya = input.biaya_service.replace(/[^0-9]+/g, "");
        } else {
          inputBiaya = input.biaya_service;
        }
      } else {
        inputBiaya = input.biaya_service;
      }
  
      const nominal = parseInt(inputBiaya);
      const dataSandi = sandiTransaksi.filter(
        (item) => item.sandi_transaksi.toLowerCase() == "penerimaan biaya service"
      );
  
      await axios
        .post(
          `${baseUrl}/arus-kas`,
          {
            no_pengembalian: currentPengembalian.no_pengembalian,
            no_service: currentPengembalian.no_service,
            kas: input.kas,
            norekening: input.kas == 1 ? input.norekening : "-",
            nominal: nominal,
            id_admin: input.id_admin,
            keterangan: `${currentPengembalian.penerimaan.merek} ${currentPengembalian.penerimaan.tipe}`,
            id_sandi: dataSandi[0].id,
          },
          {
            headers: {
              Accept: "Application/json",
              Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
            },
          }
        )
        .then((response) => {
          Swal.fire("Berhasil", "Data berhasil diupdate", "success");
          getDataPengembalian();
        })
        .catch((error) => {
          Swal.fire("Gagal", error.response.data.message, "error");
        });
  
      closeModalHandler("Bayar");
    };
  
    const deleteDataPengembalian = async (no_pengembalian) => {
      await axios
        .delete(`${baseUrl}/pengembalian/${no_pengembalian}`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then(() => {
          Swal.fire("Berhasil", "Data berhasil dihapus", "success");
          getDataPengembalian();
          writeActivityLog(
            currentUser.id,
            currentUser.jabatan,
            "Pengembalian Barang",
            "UPDATE",
            `Menghapus data nomor pengembalian ${currentPengembalian.no_pengembalian}`
          );
        })
        .catch((error) => {
          Swal.fire("Gagal", error.response.data.message, "error");
        });
    };
  
    const filterData = (shift, status_pembayaran, cabang, dari, sampai, cari) => {
      let val = dataPengembalianCadangan;
      if (shift) {
        val = val.filter((item) => {
          return item.shift.toString() === shift;
        });
      }
  
      if (status_pembayaran) {
        val = val.filter((item) => {
          if (status_pembayaran) {
            return (
              item.pembayaran &&
              item.pembayaran.status_pembayaran.toString() === status_pembayaran
            );
          } else {
            return !item.pembayaran || item.pembayaran.status_pembayaran;
          }
        });
      }
  
      if (cabang) {
        val = val.filter((item) => {
          return item.admin.cabang.nama_cabang
            .toLowerCase()
            .match(cabang.toLowerCase());
        });
      }
  
      if (dari && !sampai) {
        val = val.filter((item) => {
          const d = new Date(dari);
          const s = new Date();
          const data = new Date(item.created_at);
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
      } else if (dari && sampai) {
        val = val.filter((item) => {
          const d = new Date(dari);
          const s = new Date(`${sampai} 23:59:59`);
          const data = new Date(
            new Date(item.created_at).setHours(
              new Date(item.created_at).getHours() -
                Math.abs(new Date().getTimezoneOffset() / 60)
            )
          );
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
      }
  
      if (cari) {
        val = val.filter((item) => {
          const merek = item.penerimaan.tipe
            ? `${item.penerimaan.tipe.merek.merek.toLowerCase()} ${item.penerimaan.tipe.tipe.toLowerCase()}`
            : "";
          return (
            item.penerimaan.customer.name
              .toLowerCase()
              .match(cari.toLowerCase()) ||
            merek.match(cari.toLowerCase()) ||
            (item.penerimaan.sn &&
              item.penerimaan.sn.toLowerCase().match(cari.toLowerCase())) ||
            item.no_service.toLowerCase().match(cari.toLowerCase()) ||
            item.no_pengembalian.toString().match(cari.toLowerCase())
          );
        });
      }
  
      setDataPengembalian(val);
    };
  
    return {
      currentUser,
      fields,
      statusPembayaran,
      statusPengerjaan,
      stiker,
      success,
      successToggle,
      info,
      openModalTambahPengembalian,
      openModalTambahPengembalianToggle,
      openModalKembalikanBarang,
      openCancelModal,
      openBayarModal,
      dataPengembalian,
      setDataPengembalian,
      isLoading,
      setIsLoading,
      currentPengembalian,
      setCurrentPengembalian,
      loadDataPengembalian,
      dataRekening,
      setDataRekening,
      rekeningVisibility,
      input,
      setInput,
      filter,
      setFilter,
      details,
      nominalVisibility,
      sandiTransaksi,
      setSandiTransaksi,
      dataCabang,
      setDataCabang,
      loadDataCabang,
      setLoadDataCabang,
      dataCabangCetakList,
      setDataCabangCetakList,
      adminOptions,
      setAdminOptions,
      listNoService,
      setListNoService,
      loadVideo,
      currentAdmin,
      setCurrentAdmin,
      toggleDetails,
      changeHandler,
      submitHandler,
      closeModalHandler,
      getDataPengembalian,
      getDataPengembalianById,
      getDataRekening,
      getSandiTransaksi,
      getDataCabang,
      getDataAdmin,
      filterData,
      getPengerjaanSelesai,
      getDetailPengerjaan,
      uploadVideo,
    };
  };
  
  export default PengembalianBarangHelper;
  