package com.tomastc.ht_nki;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.ht_nki.Adapter.Outbound_Picking_Adapter;
import com.tomastc.ht_nki.ListData.OutboundPicking_item;
import com.tomastc.ht_nki.lib.KeyMapping;
import com.tomastc.ht_nki.lib.Scanner;
import com.tomastc.ht_nki.lib.Settings;
import com.tomastc.ht_nki.lib.common.AsyncHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboundPicking_Activity extends Scanner implements View.OnClickListener {
    EditText edt_date_from, edt_date_to;
    String str_date_from, str_date_to;
    RecyclerView view_outbound_picking;
    Outbound_Picking_Adapter adapter_label;
    List<OutboundPicking_item> list_item;
    List<OutboundPicking_item> list_data_item;
    Map<String, OutboundPicking_item>    map_item;
    DecimalFormat decimalFormat;
    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;
    SwipeRefreshLayout swipeContainer;
    Intent intent;
    CheckBox checkbox_cheese;
    List<String> locationQcList;

    HashMap<String, OutboundPicking_item> map_list_item02;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outbound_picking);

        Log.e("T-T","InboundQCSchedule_Activity");
        list_item = new ArrayList<OutboundPicking_item>();
        map_item = new LinkedHashMap<>();
        map_list_item02 = new HashMap<>();

        decimalFormat = new DecimalFormat("##0.00");
        calendar = Calendar.getInstance();
        calendar_from = Calendar.getInstance();
        calendar_to = Calendar.getInstance();
        date = new SimpleDateFormat("yyyy-MM-dd");
        str_date_from = date.format(calendar_from.getTime());
        str_date_to = date.format(calendar_to.getTime());

        edt_date_from = (EditText)findViewById(R.id.edt_date_from);
        edt_date_from.setText(str_date_from);
        edt_date_from.setInputType(InputType.TYPE_NULL);
        edt_date_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(OutboundPicking_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_from = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_from.setText(str_date_from);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_date_to = (EditText) findViewById(R.id.edt_date_to);
        edt_date_to.setText(str_date_to);
        edt_date_to.setInputType(InputType.TYPE_NULL);
        edt_date_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(OutboundPicking_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_to = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_to.setText(str_date_to);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        checkbox_cheese = (CheckBox) findViewById(R.id.checkbox_cheese);
        checkbox_cheese.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                load_outbound_picking();
            }
        });

        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer2);
        swipeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(getString(R.string.tag), "swipeContainer click:" + "click");
            }
        });
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeContainer.setRefreshing(false);
                        load_outbound_picking();
                    }
                },2000);
            }
        });
        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        view_outbound_picking = (RecyclerView) findViewById(R.id.view_schedule_outbound_picking);
        view_outbound_picking.setHasFixedSize(true);
        view_outbound_picking.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_outbound_picking.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_outbound_picking.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_outbound_picking.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId()) {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finish();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();

        load_outbound_picking();
    }

    private void  load_outbound_picking(){
        try {

            map_item.clear();
            Date date_from = date.parse(str_date_from);
            Date date_to = date.parse(str_date_to);
            Log.d(getString(R.string.tag), "check date from-to: " + str_date_from + "-" + str_date_to);

            if (date_to.before(date_from)) {
                new SweetAlertDialog(OutboundPicking_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {
                try {

                    JSONObject json = new JSONObject();
                    json.put("cmd", "OUTBOUND/PICKING/SCHEDULE");
                    json.put("action_plan_date_from", str_date_from);
                    json.put("action_plan_date_to", str_date_to);
                    json.put("except_complete",checkbox_cheese.isChecked()?"NOT_COMPLETED":"");

                    new AsyncHttpClient(getApplicationContext(),
                            Settings.getMgmtList().get("web_api") + "/ht_api.php",
                            json.toString()) {

                        @Override
                        protected void onFinished(String response, int resp_code) {
                            Log.d(getString(R.string.tag), "response outbound : " + response);

                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);
                                Log.e("ToT","+++++++++> Length :"+jArray.length());
                                if (jArray.length() == 0){
                                    Toast.makeText(OutboundPicking_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {

                                    Map<String, Double> qtyMap = new HashMap<>();
                                    Map<String, Double> actionActQtyMap = new HashMap<>();

                                    for(int i = 0; i < jArray.length(); i++){
                                        try {
                                            JSONObject obj = jArray.getJSONObject(i);
                                            String doNo = obj.getString("do_no");
                                            double qty = Double.parseDouble(obj.getString("qty"));
                                            double actionActQty = Double.parseDouble(obj.getString("action_act_qty"));

                                            double totalQty = qtyMap.getOrDefault(doNo, 0.0) + qty;
                                            qtyMap.put(doNo, totalQty); // อัปเดตค่าในแผนที่
                                            String totalQTY = String.valueOf(totalQty); // แปลงเป็น String
                                            ///Action ACT QTY
                                            double totalActionActQty = actionActQtyMap.getOrDefault(doNo, 0.0) + actionActQty;
                                            actionActQtyMap.put(doNo, totalActionActQty); // อัปเดตค่าในแผนที่
                                            String totalActionActQTY = String.valueOf(totalActionActQty); // แปลงเป็น String

                                            map_item.put(jArray.getJSONObject(i).getString("do_no").trim(),
                                                    new OutboundPicking_item(
                                                            jArray.getJSONObject(i).getString("id").trim(),
                                                            jArray.getJSONObject(i).getString("invoice_no").trim(),
                                                            jArray.getJSONObject(i).getString("order_no").trim(),
                                                            jArray.getJSONObject(i).getString("do_no").trim(),
                                                            jArray.getJSONObject(i).getString("parts_no").trim(),
                                                            jArray.getJSONObject(i).getString("parts_name").trim(),
                                                            totalQTY , //jArray.getJSONObject(i).getString("qty").trim(),
                                                            totalActionActQTY, //jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                            jArray.getJSONObject(i).getString("action_type").trim(),
                                                            jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                                            jArray.getJSONObject(i).getString("status").trim(),
                                                            jArray.getJSONObject(i).getString("ref_id").trim(),
                                                            jArray.getJSONObject(i).getString("ref_type").trim(),
                                                            jArray.getJSONObject(i).getString("shipping_limit").trim(),
                                                            jArray.getJSONObject(i).getString("lot_no").trim(),
                                                            jArray.getJSONObject(i).getString("trucker_no").trim(),
                                                            jArray.getJSONObject(i).getString("cont_no").trim(),
                                                            "", //jArray.getJSONObject(i).getString("location_list".trim())
                                                            "",
                                                            "",
                                                            jArray.getJSONObject(i).getString("location_id").trim().contains("null")?"":jArray.getJSONObject(i).getString("location_id").trim()));

                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    Log.e("Map Size", "จำนวนข้อมูลใน map_item: " + map_item.size());
                                }
                          set_view_map(jArray);
                          set_view_data_();

                            }catch (JSONException e) {
                                new SweetAlertDialog(OutboundPicking_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("Can't connect server.")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();
                }catch (JSONException e) {
                    new SweetAlertDialog(OutboundPicking_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("Can't connect server.")
                            .setContentText(e.getMessage())
                            .show();
                }
            }
        }  catch (ParseException e){
            new SweetAlertDialog(OutboundPicking_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR : check date from-to ")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void set_view_map(JSONArray jArray){
        Log.i("ToT","======>>>>   :"+jArray.length());
        int count = 0;
        Map<String, Double> qtyMap = new HashMap<>();

        for(int i = 0; i < jArray.length(); i++) {
            try {
                JSONObject obj = jArray.getJSONObject(i);
                String doNo = obj.getString("do_no");
                double qty = Double.parseDouble(obj.getString("qty"));

                // รวมค่า qty ตาม do_no
                qtyMap.put(doNo, qtyMap.getOrDefault(doNo, 0.0) + qty);

            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }

         System.out.println("======>>>>   :ผลรวม QTY ตาม DO_NO:");
        for (Map.Entry<String, Double> entry : qtyMap.entrySet()) {
            System.out.println("======>>>>   :DO_NO: " + entry.getKey() + " => Total QTY: " + entry.getValue());
        }

    }
    private void set_view_data_(){
        list_item.clear();

            for (String key : map_item.keySet()) {
                OutboundPicking_item item = map_item.get(key);

                list_item.add(new OutboundPicking_item(
                        item.getId() != null ? item.getId() : "N/A",
                        !Objects.equals(item.getInvoice_no(), "null") ? item.getInvoice_no() : "0000000000",
                        item.getOrder_no() != null ? item.getOrder_no() : "N/A",
                        item.getDo_no() != null ? item.getDo_no() : "N/A",
                        item.getParts_no() != null ? item.getParts_no() : "N/A",
                        item.getParts_name() != null ? item.getParts_name() : "N/A",
                        item.getQty() != null ? item.getQty() : "0",
                        item.getUnit_qty() == null ? item.getUnit_qty() : "PCS",
                        item.getAction_type() != null ? item.getAction_type() : "N/A",
                        item.getAction_act_qty() != null ? item.getAction_act_qty() : "0",
                        item.getStatus() != null ? item.getStatus() : "N/A",
                        item.getRef_id() != null ? item.getRef_id() : "N/A",
                        item.getRef_type() != null ? item.getRef_type() : "N/A",
                        item.getShipping_limit() != null ? item.getShipping_limit() : "N/A",
                        item.getLot_no() != null ? item.getLot_no() : "N/A",
                        item.getTrucker_no() != null ? item.getTrucker_no() : "N/A",
                        item.getCont_no() != null ? item.getCont_no() : "N/A",
                        "TBC",
                        item.getCount_do_no(),
                        item.getCount_status(),
                        item.getLocation_id()
                ));


            }



        HashMap<String, Integer> sumQtyMap = calculateSumQty(list_item);

        Log.e("ToT","Sum QTY  : "+sumQtyMap);

        adapter_label = new Outbound_Picking_Adapter( list_item , this);
        view_outbound_picking.setAdapter(adapter_label);
    }
    private HashMap<String, Integer> calculateSumQty(List<OutboundPicking_item> data) {
        HashMap<String, Integer> sumQtyMap = new HashMap<>();
        for (OutboundPicking_item item : data) {
            String doNo = item.getDo_no();
            int qty = (int) Math.floor(Double.parseDouble(item.getQty()));

            sumQtyMap.put(doNo, sumQtyMap.getOrDefault(doNo, 0) + qty);
        }
        return sumQtyMap;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;
        }
    }

    @SuppressLint("SuspiciousIndentation")
    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if(data.trim().equals(""))
            return;

            intent = new Intent(this, OutboundPickingDetail_Activity.class);
            intent.putExtra("do_no", data);
            intent.putExtra("event", "S");
            this.startActivity(intent);
            finish();




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
