package kr.co.compcareworker.Fragment.Plan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.EstimateList.EstimateQuickData;
import kr.co.compcareworker.Data.PlanDetail.Item;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.InvoiceListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.ProductSearchDialog;
import kr.co.compcareworker.Util.CustomView.QuickSetDialog;
import kr.co.compcareworker.Util.CustomView.TransactionDialog;
import kr.co.compcareworker.Util.ItemMoveCallback;
import kr.co.compcareworker.Util.MyModifyClick;

@SuppressLint("ValidFragment")
public class Invoice_Fragment extends Fragment implements MyModifyClick {

    Handler handler, hdr;
    FragmentActivity fa;
    String iv_idx, pd_idx, ivi_idx, pd_code, pd_ttype;

    /**
     * 명세표 데이터
     */
    ArrayItem<Item> invoice_array;
    Item invoice_data;

    /**
     * 명세표 테이블
     */
    RecyclerView invoiceRV;
    InvoiceListRecyclerAdapter invoice_adapter;
    RecyclerView.LayoutManager layoutManager;
    TextView invoice_total_priceTV;
    int total_price = 0;
    LinearLayout invoice_nullLL;

    /**
     * 프로그래스바
     */
    ProgressBar invoicePB;

    /**
     * 품목 추가
     */
    EditText pd_nameET, pd_optionET, pd_cntET, pd_unitET, pd_priceET;
    Button product_searchBtn, invoice_modifyBtn, invoice_addBtn, invoice_delBtn, invoice_cancleBtn;
    TextView pd_supply_priceTV;

    /**
     * 품목 순서저장
     */
    Button invoice_orderBtn;

    /**
     * 하단 버튼
     */
    //Quick세트
    Button quick_setBtn;
    //거래내역
    Button transactionBtn;
    /**
     * 변수
     */
    String modify_supply, modify_vat;

    @SuppressLint("ValidFragment")
    public Invoice_Fragment(Handler handler, String iv_idx) {
        this.handler = handler;
        this.iv_idx = iv_idx;
    }

    public Invoice_Fragment() {
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_invoice, container, false);

        /**명세표 테이블*/
        invoiceRV = v.findViewById(R.id.invoiceRV);
        invoice_nullLL = v.findViewById(R.id.invoice_nullLL);
        invoice_total_priceTV = v.findViewById(R.id.invoice_total_priceTV);

        /**프로그래스바*/
        invoicePB = v.findViewById(R.id.invoicePB);

        /**품목 추가*/
        pd_nameET = v.findViewById(R.id.pd_nameET);
        pd_optionET = v.findViewById(R.id.pd_optionET);
        pd_cntET = v.findViewById(R.id.pd_cntET);
        pd_unitET = v.findViewById(R.id.pd_unitET);
        pd_priceET = v.findViewById(R.id.pd_priceET);
        pd_supply_priceTV = v.findViewById(R.id.pd_supply_priceTV);

        product_searchBtn = v.findViewById(R.id.product_searchBtn);
        invoice_modifyBtn = v.findViewById(R.id.invoice_modifyBtn);
        invoice_addBtn = v.findViewById(R.id.invoice_addBtn);
        invoice_delBtn = v.findViewById(R.id.invoice_delBtn);
        invoice_cancleBtn = v.findViewById(R.id.invoice_cancleBtn);

        /**품목 순서저장*/
        invoice_orderBtn = v.findViewById(R.id.invoice_orderBtn);

        /**하단 버튼*/
        //Quick 세트
        quick_setBtn = v.findViewById(R.id.quick_setBtn);
        //거래내역
        transactionBtn = v.findViewById(R.id.transactionBtn);

        //거래명세표 어댑터 설정
        invoice_adapter = new InvoiceListRecyclerAdapter(getContext(), hdr, this::modifyClick);

        init_Handler();
        init_Listener();
        Get_Invoice();

