package com.tomas.pcs_asi;

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.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.Classify_Adapter;
import com.tomas.pcs_asi.Adapter.LotOut_Adapter;
import com.tomas.pcs_asi.ListData.Item_Classify;
import com.tomas.pcs_asi.ListData.Item_LotOut;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.KeyMapping;
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.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 Lotout_Activity extends Scanner implements View.OnClickListener {
    LotOut_Adapter lotOut_adapter;
    TextView txt_user, txt_ics, txt_job_order, txt_lot_no, txt_message;
    EditText edt_remark;
    Spinner spinner_process;
    RecyclerView view_lot_out;
    LinearLayout layout_btn_save, layout_btn_confirm, layout_input, layout_remark;
    ConstraintLayout layout_alert;
    Calendar calendar;
    SimpleDateFormat fm_dt_server;
    boolean confirm, scanner;
    int scan;
    String SCH_ID, dt_to_server, str_role ;
    Map<String, Item_LotOut> map_lot_out;
    List<Item_LotOut> list_lotout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lotout);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        scan = 0;
        confirm = false;
        scanner = true;
        map_lot_out = new LinkedHashMap<>();
        list_lotout = new ArrayList<Item_LotOut>();

        layout_btn_save = (LinearLayout)findViewById(R.id.layout_btn_save);
        layout_btn_confirm = (LinearLayout)findViewById(R.id.layout_btn_confirm);
        layout_input = (LinearLayout)findViewById(R.id.layout_input);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);

        txt_user = (TextView)findViewById(R.id.txt_user);
        txt_ics = (TextView)findViewById(R.id.txt_ics);
        txt_job_order = (TextView)findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView)findViewById(R.id.txt_lot_no);
        txt_message = (TextView)findViewById(R.id.txt_message);

        edt_remark = (EditText) findViewById(R.id.edt_remark);
        spinner_process = (Spinner) findViewById(R.id.spinner_process);

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


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imb_back:
                if (confirm == true){
                    Return_Layout();
                }else {
                    finish();
                }
                break;

            case R.id.btn_clear:
                map_lot_out.clear();
                Set_view_LotOut();
                break;

            case R.id.btn_confirmed:
                Update_LotOut();
                break;

            case R.id.btn_save:
                Set_Layout_View();
                break;
        }

    }

    private void Update_LotOut() {
            calendar = Calendar.getInstance();
            calendar = (Calendar) calendar.clone();
            dt_to_server = fm_dt_server.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 remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_lot_out");
                JSONArray jsonArray = new JSONArray();

                for (String key : map_lot_out.keySet()) {
                    Item_LotOut item = map_lot_out.get(key);

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("sch_id", item.getSch_id());
                    jsonParams.put("process", item.getProcess());
                    jsonParams.put("remark", encode);
                    jsonParams.put("user_id", txt_user.getText().toString().trim());
                    jsonParams.put("act_dt", dt_to_server);

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
                json.put("lotout_datas", jsonArray);

                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 {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d(getString(R.string.tag), "response : " + response);

                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");
                            if (status.equals("success") && affected_rows > 0) {
                                Toast.makeText(Lotout_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }


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

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);

            if (scanner == false) {
                return;

            }else {
                if (scan == 0) {
                    if (data.trim().length() == 10) { //ics
                        scan = 1;
                        txt_ics.setText(data.trim());
                        txt_job_order.setText("");
                        txt_lot_no.setText("");

                    }else if (data.trim().length() == 6) {//user
                        Check_User(data.trim());

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

                }else if (scan == 1) {
                    if (!data.trim().equals("")) {
                        txt_job_order.setText(data.trim());
                        scan = 2;
                    }
                }else {
                    if (!data.trim().equals("")) {
                        scan = 0;
                        txt_lot_no.setText(data.trim());
                        Check_ProcessSheet();
                    }
                }
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", txt_ics.getText().toString().trim());
            json.put("job_order", txt_job_order.getText().toString().trim());
            json.put("lot_no", txt_lot_no.getText().toString().trim());

            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){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Process sheet!")
                                    .show();
                            txt_ics.setText("");
                            txt_job_order.setText("");
                            txt_lot_no.setText("");
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                SCH_ID = jArray.getJSONObject(i).getString("sch_id").trim();
                            }
                            Log.d(getString(R.string.tag), "response: " + SCH_ID);
                            Add_Map_LotOut(SCH_ID);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Add_Map_LotOut(String sch_id) {
        if (map_lot_out.containsKey(sch_id)){// duplicate --> del
            map_lot_out.remove(sch_id);

        }else {
            map_lot_out.put(sch_id, new Item_LotOut(
                    sch_id,
                    txt_ics.getText().toString().trim(),
                    txt_job_order.getText().toString().trim(),
                    txt_lot_no.getText().toString().trim(),
                    spinner_process.getSelectedItem().toString().trim()));
            Log.d(getString(R.string.tag), "else: " + String.valueOf(map_lot_out.size()));
        }
        Set_view_LotOut();

    }

    private void Set_view_LotOut() {
        list_lotout.clear();
        for (String key : map_lot_out.keySet()){
            Item_LotOut item = map_lot_out.get(key);
            list_lotout.add(new Item_LotOut(
                    item.getSch_id(),
                    item.getIcs(),
                    item.getJob_order(),
                    item.getLot_no(),
                    item.getProcess()));
        }
        Log.d(getString(R.string.tag), "list_lotout: " + String.valueOf(list_lotout.size()));
        lotOut_adapter = new LotOut_Adapter(list_lotout, Lotout_Activity.this);
        view_lot_out.setAdapter(lotOut_adapter);
        scan = 0;
        txt_ics.setText("");
        txt_job_order.setText("");
        txt_lot_no.setText("");

    }

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
                User_Lists lists = Settings.getMap_user().get(data);
                String nameEng = lists.getNameEng();
                str_role = lists.getRole();
                Log.d(getString(R.string.tag), "nameEng : " + nameEng);
                Log.d(getString(R.string.tag), "str_role : " + str_role);

                if (str_role.trim().equals("LEADER")){
                    txt_user.setText(data);
                }else {
                    new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!!")
                            .show();
                }
        }else {
            txt_user.setText("");
            new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Set_Layout_View() {
        if (map_lot_out.size() == 0 ||
                txt_user.getText().toString().trim().equals("")){
            new SweetAlertDialog(Lotout_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else {
            scanner = false;
            confirm = true;
            layout_input.setVisibility(View.GONE);
            layout_btn_save.setVisibility(View.GONE);
            layout_btn_confirm.setVisibility(View.VISIBLE);

            txt_user.setBackgroundResource(R.drawable.img_backgroup);
            layout_remark.setBackgroundResource(R.drawable.img_backgroup);
            edt_remark.setEnabled(false);
        }
    }

    private void Return_Layout() {
        scanner = true;
        confirm = false;
        layout_input.setVisibility(View.VISIBLE);
        layout_btn_save.setVisibility(View.VISIBLE);
        layout_btn_confirm.setVisibility(View.GONE);

        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
        layout_remark.setBackgroundResource(R.drawable.button_backgroup_menu);
        edt_remark.setEnabled(true);

    }


    @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:
                    if (confirm == true){
                        Return_Layout();
                    }else {
                        finish();
                    }
                    break;
                case P2:
                    if (confirm == true){
                        // update lotout
                        Update_LotOut();
                    }else {
                        Set_Layout_View();
                    }
                    break;

                case P3:
                    map_lot_out.clear();
                    Set_view_LotOut();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }



}