// 1 => LOADING
// 2 => DONE
// 3 => ERROR

import * as api from "../api/cashier.js";

export default {
  namespaced: true,
  state: {
    dialog_cashier: false,
    status_options: [ 
      { val: 0, text: 'All' }, { val: 1, text: 'Draft' },
      { val: 2, text: 'Paid' }, { val: 3, text: 'Realitation' }
    ],
    selected_status: { val: 1, text: 'Draft' },
    menuStartDate: false,
    menuEndDate: false,

    dStartDate: new Date().toISOString().substring(0, 10),
    dEndDate: new Date().toISOString().substring(0, 10),
    xStartDate: moment(new Date()).format('YYYY-MM-DD'),
    xEndDate: moment(new Date()).format('YYYY-MM-DD'),

    // listing
    currentPage: 1,
    search_status: 0,
    search_error_message: "",
    cashierList: [],
    selected_cashier: {},
    total_page_cashier: 0,
    xsearch: "",
    act: "new",
    imagePreviews: [],
    imagePrevPaid: [],

    // form
    load_status_branch: 0,
    error_message: "",
    alert_error: false,
    branchList: [],
    selected_branch: {},
    search_branch: "",
    accountDanaList: [],
    selected_accountDana: {},
    search_accountDana: "",
    load_status_accDana: 0,
    accountBiayaList: [],
    selected_accountBiaya: {},
    search_accountBiaya: "",
    load_status_accBiaya: 0,
    accountTempList: [],
    selected_accountTemp: {},
    search_accountTemp: "",
    load_status_accTemp: 0,
    load_status: 0,
    purchaseList: [],
    selected_purchase: [],
    resume_total: {"totalRealitation": 0},
    errors: [],
    alert_error: false,
    alert_success: false,
    success_message: "",
    totalDraft: 0,

    // detail
    search_status_detail: 0,
    details: [],
    show_progrees_upload: false,
    note: "",
    notepay: "",
    dialog_cashier_pay: false,
    totalPaid: 0,
    restPrice: 0,
    openprint: false,
    numberRequest: [],
    total_akhir: 0,
    requestDescription: "",
    status: '',
    xdate: '',
    imagePayPreviews: [],
    imagePayFiles: [],
    user: one_user(),
    userReceive: [],
    selected_userReceive:'',
    imageRelationPreviews: [],
    imageRelationFiles: [],

    // voucher detail
    dialog_view_img: false,
    listing_item_realise: [],
    selected_img_view: ''
  },
  mutations: {
    update_dialog_cashier(state, val) {
      state.dialog_cashier = val;
    },
    update_status_options(state, val) {
      state.status_options = val;
    },
    update_selected_status(state, val) {
      state.selected_status = val;
    },
    update_menuStartDate(state, val) {
      state.menuStartDate = val;
    },
    update_menuEndDate(state, val) {
      state.menuEndDate = val;
    },
    update_dStartDate(state, val) {
      state.dStartDate = val;
    },
    update_dEndDate(state, val) {
      state.dEndDate = val;
    },
    update_xStartDate(state, val) {
      state.xStartDate = val;
    },
    update_xEndDate(state, val) {
      state.xEndDate = val;
    },
    update_currentPage(state, val) {
      state.currentPage = val;
    },
    update_search_status(state, val) {
      state.search_status = val;
    },
    update_search_error_message(state, val) {
      state.search_error_message = val;
    },
    update_cashierList(state, val) {
      state.cashierList = val;
    },
    update_selected_cashier(state, val) {
      state.selected_cashier = val;
    },
    update_total_page_cashier(state, val) {
      state.total_page_cashier = val;
    },
    update_xsearch(state, val) {
      state.xsearch = val;
      state.currentPage = 1;
    },
    update_act(state, val) {
      state.act = val
    },
    update_load_status_branch(state, val) {
      state.load_status_branch = val;
    },
    update_error_message(state, val) {
      state.error_message = val;
    },
    update_alert_error(state, val) {
      state.alert_error = val;
    },
    update_branchList(state, val) {
      state.branchList = val;
    },
    update_selected_branch(state, val) {
      state.selected_branch = val;
    },
    update_search_branch(state, val) {
      state.search_branch = val;
    },
    update_accountDanaList(state, val) {
      state.accountDanaList = val;
    },
    update_selected_accountDana(state, val) {
      state.selected_accountDana = val;
    },
    update_search_accountDana(state, val) {
      state.search_accountDana = val;
    },
    update_load_status_accDana(state, val) {
      state.load_status_accDana = val;
    },
    update_accountBiayaList(state, val) {
      state.accountBiayaList = val;
    },
    update_selected_accountBiaya(state, val) {
      state.selected_accountBiaya = val;
    },
    update_search_accountBiaya(state, val) {
      state.search_accountBiaya = val;
    },
    update_load_status_accBiaya(state, val) {
      state.load_status_accBiaya = val;
    },
    update_accountTempList(state, val) {
      state.accountTempList = val;
    },
    update_selected_accountTemp(state, val) {
      state.selected_accountTemp = val;
    },
    update_search_accountTemp(state, val) {
      state.search_accountTemp = val;
    },
    update_load_status_accTemp(state, val) {
      state.load_status_accTemp = val;
    },
    update_load_status(state, val) {
      state.load_status = val;
    },
    update_purchaseList(state, val) {
      state.purchaseList = val;
    },
    update_selected_purchase(state, val) {
      state.selected_purchase = val;
    },
    update_resume_total(state, val) {
      state.resume_total = val;
    },
    update_errors(state, val) {
      state.errors = val;
    },
    update_alert_error(state, val) {
      state.alert_error = val;
    },
    update_alert_success(state, val) {
      state.alert_success = val;
    },
    update_success_message(state, val) {
      state.success_message = val;
    },
    update_totalDraft(state, val) {
      state.totalDraft = val
    },
    update_search_status_detail(state, val) { 
      state.search_status_detail = val; 
    },
    update_details(state, val) {
      state.details = val
    },
    update_show_progrees_upload(state, val) {
        state.show_progrees_upload = val
    },
    update_note(state, val) {
        state.note = val
    },
    update_notepay(state, val) {
        state.notepay = val
    },
    update_dialog_cashier_pay(state, val) {
        state.dialog_cashier_pay = val
    },
    update_totalPaid(state, val) {
      state.totalPaid = val
    },
    update_restPrice(state, val) {
      state.restPrice = val
    },
    update_openprint(state, val) {
      state.openprint = val
    },
    update_imagePreviews(state, val) {
        state.imagePreviews = val
    },
    update_imagePrevPaid(state, val) {
        state.imagePrevPaid = val
    },
    update_numberRequest(state, val) {
        state.numberRequest = val
    },
    update_total_akhir(state, val) {
        state.total_akhir = val
    },
    update_requestDescription(state, val) {
        state.requestDescription = val
    },
    update_status(state, val) {
        state.status = val
    },
    update_xdate(state, val) {
        state.xdate = val
    },
    update_imagePayPreviews(state, val) {
      state.imagePayPreviews = val;
    },
    update_imagePayFiles(state, val) {
      state.imagePayFiles = val;
    },
    update_user(state, val) {
      state.user = val;
    },
    update_userReceive(state, val) {
      state.userReceive = val;
    },
    update_selected_userReceive(state, val) {
      state.selected_userReceive = val;
    },
    update_imageRelationPreviews(state, val) {
      state.imageRelationPreviews = val;
    },
    update_imageRelationFiles(state, val) {
      state.imageRelationFiles = val;
    },
    update_dialog_view_img(state, val) {
      state.dialog_view_img = val
    },
    update_listing_item_realise(state, val) {
      state.listing_item_realise = val
    },
    update_selected_img_view(state, val) {
      state.selected_img_view = val
    }
  },
  actions: {
    async search(context) {
      context.commit("update_search_status", 1);

      try {
        var url_string = window.location.href
        var url = new URL(url_string);
        var status = url.searchParams.get("status");
        var xstartdate = url.searchParams.get("startdate");

        context.commit("update_status", status);
        context.commit("update_xdate", xstartdate);

        const today = moment(new Date()).format('YYYY-MM-DD');

        var startDate = xstartdate == null || xstartdate == '' ? context.state.xStartDate : xstartdate;
        var endDate = xstartdate == null || xstartdate == '' ? context.state.xEndDate : today;

        var prm = {
          token: one_token(),
          currentPage: context.state.currentPage,
          status: status == null || status == '' ? context.state.selected_status.text : status,
          search: context.state.xsearch,
          startdate: startDate,
          enddate: endDate,
          lastId: -1,
        };

        let resp = await api.search(prm);
        if (resp.status != "OK") {
          context.commit("update_search_status", 3);
          context.commit("update_search_error_message", resp.message);
        } else {
          context.commit("update_search_status", 2);
          context.commit("update_search_error_message", "");
          let data = {
            records: resp.data.records,
            total: resp.data.total,
          };

          context.commit("update_cashierList", data.records);
          context.commit("update_total_page_cashier", data.total);
        }
      } catch (e) {
        context.commit("update_search_status", 3);
        context.commit("update_search_error_message", e.message);
      }
    },

    async searchBranch(context, prm) {
        context.commit("update_load_status_branch", 1)
        try {
            let resp = await api.searchBranch(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status_branch", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status_branch", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_branchList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status_branch", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async searchAccDana(context, prm) {
        context.commit("update_load_status_accDana", 1)
        try {
            let resp = await api.searchAccDana(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status_accDana", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status_accDana", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_accountDanaList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status_accDana", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async searchAccBiaya(context, prm) {
        context.commit("update_load_status_accBiaya", 1)
        try {
            let resp = await api.searchAccBiaya(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status_accBiaya", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status_accBiaya", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_accountBiayaList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status_accBiaya", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async searchAccTemp(context, prm) {
        context.commit("update_load_status_accTemp", 1)
        try {
            let resp = await api.searchAccTemp(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status_accTemp", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status_accTemp", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_accountTempList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status_accTemp", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async getPurchase(context, prm) {
        context.commit("update_load_status", 1)
        try {
            let resp = await api.getPurchase(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_purchaseList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async searchdetail(context, prm) {
        context.commit("update_search_status_detail", 1)
        try {
            let resp = await api.searchdetail(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_search_status_detail", 3)
                context.commit("update_search_error_message", resp.message);
            } else {
                context.commit("update_search_status_detail", 2)
                context.commit("update_search_error_message", "");
                let data = {
                    records: resp.data.records
                }

                let total = 0;
                data.records.forEach(element => {
                  total = total + Number(element.realised_price)
                });

                context.commit("update_details", data.records)
                context.commit("update_restPrice", total)
            }
        } catch (e) {
            context.commit("update_search_status_detail", 3)
            context.commit("update_search_error_message", e.message);
        }
    },

    async save(context, prm) {
        context.commit("update_search_status_detail", 1)
        try {

            let resp = await api.saveDetail(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_search_status_detail", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_search_status_detail", 2)
                context.commit("update_error_message", resp.message);

                let data = {
                    records: resp.data.records
                }

                context.commit("update_alert_success", true);
                context.commit("update_dialog_cashier", false);
                var msg = `Sukses menyimpan data baru dengan kode ${data.records[0].PaymentVoucherNumber}`;
                context.commit("update_success_message", msg);
                context.commit("update_selected_cashier", data.records[0]);
                context.dispatch("search");
                context.dispatch("searchdetail", data.records[0].PaymentVoucherID);
            }
        } catch (e) {
            context.commit("update_search_status_detail", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async getTotalDraft(context, prm) {
        context.commit("update_search_status", 1)
        try {
            let resp = await api.getTotalDraft(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_search_status", 3)
                context.commit("update_error_message", resp.message);
            } else {
                context.commit("update_search_status", 2)
                context.commit("update_error_message", "");
                let data = {
                    total: resp.data.total
                }

                context.commit("update_totalDraft", data.total)
            }
        } catch (e) {
            context.commit("update_search_status", 3)
            context.commit("update_error_message", e.message);
        }
    },

    async getTotalPaid(context, prm) {
        context.commit("update_search_status", 1)
        try {
            let resp = await api.getTotalPaid(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_search_status", 3)
                context.commit("update_error_message", resp.message);
            } else {
                context.commit("update_search_status", 2)
                context.commit("update_error_message", "");
                let data = {
                    total: resp.data.total
                }

                context.commit("update_totalPaid", data.total)
            }
        } catch (e) {
            context.commit("update_search_status", 3)
            context.commit("update_error_message", e.message);
        }
    },

    async delete(context, prm) {
        context.commit("update_search_status", 1)
        try {

            let resp = await api.deleteVoucher(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_search_status", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_search_status", 2)
                context.commit("update_error_message", resp.message);

                let data = {
                    records: resp.data.records
                }

                context.commit("update_alert_success", true);
                context.commit("update_dialog_cashier", false);
                var msg = `Sukses menghapus data dengan kode ` + prm.PVNumber;
                context.commit("update_success_message", msg);
                // context.commit("update_selected_cashier", data.records[0]);
                context.dispatch("search");
                context.dispatch("searchdetail", "");
            }
        } catch (e) {
            context.commit("update_search_status", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async update(context, prm) {
        context.commit("update_search_status_detail", 1)
        try {

            let resp = await api.editVoucherV2(prm)
            if (resp.status != "OK") {
                context.commit("update_search_status_detail", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_search_status_detail", 2)
                context.commit("update_error_message", resp.message);

                let data = {
                    records: resp.data.records
                }

                context.commit("update_note", "");
                context.commit("update_restPrice", 0);
                context.commit("update_total_akhir", 0);
                context.commit("update_imageRelationPreviews", []);
                context.commit("update_imageRelationFiles", []);
                context.commit("update_alert_success", true);
                context.commit("update_dialog_cashier", false);
                var msg = `Sukses Realisasi dengan kode ${data.records[0].PaymentVoucherNumber}`;
                context.commit("update_success_message", msg);
                // context.commit("update_selected_cashier", data.records[0]);
                context.dispatch("search");
                // context.dispatch("searchdetail", data.records[0].PaymentVoucherID);
            }
        } catch (e) {
            context.commit("update_search_status_detail", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async updatepaid(context, prm) {
        context.commit("update_search_status_detail", 1)
        try {

            let resp = await api.updatepaid(prm)
            console.log("updatepaid resp", resp)
            if (resp.status != "OK") {
                context.commit("update_search_status_detail", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_search_status_detail", 2)
                context.commit("update_error_message", resp.message);

                let data = {
                    records: resp.data.records
                }

                context.commit("update_notepay", "");
                context.commit("update_imagePayPreviews", []);
                context.commit("update_imagePayFiles", []);
                context.commit("update_selected_userReceive", '');
                context.commit("update_alert_success", true);
                context.commit("update_dialog_cashier_pay", false);
                var msg = `Sukses Pembayaran dengan kode ${data.records[0].PaymentVoucherNumber}`;
                context.commit("update_success_message", msg);
                // context.commit("update_selected_cashier", data.records[0]);
                context.dispatch("search");
                // context.dispatch("searchdetail", data.records[0].PaymentVoucherID);
            }
        } catch (e) {
            context.commit("update_search_status_detail", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async getPurchaseUpdateNew(context, prm) {
        context.commit("update_load_status", 1)
        try {
            let resp = await api.getPurchaseUpdateNew(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("update_load_status", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_purchaseList", data.records)
            }
        } catch (e) {
            context.commit("update_load_status", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async getUserReceive(context) {
        context.commit("update_load_status", 1)
        try {
            let prm = {
              token: one_token(),
              userId: context.state.user.M_UserID,
            }
            let resp = await api.getUserReceive(prm)
            if (resp.status != "OK") {
                context.commit("update_load_status", 3)
                context.commit("update_error_message", resp.message);
                context.commit("update_alert_error", true);
            } else {
                context.commit("update_load_status", 2)
                context.commit("update_error_message", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("update_userReceive", data.records)
            }
        } catch (e) {
            context.commit("update_load_status", 3)
            context.commit("update_error_message", e.message);
            context.commit("update_alert_error", true);
        }
    },

    async getVoucherDetail(context) {
      try {
        let param = {
          token: one_token(),
          ID: context.state.selected_cashier.PaymentVoucherID
        }
        let resp = await api.getVoucherDetail(param)
        if (resp.status != 'OK') {
          context.commit("update_error_message", resp.message);
          context.commit("update_alert_error", true);
        } else {
          let data = resp.data

          context.commit("update_listing_item_realise", data)
  
          let realised = data.reduce((sum, item) => sum + Number(item.estimate_price), 0);
          let detail = context.state.details;
          let adjustment = detail.reduce((sum, item) => sum + Number(item.PurchaseRequestDirectAdjustment), 0)

          let total = Number(context.state.selected_cashier.PaymentVoucherTotal)
          let sisa = (total + adjustment) - realised
          context.commit("update_total_akhir", sisa)
        }
      } catch (error) {
        context.commit("update_error_message", error.message);
        context.commit("update_alert_error", true);
      }
    },

    async saveVoucherDetail(context, param) {
      try {
        param.token = one_token()
        let resp = await api.saveVoucherDetail(param)
        if (resp.status != 'OK') {
          context.commit("update_error_message", resp.message);
          context.commit("update_alert_error", true);
        } else {
          context.commit("update_alert_success", true);
          context.commit("update_success_message", "Success");

          let ID = context.state.selected_cashier.PaymentVoucherID;
          context.dispatch("searchdetail", ID)
          context.commit("update_dialog_realise_item", false);
          context.commit("update_listing_item_realise", [])
        }

      } catch (error) {
        context.commit("update_error_message", error.message);
        context.commit("update_alert_error", true);
      }
    }
  },
};