        return v;
    }


    void Get_Invoice() {

        HashMap<String, String> data = new HashMap<>();
        data.put("iv_idx", iv_idx);
        new ApiClient(data, "proc_invoice_item", hdr);
    }

    void Set_Contents() {

        invoice_adapter = new InvoiceListRecyclerAdapter(getContext(), hdr, this::modifyClick);
        invoice_adapter.addItem(invoice_array.getArrayitem());

        //거래명세표 리스트 롱클릭 드래그 시 순서변경
        ItemTouchHelper.Callback callback = new ItemMoveCallback(invoice_adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(invoiceRV);

        layoutManager = new LinearLayoutManager(getContext());
        invoiceRV.setLayoutManager(layoutManager);
        invoiceRV.setAdapter(invoice_adapter);

        if (invoice_array.size() == 0) {

            invoice_nullLL.setVisibility(View.VISIBLE);
        }

        invoice_total_priceTV.setText(Common.getInstance().moneyFormatToWon(total_price));

        pd_priceET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //입력란에 변화가 있을 경우
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //입력이 끝났을 경우

                if (pd_priceET.isFocusable() && !s.toString().equals("") && !pd_cntET.getText().toString().equals("")) {

                    int supply = Integer.parseInt(pd_priceET.getText().toString()) * Integer.parseInt(pd_cntET.getText().toString());
                    pd_supply_priceTV.setText(Common.getInstance().moneyFormatToWon(supply));

                } else if (s.toString().equals("")) {
                    pd_supply_priceTV.setText(pd_cntET.getText().toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //입력 하기 전
            }
        });

        pd_cntET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //입력란에 변화가 있을 경우
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //입력이 끝났을 경우
                if (pd_cntET.isFocusable() && !s.toString().equals("") && !pd_priceET.getText().toString().equals("")) {

                    int supply = Integer.parseInt(pd_priceET.getText().toString()) * Integer.parseInt(pd_cntET.getText().toString());
                    pd_supply_priceTV.setText(Common.getInstance().moneyFormatToWon(supply));

                } else if (s.toString().equals("")) {
                    pd_supply_priceTV.setText(pd_priceET.getText().toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //입력 하기 전
            }
        });

    }

    private void init_Listener() {

        //품목 추가버튼 클릭시
        invoice_addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(pd_nameET.getText())) {

                    Toast.makeText(getContext(), "품명을 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(pd_cntET.getText())) {

                    Toast.makeText(getContext(), "수량을 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(pd_priceET.getText())) {

                    Toast.makeText(getContext(), "단가를 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                double vat = Integer.parseInt(pd_priceET.getText().toString()) * 0.1 * (Integer.parseInt(pd_cntET.getText().toString()));
                int final_vat = (int) Math.floor(vat);
                int supply_price = (Integer.parseInt(pd_priceET.getText().toString()) * (Integer.parseInt(pd_cntET.getText().toString())));
                int sum_price = final_vat + supply_price;

                int es_price = 0;
                int item_supply = 0;
                int item_vat = 0;
                int num = 1;

                if (invoice_array.size() > 0) {
                    for (int i = 0; i < invoice_array.size(); i++) {

                        item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
                        item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());

                    }
                    num = Integer.parseInt(invoice_array.getArrayitem().get(invoice_array.size() - 1).getNum()) + 1;
                }

                item_vat = (int) Math.floor(item_vat) + final_vat;
                item_supply = item_supply + supply_price;
                es_price = es_price + item_vat + item_supply;

                if (TextUtils.isEmpty(pd_idx) || pd_idx.equals("")) {
                    pd_idx = "0";
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("mode", "insert");
                data.put("iv_idx", iv_idx);
                data.put("pd_idx", pd_idx);
                data.put("pd_name", pd_nameET.getText().toString());
                data.put("pd_option", pd_optionET.getText().toString());
                data.put("pd_cnt", pd_cntET.getText().toString());
                data.put("pd_size", pd_unitET.getText().toString());
                data.put("price", pd_priceET.getText().toString());
                data.put("vat", "" + final_vat);
                data.put("supply_price", "" + supply_price);
                data.put("sum_price", "" + sum_price);
                data.put("es_price", "" + es_price);
                data.put("item_supply", "" + item_supply);
                data.put("item_vat", "" + item_vat);
                data.put("num", "" + num);

                if (!TextUtils.isEmpty(pd_code) && !TextUtils.isEmpty(pd_ttype)) {
                    data.put("pd_code", pd_code);
                    data.put("pd_ttype", pd_ttype);
                }

                new ApiClient(data, "proc_invoice_write", hdr);
            }
        });


        //수정버튼 클릭시
        invoice_modifyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(pd_nameET.getText())) {

                    Toast.makeText(getContext(), "품명을 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(pd_cntET.getText())) {

                    Toast.makeText(getContext(), "수량을 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(pd_priceET.getText())) {

                    Toast.makeText(getContext(), "단가를 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                double vat = Integer.parseInt(pd_priceET.getText().toString()) * 0.1 * (Integer.parseInt(pd_cntET.getText().toString()));
                int final_vat = (int) Math.floor(vat);
                int supply_price = (Integer.parseInt(pd_priceET.getText().toString()) * (Integer.parseInt(pd_cntET.getText().toString())));
                int sum_price = final_vat + supply_price;

                int es_price = 0;
                int item_supply = 0;
                int item_vat = 0;

                for (int i = 0; i < invoice_array.size(); i++) {

                    item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
                    item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());

                }

                item_vat = (int) Math.floor(item_vat) - Integer.parseInt(modify_vat) + final_vat;
                item_supply = item_supply - Integer.parseInt(modify_supply) + supply_price;
                es_price = es_price + item_vat + item_supply;

                if (TextUtils.isEmpty(pd_idx) || pd_idx.equals("")) {
                    pd_idx = "0";
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("mode", "update");
                data.put("iv_idx", iv_idx);
                data.put("ivi_idx", ivi_idx);
                data.put("pd_idx", pd_idx);
                data.put("pd_name", pd_nameET.getText().toString());
                data.put("pd_option", pd_optionET.getText().toString());
                data.put("pd_cnt", pd_cntET.getText().toString());
                data.put("pd_size", pd_unitET.getText().toString());
                data.put("price", pd_priceET.getText().toString());
                data.put("vat", "" + final_vat);
                data.put("supply_price", "" + supply_price);
                data.put("sum_price", "" + sum_price);
                data.put("es_price", "" + es_price);
                data.put("item_supply", "" + item_supply);
                data.put("item_vat", "" + item_vat);
                data.put("purchase_price", "0");

                if (!TextUtils.isEmpty(pd_code) && !TextUtils.isEmpty(pd_ttype)) {
                    data.put("pd_code", pd_code);
                    data.put("pd_ttype", pd_ttype);
                }

                new ApiClient(data, "proc_invoice_write", hdr);

            }
        });

        //삭제버튼 클릭시
        invoice_delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int es_price = 0;
                int item_supply = 0;
                int item_vat = 0;

                for (int i = 0; i < invoice_array.size(); i++) {

                    item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
                    item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());
                }

                item_vat = (int) Math.floor(item_vat) - Integer.parseInt(modify_vat);
                item_supply = item_supply - Integer.parseInt(modify_supply);
                es_price = es_price + item_vat + item_supply;

                HashMap<String, String> data = new HashMap<>();
                data.put("mode", "delete");
                data.put("iv_idx", iv_idx);
                data.put("ivi_idx", ivi_idx);
                data.put("es_price", "" + es_price);
                data.put("item_supply", "" + item_supply);
                data.put("item_vat", "" + item_vat);

                new ApiClient(data, "proc_invoice_write", hdr);
            }
        });

        //취소버튼 클릭시
        invoice_cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText edit[] = {pd_nameET, pd_optionET, pd_cntET, pd_unitET, pd_priceET};

                for (int i = 0; i < edit.length; i++) {
                    edit[i].getText().clear();
                    edit[i].clearFocus();
                }

                pd_supply_priceTV.setText("");
                ivi_idx = null;
                pd_idx = null;
                modify_supply = null;
                modify_vat = null;

                invoice_modifyBtn.setVisibility(View.GONE);
                invoice_delBtn.setVisibility(View.GONE);
                invoice_addBtn.setVisibility(View.VISIBLE);

            }
        });

        //품목 검색버튼 클릭시
        product_searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ProductSearchDialog dialog = new ProductSearchDialog(getContext(), new ProductSearchDialog.ProductSearchDialogListener() {

                    @Override
                    public void clickBtn(HashMap<String, String> data) {

                        pd_nameET.setText(data.get("pd_name"));
                        pd_optionET.setText(data.get("pd_option"));
                        pd_idx = data.get("pd_idx");
                        pd_code = data.get("pd_code");
                        pd_ttype = data.get("pd_ttype");

                    }
                }, fa.userItem.getArrayitem().getAgIdx());
                dialog.show();
            }
        });

