package com.tomas.lps_asi;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.Adapter.NG_Adapter;
import com.tomas.lps_asi.ListData.NG_Code;
import com.tomas.lps_asi.ListData.NG_List;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.Scanner;
import com.tomas.lps_asi.lib.common.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class TapingCheck_Activity extends Scanner implements View.OnClickListener {
    NG_Adapter ng_adapter;
    Calendar calendar;
    Map<String, NG_List> map_ng_scan;
    Map<String, NG_Code> map_code_ng;
    List<NG_List>list_ng;
    TextView txt_taping_lot, txt_check_time, txt_check_by, txt_user_id, txt_machine_code, txt_ng_code, txt_message;
    EditText edt_ng_qty, edt_remark;
    Spinner spinner_status;
    RecyclerView view_ng;
    Button btn_clear, btn_save;
    ImageButton imb_back;
    ConstraintLayout layout_alert;
    JSONArray  json_label_detail;
    String check_by, check_times, str_dt_format = "yyyy-MM-dd HH:mm:ss", aoi_type;
    SimpleDateFormat date_time_fm;
    int sum_ng = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taping_check);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        txt_message = (TextView)findViewById(R.id.txt_message);

        check_times = "";
        check_by = "";

        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        list_ng = new ArrayList<NG_List>();
        map_ng_scan = new LinkedHashMap<>();
        map_code_ng = new LinkedHashMap<>();

        txt_taping_lot = (TextView) findViewById(R.id.txt_taping_lot);
        txt_check_time = (TextView) findViewById(R.id.txt_check_time);
        txt_check_by = (TextView) findViewById(R.id.txt_check_by);
        txt_user_id = (TextView) findViewById(R.id.txt_user_id);
        txt_machine_code = (TextView) findViewById(R.id.txt_machine_code);
        txt_ng_code = (TextView) findViewById(R.id.txt_ng_code);

        edt_ng_qty = (EditText) findViewById(R.id.edt_ng_qty);
        edt_ng_qty.requestFocus();
        edt_ng_qty.setShowSoftInputOnFocus(false);
        edt_remark = (EditText) findViewById(R.id.edt_remark);

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

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

        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_save = (Button) findViewById(R.id.btn_save);

        Get_NGCode();

    }



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

            case R.id.btn_clear:
                Clear_layout();
                break;

            case R.id.btn_save:
                Check_data();
                break;

        }
    }

    private void Block_button() {
        btn_save.setEnabled(false);
        btn_save.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        btn_save.setEnabled(true);
        btn_save.setBackgroundResource(R.drawable.button_backgroup_green);
    }
    private void Clear_layout() {
        sum_ng = 0;
        check_times = "";
        check_by = "";
        map_ng_scan.clear();
        list_ng.clear();
        txt_taping_lot.setText("");
        txt_check_time.setText("Check times :  ");
        txt_check_by.setText("");
        txt_user_id.setText("");
        txt_machine_code.setText("");
        edt_remark.setText("");
        edt_ng_qty.setText("");
        spinner_status.setSelection(0);
        Set_View_NG_Scan();
    }

    private void Check_data() {
        if (txt_taping_lot.getText().toString().trim().equals("")){
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Taping label")
                    .show();

        }else if (txt_user_id.getText().toString().trim().equals("")){
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน")
                    .show();

        }else if (spinner_status.getSelectedItem().toString().trim().equals("")){
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาเลือกผลการตรวจสอบ")
                    .show();

        }else if (!check_by.trim().equals("operator_check") && txt_machine_code.getText().toString().trim().equals("")){
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนเครื่องตรวจ")
                    .show();
        }else if (spinner_status.getSelectedItem().toString().trim().equals("NG") && map_ng_scan.size() == 0){
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน NG")
                    .show();
        }else {
            Block_button();
            Save_TapingCheck();
        }
    }



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

        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            if (data.substring(0,1).trim().equals("E")){//taping label
                CheckTapingLabel(data.trim());

            }else if (data.substring(0,3).trim().equals("AOI")){//machine
                if (!txt_taping_lot.getText().toString().trim().equals("")
                        && !check_by.toString().trim().equals("operator_check")){
                    //check_machine
                    Check_MachineAOI(data.trim());
                }
            }else if (data.substring(0,2).trim().equals("NG")){//NG
                if (edt_ng_qty.getText().toString().trim().equals("")) {
                    new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาใส่จำนวน NG")
                            .show();
                } else {
                    String str_ng_code = data.trim();
                    Log.d(getString(R.string.tag), "str_ng_code : " + str_ng_code);

                    if (map_code_ng.containsKey(str_ng_code)) {
                        if (map_ng_scan.containsKey(str_ng_code)) {//ng code duplicate -->del
                            map_ng_scan.remove(str_ng_code);
                            Set_View_NG_Scan();

                        } else {//add map ng_list
                            txt_ng_code.setText(str_ng_code);
                            Add_map_ng_scan(str_ng_code);
                        }
                    } else {
                        txt_ng_code.setText("");
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบ NG code!")
                                .show();
                    }
                }

            }else if (data.length() == 6){//User
                if (Settings.getMap_user().containsKey(data.trim())){
                    if (Settings.getMap_user().get(data.trim()).getTapingCheck().trim().equals("1")){
                        txt_user_id.setText(data.trim());
                    }else {
                        txt_user_id.setText("");
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่อนุญาตให้ทำ Taping Check")
                                .show();
                    }
                }else {
                    txt_user_id.setText("");
                    new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบรหัสพนักงาน")
                            .show();
                }

            }else {
                new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("QR Code ไม่ถูกต้อง!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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



    private void Add_map_ng_scan(String ng_code) {
        Log.d(getString(R.string.tag), "Add_map_ng_scan : " + ng_code );

        NG_Code ng = map_code_ng.get(ng_code);
        map_ng_scan.put(ng_code, new NG_List(
                txt_taping_lot.getText().toString().trim(),
                ng.getNg_code(),
                ng.getNg_name(),
                edt_ng_qty.getText().toString().trim()));
        Log.e(getString(R.string.tag), "map_ng_scan: " + map_ng_scan.size());


        Set_View_NG_Scan();
        txt_ng_code.setText("");
        edt_ng_qty.setText("");
    }

    private void Set_View_NG_Scan() {
        sum_ng = 0;
        list_ng.clear();
        for (String key : map_ng_scan.keySet()) {
            NG_List list = map_ng_scan.get(key);
            list_ng.add(new NG_List(
                    list.getTaping_lot(),
                    list.getNg_code(),
                    list.getNg_name(),
                    list.getNg_qty()));

            String qty = list.getNg_qty();
            int int_qty = Integer.parseInt(qty);
            sum_ng = (sum_ng+int_qty);

        }
        ng_adapter = new NG_Adapter(list_ng, TapingCheck_Activity.this);
        view_ng.setAdapter(ng_adapter);
        Log.d(getString(R.string.tag), "sum_ng: " + sum_ng);
    }


    private void Save_TapingCheck() {
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        String dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");
            String create_user_id = txt_user_id.getText().toString().trim();
            String remark = edt_remark.getText().toString().trim();
            remark = URLEncoder.encode(remark,"UTF-8");

            //taping check
            JSONArray jArray_taping_check = new JSONArray();
            Map<String, String> jsontaping = new HashMap<>();
            jsontaping.put("taping_lot_no", txt_taping_lot.getText().toString().trim());
            jsontaping.put("check_times", check_times);
            jsontaping.put("check_by",check_by);
            jsontaping.put("machine_code", txt_machine_code.getText().toString().trim().equals("")?"":txt_machine_code.getText().toString().trim());
            jsontaping.put("ng_qty", String.valueOf(sum_ng));
            jsontaping.put("status", spinner_status.getSelectedItem().toString().trim());
            jsontaping.put("remark", remark);
            jsontaping.put("create_user_id", create_user_id);
            jsontaping.put("create_dt", dt_to_server);
            JSONObject jsonObjTp = new JSONObject(jsontaping);
            jArray_taping_check.put(jsonObjTp);

            //NG
            JSONArray jArray_ng = new JSONArray();
            if (map_ng_scan.size() > 0) {
                for (String key : map_ng_scan.keySet()) {
                    NG_List lists = map_ng_scan.get(key);
                    String ng_name = lists.getNg_name();
                    ng_name = URLEncoder.encode(ng_name,"UTF-8");

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("taping_lot_no", lists.getTaping_lot());
                    jsonParams.put("ng_code", lists.getNg_code());
                    jsonParams.put("ng_name", ng_name);
                    jsonParams.put("qty", lists.getNg_qty());
                    jsonParams.put("check_times", check_times);
                    jsonParams.put("create_user_id", create_user_id);
                    jsonParams.put("create_dt", dt_to_server);
                    JSONObject jsonObj = new JSONObject(jsonParams);
                    jArray_ng.put(jsonObj);
                }
            }else {
                jArray_ng = new JSONArray();

            }
            Log.d(getString(R.string.tag), "response: " + jArray_ng.length());

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            json.put("tp_check_datas",jArray_taping_check);
            json.put("ng_datas",jArray_ng);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/taping_check.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 status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            Unblock_button();
                            Clear_layout();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("บันทึกข้อมูลสำเร็จ")
                                    .show();

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(jsonObject.getString("message"))
                                    .show();
                        }

                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private void Check_MachineAOI(String machine_code) {
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("machine_code", machine_code);
            json.put("aoi_type",  check_by.trim().equals("aoi_machine")?"AOI":"IFAOI");
            json.put("type", json_label_detail.getJSONObject(0).getString("type"));

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_machine_code.setText("");
                            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักรนี้")
                                    .show();
                        }else {

//                            for (int i = 0; i < jArray.length(); i++) {
//                                aoi_type =  jArray.getJSONObject(i).getString("aoi_type").trim();
//                            }

                            Log.d(getString(R.string.tag), "check_by = " + check_by+" / aoi_type = "+aoi_type);
//                            if ((check_by.trim().equals("aoi_machine")&& aoi_type.trim().equals("AOI"))
//                            ||(check_by.trim().equals("if_aoi_machine")&& aoi_type.trim().equals("IFAOI"))){
                                txt_machine_code.setText(machine_code);
//                            }else {
//                                new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                        .setTitleText("แจ้งเตือน")
//                                        .setContentText("เครื่องจักรนี้ไม่ใช่ "+check_by)
//                                        .show();
//                            }
                        }
                        layout_alert.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void CheckTapingLabel(String taping_lot_no) {
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "check_taping");
            json.put("taping_lot_no", taping_lot_no);

            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/taping_check.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        String message = jsonObject.getString("message");
                        message = URLDecoder.decode(message, "UTF-8");
                        Log.d(getString(R.string.tag), "message: " + message);
                        check_times = jsonObject.getString("check_times");
                        check_by = jsonObject.getString("check_by");

                        if (status.trim().equals("success")){
                            json_label_detail = jsonObject.getJSONArray("label_detail");
                            Log.d(getString(R.string.tag), "json_label_detail: " + json_label_detail);

                            txt_taping_lot.setText(taping_lot_no);
                            txt_check_time.setText("Check times :  "+check_times+"#");
                            txt_check_by.setText(check_by);

                            if (check_by.trim().equals("operator_check")){
                                txt_machine_code.setBackgroundResource(R.drawable.button_backgroup_gray);
                            }else {
                                txt_machine_code.setBackgroundResource(R.drawable.img_backgroup);
                            }

                        }else {
                            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText(message)
                                    .show();
                        }
                            layout_alert.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
                    .execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Get_NGCode() {
        map_code_ng.clear();
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "search");

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ NG code")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                String code =  jArray.getJSONObject(i).getString("ng_code").trim();
                                String name =  jArray.getJSONObject(i).getString("ng_name").trim();
                                name =  URLDecoder.decode(name, "UTF-8");
                                map_code_ng.put(code, new NG_Code(code, name));
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_code_ng.size()));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }




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

                case P2:
                    btn_save.performClick();
                    break;

                case P3:
                    btn_clear.performClick();
                    break;

            }
        }

        return super.onKeyUp(keyCode, event);
    }

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