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.TextView;
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.Inbound_Rack_Adapter;
import com.tomastc.ht_nki.ListData.InbounRackSchedule_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 cn.pedant.SweetAlert.SweetAlertDialog;

public class InboundRackSchedule_Activity extends Scanner implements View.OnClickListener {
    EditText edt_date_from, edt_date_to;
    String str_date_from, str_date_to;
    RecyclerView view_inbound_Rack;
    Inbound_Rack_Adapter adapter_label;
    Map<String, InbounRackSchedule_item> map_inboundRack_item;
    List<InbounRackSchedule_item> list_item;
    DecimalFormat decimalFormat;
    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;
    SwipeRefreshLayout swipeContainer;
    CheckBox checkbox_rack_inbound;
    TextView txt_user, txt_device ;

    boolean isCheck = true;

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

        list_item = new ArrayList<InbounRackSchedule_item>();
        map_inboundRack_item = new LinkedHashMap<>();

        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(InboundRackSchedule_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(InboundRackSchedule_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_rack_inbound = (CheckBox) findViewById(R.id.checkbox_rack_inbound);
        checkbox_rack_inbound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                load_inbound_rack_schedule();
            }
        });

        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_inbound_rack_schedule();
                    }
                },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_inbound_Rack = (RecyclerView) findViewById(R.id.view_schedule_Inbound_rack);
        view_inbound_Rack.setHasFixedSize(true);
        view_inbound_Rack.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_inbound_Rack.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_inbound_Rack.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_inbound_Rack.setItemAnimator(new DefaultItemAnimator());

    }


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

    private void load_inbound_rack_schedule() {
        try {
            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(InboundRackSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {

                map_inboundRack_item.clear();

                try {

                    JSONObject json = new JSONObject();
                    json.put("cmd", "INBOUND/RACK/SCHEDULE");
                    json.put("action_plan_date_from", str_date_from);
                    json.put("action_plan_date_to", str_date_to);
                    json.put("except_complete",checkbox_rack_inbound.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), "----> RACK response: " + response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);
                                if (jArray.length() == 0){
                                    Toast.makeText(InboundRackSchedule_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {
                                    Log.d("TOT","Count Data Rack  : "+jArray.length());

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

                                    String ticket_check="";
                                    String status="";
                                    for(int i = 0; i < jArray.length(); i++){
                                        try {
                                            JSONObject obj = jArray.getJSONObject(i);
                                            String ticketNo = obj.getString("ticket_no");

                                            if(ticket_check.equals(""))
                                            {

                                                ticket_check = jArray.getJSONObject(i).getString("ticket_no");
                                                status = jArray.getJSONObject(i).getString("status");


                                            }
                                            else if(!ticket_check.equals(jArray.getJSONObject(i).getString("ticket_no")))
                                            {

                                                ticket_check = jArray.getJSONObject(i).getString("ticket_no");
                                                status = jArray.getJSONObject(i).getString("status");

                                            }


                                            double qty = Double.parseDouble(obj.getString("qty"));
                                            double actionActQty = 0.00;


                                            if( jArray.getJSONObject(i).getString("status").equals(status))
                                            {
                                                actionActQty = Double.parseDouble(obj.getString("action_act_qty"));

                                            }
                           

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





                                            map_inboundRack_item.put(jArray.getJSONObject(i).getString("ticket_no"),
                                                    new InbounRackSchedule_item(
                                                            jArray.getJSONObject(i).getString("id").trim(),
                                                            jArray.getJSONObject(i).getString("order_no").trim().contains("null")?"":jArray.getJSONObject(i).getString("order_no").trim(),
                                                            jArray.getJSONObject(i).getString("ticket_no").trim(),
                                                            jArray.getJSONObject(i).getString("parts_no").trim(),
                                                            jArray.getJSONObject(i).getString("parts_name").trim(),
                                                            totalQTY, //jArray.getJSONObject(i).getString("qty").trim(),
                                                            jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                            status.contains("QC")? "0" : totalActionActQTY, //jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                                            status,
                                                            jArray.getJSONObject(i).getString("supplier_id").trim(),
                                                            jArray.getJSONObject(i).getString("tire_week").trim()
                                                    ));
                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }
                             set_view_map(jArray);
                             set_view_data();

                            }catch (JSONException e) {
                                new SweetAlertDialog(InboundRackSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR-01")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();
                }  catch (JSONException e) {
                    new SweetAlertDialog(InboundRackSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR-02")
                            .setContentText(e.getMessage())
                            .show();
                }
            }
        }  catch (ParseException e){
            new SweetAlertDialog(InboundRackSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR : check date from-to ")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void set_view_data(){
        list_item.clear();

        for (String key : map_inboundRack_item.keySet()) {
            InbounRackSchedule_item item = map_inboundRack_item.get(key);
            Log.d("TOT", "Data Status ====> : " + item.getStatus());
            Log.d("TOT", "Data Status ====> :  true");

            list_item.add(new InbounRackSchedule_item(
                    item.getId(),
                    item.getOrder_no(),
                    item.getTicket_no(),
                    item.getParts_no(),
                    item.getParts_name(),
                    item.getQty(),
                    item.getUnit_qty(),
                    item.getAction_act_qty(),
                    item.getStatus(),
                    item.getSupplier_id(),
                    item.getLot_no()
            ));


        }

        adapter_label = new Inbound_Rack_Adapter(list_item, this);
        view_inbound_Rack.setAdapter(adapter_label);
    }

    private void set_view_map(JSONArray jArray){
        Log.i("ToT","======>>>>   :"+jArray.length());
        int count = 0;
        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 ticketNo = obj.getString("ticket_no");
                double qty = Double.parseDouble(obj.getString("qty"));
                double action_act_qty = Double.parseDouble(obj.getString("action_act_qty"));

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

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

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

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.imb_back) {
            finish();
        }
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if(data.trim().equals(""))
            return;
        try {
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            String resultToken = tokens[0];

            if (tokens.length == 1){
                Intent  intent = new Intent(this, InboundRackScheduleDetail_Activity.class);
                intent.putExtra("ticket_no", resultToken);
                this.startActivity(intent);
            }else {
                new SweetAlertDialog(InboundRackSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }

        }catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

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

    @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);
    }

}
