package com.tomas.pcs_asi;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.Lot_DB_Adapter;
import com.tomas.pcs_asi.ListData.Get_Lot_DB;
import com.tomas.pcs_asi.ListData.Get_Lot_Ins;
import com.tomas.pcs_asi.lib.ConvertStringToCalendar;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.Scanner;
import com.tomas.pcs_asi.lib.common.Utils;

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.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Mold_Lot_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics, txt_job_order, txt_qty_lot, txt_working, txt_wait_oven, txt_oven, txt_message;
    String str_process, str_ics, str_job, str_lot_no, str_qty_lot, str_working, str_finish, str_wait, str_oven,
            process_check, status_check, dt_format = "yyyy-MM-dd HH:mm:ss", str_sch_id,
            str_machine, str_user_id, str_mag_no, str_qty_input, mold_plan_start_dt, mold_plan_end_dt;
//            mold_equipment_exp, mold_equipment;
    ConstraintLayout layout_alert;
    Calendar calendar;
    SimpleDateFormat date_time_fm;
    List<Get_Lot_DB> list_item;
    Lot_DB_Adapter lot_db_adapter;
    RecyclerView recyclerView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mold_lot);

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list_item = new ArrayList<Get_Lot_DB>();

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

        txt_header = (TextView) findViewById(R.id.txt_header_lot);
        txt_ics = (TextView) findViewById(R.id.txt_ics);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_qty_lot = (TextView) findViewById(R.id.txt_qty_lot);
        txt_working = (TextView) findViewById(R.id.txt_working);
        txt_wait_oven = (TextView) findViewById(R.id.txt_wait_oven);
        txt_oven = (TextView) findViewById(R.id.txt_oven);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

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

        str_process = Settings.getPROCESS();
        str_ics = Settings.getICS();
        str_job = Settings.getJobOrder();
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_qty_lot = (TextView) findViewById(R.id.txt_qty_lot);

        txt_header.setText(str_process+" LOT");
        txt_ics.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);

        Get_Schedule_Lot(str_ics, str_job);
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                Intent intent = new Intent(Mold_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

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

            try {

                    str_lot_no = data.trim();
                    Log.d(getString(R.string.tag), "lot_no : " + str_lot_no);
                    Check_ProcessSheet(str_ics, str_job, str_lot_no);

                Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", ics);
            json.put("job_order", job_order);
            json.put("lot_no", lot_no);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/production_plan.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){
                            str_lot_no = "";
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Mold_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Lot no.!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++){
                                process_check = jArray.getJSONObject(i).getString("process").trim();
                                status_check = jArray.getJSONObject(i).getString("status").trim();
                                str_sch_id = jArray.getJSONObject(i).getString("sch_id").trim();
                                str_qty_input = jArray.getJSONObject(i).getString("bonding_ins_output").trim() == "null" ? "" : jArray.getJSONObject(i).getString("bonding_ins_output").trim();
                                str_mag_no = jArray.getJSONObject(i).getString("bonding_ins_mag_no_output").trim() == "null" ? "" : jArray.getJSONObject(i).getString("bonding_ins_mag_no_output").trim();
                                str_machine = jArray.getJSONObject(i).getString("mold_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("mold_machine").trim();
                                str_user_id = jArray.getJSONObject(i).getString("mold_start_user_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("mold_start_user_id").trim();
//                                mold_equipment= jArray.getJSONObject(i).getString("mold_equipment").trim() == "null" ? "" : jArray.getJSONObject(i).getString("mold_equipment").trim();


                                JSONObject obj = jArray.getJSONObject(i);
                                JSONObject array_start_dt = obj.getJSONObject("mold_plan_start_dt");
                                mold_plan_start_dt = array_start_dt.getString("date");
                                mold_plan_start_dt = mold_plan_start_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "mold_plan_start_dt: " + mold_plan_start_dt);

                                JSONObject array_end_dt = obj.getJSONObject("mold_plan_end_dt");
                                mold_plan_end_dt = array_end_dt.getString("date");
                                mold_plan_end_dt = mold_plan_end_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "b_ins_plan_end_dt: " + mold_plan_end_dt);

//                                if (jArray.getJSONObject(i).getString("mold_equipment_exp").trim() == "null"){
//                                    mold_equipment_exp = " ";
//                                }else {
//                                    JSONObject array_eqm_exp = obj.getJSONObject("mold_equipment_exp");
//                                    mold_equipment_exp = array_eqm_exp.getString("date");
//                                    mold_equipment_exp = mold_equipment_exp.substring(0, 10);
//                                }
                            }
                            Check_Status();
//                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Mold_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_Status() {
        if (status_check.trim().equals(ProductionSchedule.STATUS.BONDING_INS_FINISHED.toString())){
            Check_Plan_start_end(mold_plan_start_dt, "Start Plan MOLD");

        }else if(status_check.trim().equals(ProductionSchedule.STATUS.MOLD_WORKING.toString())){
            Settings.setMACHINE(str_machine);
            Settings.setUserId(str_user_id);
            Settings.setQtyInput(str_qty_input);
//            Settings.setEQM(mold_equipment);
//            Settings.setEqmExp(mold_equipment_exp);
            Check_Plan_start_end(mold_plan_start_dt, "Finish Plan MOLD");

        }else{
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Mold_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("สถานะ ProcessSheet : "+status_check)
                    .show();
        }
    }

    private void Check_Plan_start_end(String plan_dt, String message) {
        calendar = ConvertStringToCalendar.convert(plan_dt,dt_format);
        String p_date1 = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date1);

        calendar.add(Calendar.MINUTE, 30);
        String p_date2 = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date2);

        Calendar now = Calendar.getInstance();
        Calendar now_dt = (Calendar) now.clone();
        String str_now = date_time_fm.format(now_dt.getTime());
        Log.d(getString(R.string.tag), "now_dt: " + str_now);

        if (now_dt.after(calendar)){
            Log.d(getString(R.string.tag), "if alert");
            Settings.setOverdueDt(plan_dt);
            Settings.setOverdueTitle(message);
        }else {
            Log.d(getString(R.string.tag), "else ");
            Settings.setOverdueDt("");
            Settings.setOverdueTitle("");
        }
        // Discard the ScanManager class instance.
        mScanManager.removeDataListener(Mold_Lot_Activity.this);
        // Discard the ScanManager class instance to release the resources.
        mScanManager.releaseScanManager();

        Settings.setSchId(str_sch_id);
        Settings.setLotNo(str_lot_no);
        Settings.setSTATUS(status_check);
        Settings.setMagNo(str_mag_no);
        Settings.setMcType(ProductionSchedule.MACHINE.MOLD.toString());

        Check_Random_Status();
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_status");
            json.put("sch_id", str_sch_id);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/random_check.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){
                            Intent intent = new Intent(Mold_Lot_Activity.this, Process_Activity.class);
                            startActivity(intent);
                            finish();
                        }else {
                            String id = jArray.getJSONObject(0).getString("id").trim();
                            String sch_id = jArray.getJSONObject(0).getString("sch_id").trim();
                            String machine_code = jArray.getJSONObject(0).getString("machine_code").trim();
                            String random_type = jArray.getJSONObject(0).getString("random_type").trim();
                            String check_time = jArray.getJSONObject(0).getString("check_time").trim();

                            Intent intent = new Intent(Mold_Lot_Activity.this, RandomCheck_Activity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("sch_id",sch_id);
                            intent.putExtra("machine_code",machine_code);
                            intent.putExtra("random_type",random_type);
                            intent.putExtra("check_time",check_time);
                            startActivity(intent);

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_sch_lot_mold");
            json.put("ics_product", ics);
            json.put("job_order", job_order);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/production_plan.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){
                            txt_working.setText("0");
                            txt_wait_oven.setText("0");
                            txt_oven.setText("0");
                            txt_qty_lot.setText("0 LOT");
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Mold_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่มีงานพร้อมเข้า mold.")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {

                                str_qty_lot = jArray.getJSONObject(i).getString("Qty_Lot").trim();
                                str_finish = jArray.getJSONObject(i).getString("FINISHED").trim();
                                str_working = jArray.getJSONObject(i).getString("WORKING").trim();
                                str_wait = jArray.getJSONObject(i).getString("WAIT_OVEN").trim();
                                str_oven = jArray.getJSONObject(i).getString("OVEN").trim();

                                list_item.add(new Get_Lot_DB(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        str_qty_lot,
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                        jArray.getJSONObject(i).getString("process").trim(),
                                        jArray.getJSONObject(i).getString("status").trim(),
                                        jArray.getJSONObject(i).getString("oven_mold_act_end_dt").trim() == "null" ? "" : jArray.getJSONObject(i).getString("oven_mold_act_end_dt").trim(),
                                        str_finish,
                                        str_working,
                                        str_wait,
                                        str_oven));
                            }

                            txt_working.setText(str_working);
                            txt_wait_oven.setText(str_wait);
                            txt_oven.setText(str_oven);
                            txt_qty_lot.setText(str_finish + " / " + str_qty_lot + " LOT");
                            View_data();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Mold_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void View_data() {
        Log.d(getString(R.string.tag), String.valueOf(list_item.size()));

        lot_db_adapter = new Lot_DB_Adapter(list_item, Mold_Lot_Activity.this, "MOLD");
        recyclerView.setAdapter(lot_db_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }


    @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:
                    Intent intent = new Intent(Mold_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }
}