package com.tomastc.ht_nki;


import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
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.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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_QC_Adapter;
import com.tomastc.ht_nki.ListData.InboundQCSchedule_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.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 InboundQCSchedule_Activity extends Scanner implements View.OnClickListener {

    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;
    String str_date_from, str_date_to,pub_status="";
    Spinner spinner_status;
    TextView txt_supplier, txt_part_no;
    Dialog dialog;
    EditText edt_date_from, edt_date_to;
    SwipeRefreshLayout swipeContainer;
    Inbound_QC_Adapter adapter;
    RecyclerView view_schedule_inbound_qc;
    Double sum_total;
    CheckBox checkbox_inbound_qc;
    Map<String, InboundQCSchedule_item> map_sch_inbound_qc_item;
    List<InboundQCSchedule_item> list_item_sch_inbound_qc;


    Double totalQty = 0.0;


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

        map_sch_inbound_qc_item = new LinkedHashMap<>();
        list_item_sch_inbound_qc = new ArrayList<InboundQCSchedule_item>();

        //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());


        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());

        spinner_status = (Spinner)findViewById(R.id.spinner_status);

        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(InboundQCSchedule_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(InboundQCSchedule_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_inbound_qc = findViewById(R.id.checkbox_inbound_qc);
        checkbox_inbound_qc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                load_schedule();
            }
        });

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

        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);
                        //Refresh
                        load_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
        );
    }

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

        load_schedule();
    }
    private void load_schedule() {
        try {//check date from-to
            Date date_from = date.parse(str_date_from);
            Date date_to = date.parse(str_date_to);

            if (date_to.before(date_from)) {
                new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {
                map_sch_inbound_qc_item.clear();
                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", "INBOUND/QC/SCHEDULE");
                    json.put("action_plan_date_from", str_date_from);
                    json.put("action_plan_date_to", str_date_to);
                    json.put("except_complete",checkbox_inbound_qc.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 ===> : " + response);

                            try{
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);

                                if (jArray.length() == 0) {
                                    Toast.makeText(InboundQCSchedule_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 ticketNo = obj.getString("ticket_no");
                                            double qty = Double.parseDouble(obj.getString("qty"));
                                            double 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_sch_inbound_qc_item.put( jArray.getJSONObject(i).getString("ticket_no").trim(),
                                                    new InboundQCSchedule_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(),
                                                            totalActionActQTY, //jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                                            totalQTY, //jArray.getJSONObject(i).getString("qty").trim(),
                                                            jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                            jArray.getJSONObject(i).getString("supplier_id").trim().contains("null")?"":jArray.getJSONObject(i).getString("supplier_id").trim(),
                                                            jArray.getJSONObject(i).getString("tire_week").trim(),
                                                            jArray.getJSONObject(i).getString("status").trim(),
                                                            jArray.getJSONObject(i).getString("bc_tire").trim(),
                                                            "", //jArray.getJSONObject(i).getString("sumQty").trim(),
                                                            "" //jArray.getJSONObject(i).getString("sumAction_act_qty").trim()
                                                    ));
                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }

                         set_view_map(jArray);
                         set_view_schedule();


                            }catch (JSONException e) {
                                new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("Data not found.")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();
                }catch (JSONException e) {
                    new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("Error connection server.")
                            .setContentText(e.getMessage())
                            .show();
                }
            }

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

    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("ticket_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 ตาม TICKET_NO:");
        for (Map.Entry<String, Double> entry : qtyMap.entrySet()) {
            System.out.println("======>>>>   :TICKET_NO: " + entry.getKey() + " => Total QTY: " + entry.getValue());
        }

    }

    private void set_view_schedule() {

        list_item_sch_inbound_qc.clear();


        for (String key : map_sch_inbound_qc_item.keySet()) {
            InboundQCSchedule_item item = map_sch_inbound_qc_item.get(key);
            double qty = Double.parseDouble(item.getQty()); // แปลง String เป็น double
            totalQty += qty; // รวมค่า qty
            Log.e("TOT", "Data SumQTY 02 : " + totalQty);
            list_item_sch_inbound_qc.add(new InboundQCSchedule_item(
                    item.getId(),
                    item.getOrder_no(),
                    item.getTicket_no(),
                    item.getParts_no(),
                    item.getParts_name(),
                    item.getAction_act_qty(),
                    item.getQty(),
                    item.getUnit_qty(),
                    item.getSupplier_id(),
                    item.getLot_no(),
                    item.getStatus(),
                    item.getBc_tire(),
                    String.valueOf(totalQty),
                    item.getSumAction_act_qty()
            ));
        }
        Log.e("TOT", "Data SumQTY 02 out loop: " + totalQty);


        adapter = new Inbound_QC_Adapter(list_item_sch_inbound_qc, this);
        view_schedule_inbound_qc.setAdapter(adapter);
    }

    @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
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;
        }

    }

    @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){

                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", "INBOUND/QC/DETAIL");
                    json.put("ticket_no", resultToken);

                    new AsyncHttpClient(getApplicationContext(),
                            Settings.getMgmtList().get("web_api") + "/ht_api.php",
                            json.toString()
                    ) {
                        @SuppressLint("StaticFieldLeak")
                        @Override
                        protected void onFinished(String response, int resp_code) {
                            Log.d(getString(R.string.tag), "response inbound detail: " + response);
                            try {

                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);

                                if (jArray.length() == 0 ) {

                                    Toast.makeText(InboundQCSchedule_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {


                                    pub_status = jArray.getJSONObject(0).getString("status").trim();




                                }



                            }catch (JSONException e) {
                                new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("Can not connect server")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();





                }catch (JSONException e) {
                    new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("Can not connect server")
                            .setContentText(e.getMessage())
                            .show();
                }


            }else {
                new SweetAlertDialog(InboundQCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }


            final Handler handler = new Handler();
            handler.postDelayed((Runnable) () -> {

                if (!pub_status.contains("COMPLETED")) {

                    Intent intent = new Intent(this, InboundQCScheduleDetail_Activity.class);
                    intent.putExtra("ticket_no", resultToken);
                    intent.putExtra("state", "scan");
                    this.startActivity(intent);
                    finish();

                } else {
                    Toast.makeText(InboundQCSchedule_Activity.this, "Status complete! ", Toast.LENGTH_SHORT).show();

                }


            }, 500);




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


    }


}