//        //품목 순서저장 클릭시
//        invoice_orderBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                int es_price = 0;
//                int item_supply = 0;
//                int item_vat = 0;
//
//                for (int i = 0; i < invoice_adapter.getItemCount(); i++) {
//
//                    item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
//                    item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());
//
//                }
//
//                item_vat = (int)Math.floor(item_vat);
//                es_price = item_vat + item_supply;
//
//                for (int i = 0; i < invoice_adapter.getItemCount(); i++) {
//
//                    String index = invoice_adapter.getItemIndex(i);
//                    String ivi_idx = "" + invoice_adapter.getItemPdId(i);
//
//                    HashMap<String, String> data = new HashMap<>();
//                    data.put("mode", "order");
//                    data.put("iv_idx", iv_idx);
//                    data.put("ivi_idx", ivi_idx);
//                    data.put("num", index);
//                    data.put("es_price", "" + es_price);
//                    data.put("item_supply", "" + item_supply);
//                    data.put("item_vat", "" + item_vat);
//
//                    new ApiClient(data, "proc_invoice_write", hdr);
//                }
//            }
//        });

        //거래내역 버튼 클릭시
        transactionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransactionDialog dialog = new TransactionDialog(getContext(), new TransactionDialog.TransactionDialogListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> get_data) {

                        HashMap<String, String> data = new HashMap<>();
                        data.put("iv_idx", get_data.get("iv_idx"));

                        new ApiClient(data, "proc_invoice_item_view", hdr);
                    }
                });
                dialog.show();
            }
        });

        //QUICK 세트 클릭시
        quick_setBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                QuickSetDialog dialog = new QuickSetDialog(getContext(), new QuickSetDialog.QuicksetDialogListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> get_data) {

                        HashMap<String, String> data = new HashMap<>();
                        data.put("qs_idx", get_data.get("qs_idx"));

                        new ApiClient(data, "proc_estimate_quick_view", hdr);
                    }
                });
                dialog.show();
            }
        });

    }

    //거래명세표 리스트 수정버튼 클릭시
    @Override
    public void modifyClick(Item item) {

        pd_nameET.setText(item.getPdName());
        pd_optionET.setText(item.getPdOption());
        pd_cntET.setText(item.getPdCnt());
        pd_unitET.setText(item.getPdSize());
        pd_priceET.setText(item.getPrice());
        pd_supply_priceTV.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(item.getSupplyPrice())));
        ivi_idx = item.getIviIdx();
        pd_idx = item.getPdIdx();
        pd_code = item.getPdCode();
        pd_ttype = item.getPdTtype();

        modify_supply = item.getSupplyPrice();
        modify_vat = item.getVat();

        invoice_modifyBtn.setVisibility(View.VISIBLE);
        invoice_delBtn.setVisibility(View.VISIBLE);
        invoice_addBtn.setVisibility(View.GONE);

    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {
                    if (url.equals("proc_invoice_item")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        invoice_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<Item>>() {
                        }.getType());

                        if (invoice_array.isSuccess()) {

                            if (invoice_array.size() > 0) {

                                total_price = 0;

                                for (int i = 0; i < invoice_array.size(); i++) {
                                    invoice_data = invoice_array.getArrayitem().get(i);
                                    total_price = total_price + Integer.parseInt(invoice_data.getSupplyPrice());
                                }

                                invoice_nullLL.setVisibility(View.GONE);

                            } else {

                                invoice_nullLL.setVisibility(View.VISIBLE);
                            }

                            Set_Contents();

                        } else {

                            Toast.makeText(getContext(), invoice_array.getMessage(), Toast.LENGTH_SHORT).show();
                            Set_Contents();
                        }
                    } else if (url.equals("proc_invoice_write")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();

                            EditText edit[] = {pd_nameET, pd_optionET, pd_cntET, pd_unitET, pd_priceET};

                            for (int i = 0; i < edit.length; i++) {
                                edit[i].getText().clear();
                                edit[i].clearFocus();
                            }

                            pd_supply_priceTV.setText("");
                            ivi_idx = null;
                            pd_idx = null;
                            modify_supply = null;
                            modify_vat = null;

                            invoice_modifyBtn.setVisibility(View.GONE);
                            invoice_delBtn.setVisibility(View.GONE);
                            invoice_addBtn.setVisibility(View.VISIBLE);

                            total_price = 0;

                            Get_Invoice();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_estimate_quick_view")) {

                        ArrayItem<EstimateQuickData> quick_array;
                        EstimateQuickData quickData;

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        quick_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<EstimateQuickData>>() {
                        }.getType());

                        if (quick_array.isSuccess()) {

                            int es_price = 0;
                            int item_supply = 0;
                            int item_vat = 0;
                            int num = 1;
                            if (invoice_array.size() > 0) {

                                for (int i = 0; i < invoice_array.size(); i++) {

                                    item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
                                    item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());

                                }

                                num = Integer.parseInt(invoice_array.getArrayitem().get(invoice_array.size() - 1).getNum()) + 1;
                            }

                            if (quick_array.size() > 0) {

                                for (int i = 0; i < quick_array.size(); i++) {

                                    quickData = quick_array.getArrayitem().get(i);

                                    item_vat = (int) Math.floor(item_vat) + Integer.parseInt(quickData.getVat());
                                    item_supply = item_supply + Integer.parseInt(quickData.getSupplyPrice());
                                    es_price = item_vat + item_supply;

                                    HashMap<String, String> data = new HashMap<>();
                                    data.put("mode", "insert");
                                    data.put("iv_idx", iv_idx);
                                    data.put("pd_idx", quickData.getPdIdx());
                                    data.put("pd_name", quickData.getPdName());
                                    data.put("pd_option", quickData.getPdOption());
                                    data.put("pd_code", quickData.getPdCode());
                                    data.put("pd_ttype", quickData.getPdTtype());
                                    data.put("pd_cnt", quickData.getPdCnt());
                                    data.put("pd_size", quickData.getPdSize());
                                    data.put("price", quickData.getPrice());
                                    data.put("vat", quickData.getVat());
                                    data.put("supply_price", quickData.getSupplyPrice());
                                    data.put("sum_price", quickData.getSumPrice());
                                    data.put("es_price", "" + es_price);
                                    data.put("item_supply", "" + item_supply);
                                    data.put("item_vat", "" + item_vat);
                                    data.put("num", "" + num);

                                    new ApiClient(data, "proc_invoice_write", hdr);

                                    num++;
                                }
                            }

                        } else {

                            Toast.makeText(getContext(), quick_array.getMessage(), Toast.LENGTH_SHORT).show();
                            Set_Contents();
                        }
                    } else if (url.equals("proc_invoice_item_view")) {

                        ArrayItem<Item> item_array;
                        Item item_data;

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        item_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<Item>>() {
                        }.getType());

                        if (item_array.isSuccess()) {

                            int es_price = 0;
                            int item_supply = 0;
                            int item_vat = 0;
                            int num = 1;
                            if (invoice_array.size() > 0) {

                                for (int i = 0; i < invoice_array.size(); i++) {

                                    item_vat = item_vat + Integer.parseInt(invoice_array.getArrayitem().get(i).getVat());
                                    item_supply = item_supply + Integer.parseInt(invoice_array.getArrayitem().get(i).getSupplyPrice());

                                }

                                num = Integer.parseInt(invoice_array.getArrayitem().get(invoice_array.size() - 1).getNum()) + 1;
                            }

                            if (item_array.size() > 0) {

                                for (int i = 0; i < item_array.size(); i++) {

                                    item_data = item_array.getArrayitem().get(i);

                                    item_vat = (int) Math.floor(item_vat) + Integer.parseInt(item_data.getVat());
                                    item_supply = item_supply + Integer.parseInt(item_data.getSupplyPrice());
                                    es_price = item_vat + item_supply;

                                    HashMap<String, String> data = new HashMap<>();
                                    data.put("mode", "insert");
                                    data.put("iv_idx", iv_idx);
                                    data.put("pd_idx", item_data.getPdIdx());
                                    data.put("pd_name", item_data.getPdName());
                                    data.put("pd_option", item_data.getPdOption());
                                    data.put("pd_code", item_data.getPdCode());
                                    data.put("pd_ttype", item_data.getPdTtype());
                                    data.put("pd_cnt", item_data.getPdCnt());
                                    data.put("pd_size", item_data.getPdSize());
                                    data.put("price", item_data.getPrice());
                                    data.put("vat", item_data.getVat());
                                    data.put("supply_price", item_data.getSupplyPrice());
                                    data.put("sum_price", item_data.getSumPrice());
                                    data.put("es_price", "" + es_price);
                                    data.put("item_supply", "" + item_supply);
                                    data.put("item_vat", "" + item_vat);
                                    data.put("num", "" + num);

                                    new ApiClient(data, "proc_invoice_write", hdr);

                                    num++;
                                }
                            }

                        } else {

                            Toast.makeText(getContext(), invoice_array.getMessage(), Toast.LENGTH_SHORT).show();
                            Set_Contents();
                        }
                    } else if (msg.what == -1) {

                        Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
    }
}
