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.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.NG_Adapter;
import com.tomas.pcs_asi.ListData.Get_OutputCode;
import com.tomas.pcs_asi.ListData.NG_Lists;
import com.tomas.pcs_asi.ListData.User_Lists;
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.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 Mold_Output_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics_product, txt_job_order, txt_lot_no, txt_user, txt_scan_ng, txt_input, txt_output, txt_overdue_title, txt_overdue_dt, txt_message,
            txt_leader, txt_leader_lotout;
    EditText edt_qty_ng, edt_remark;
    LinearLayout layout_scan, layout_sum, layout_remark;
    ConstraintLayout layout_alert, layout_alert_plan, layout_output, layout_nurse_call, layout_lotout;
    Button btn_confirm, btn_finish;
    String str_process, str_status, str_overdue_dt, str_overdue_title, str_sch_id, str_ics_product, str_job, str_lot, str_input, str_role, dt_to_server,
    str_ng_code, str_leader,DefectName;
    int sum_output, output, total, input;
    Map<String, Get_OutputCode> map_code_ng;
    Map<String, NG_Lists>map_ng_scan;
    List<NG_Lists> list_ng;
    boolean Overdue, nurse_call, lot_out, Finish, b_confirm;
    NG_Adapter ng_adapter;
    RecyclerView view_ng;
    Calendar calendar;
    SimpleDateFormat fm_dt_server;

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

        b_confirm = true;
        Finish = false;
        nurse_call = false;
        Overdue = false;
        lot_out = false;
        map_code_ng = new LinkedHashMap<>();
        map_ng_scan = new LinkedHashMap<>();
        list_ng = new ArrayList<NG_Lists>();

        layout_lotout = (ConstraintLayout)findViewById(R.id.layout_lotout);
        txt_leader_lotout = (TextView)findViewById(R.id.txt_leader_lotout);

        layout_scan = (LinearLayout) findViewById(R.id.layout_scan_ng);
        layout_sum = (LinearLayout) findViewById(R.id.layout_sum);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);
        layout_alert = (ConstraintLayout) findViewById(R.id.layout_alert);
        layout_alert_plan = (ConstraintLayout) findViewById(R.id.layout_alert_plan);
        layout_output = (ConstraintLayout)findViewById(R.id.layout_output);
        layout_nurse_call = (ConstraintLayout) findViewById(R.id.layout_nurse_call);

        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_finish = (Button)findViewById(R.id.btn_finish);

        txt_header = (TextView)findViewById(R.id.txt_header);
        txt_ics_product = (TextView) findViewById(R.id.txt_ics_product);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_scan_ng = (TextView)findViewById(R.id.txt_ng_code) ;
        txt_input = (TextView) findViewById(R.id.txt_total_input);
        txt_output = (TextView)findViewById(R.id.txt_total_output);
        txt_overdue_title = (TextView)findViewById(R.id.txt_overdue_title);
        txt_overdue_dt= (TextView)findViewById(R.id.txt_overdue_dt);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_leader = (TextView)findViewById(R.id.txt_leader);

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

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

        str_process = Settings.getPROCESS();
        str_status  = Settings.getSTATUS();
        str_overdue_dt  = Settings.getOverdueDt();
        str_overdue_title = Settings.getOverdueTitle();
        str_sch_id = Settings.getSchId();
        str_ics_product = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_input = Settings.getQtyInput();
        input = Integer.parseInt(str_input);
        Log.d(getString(R.string.tag), "MOLD Output Activity : " + str_process+" | "+ str_status+ " | "+str_overdue_dt+"|"+str_input);

        txt_header.setText(str_process+" OUTPUT");
        txt_ics_product.setText("ICS : "+str_ics_product);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot);
        txt_input.setText(str_input);

        if (str_overdue_dt.trim().equals("") || str_overdue_dt.trim().equals("null")) {
            Overdue = false;
            layout_alert_plan.setVisibility(View.GONE);
            layout_output.setVisibility(View.VISIBLE);

        } else {
            Overdue = true;
            layout_output.setVisibility(View.GONE);
            txt_overdue_title.setText(str_overdue_title);
            txt_overdue_dt.setText(str_overdue_dt);
            layout_alert_plan.setVisibility(View.VISIBLE);
        }
        Get_Output_List(str_process);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                if (Finish == true){
                    Return_Layout();
                }else{
                    Intent i = new Intent(Mold_Output_Activity.this, Process_Activity.class);
                    startActivity(i);
                    finish();
                }
                break;

            case R.id.btn_finish:
                if (txt_user.getText().toString().equals("")) {
                    new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนรหัสพนักงาน!")
                            .show();
                }else {
                    Finish = true;
                    Set_Layout_view();
                    btn_finish.setVisibility(View.GONE);
                    btn_confirm.setVisibility(View.VISIBLE);
                }
                break;

            case R.id.btn_ok:
                Overdue = false;
                layout_alert_plan.setVisibility(View.GONE);
                layout_output.setVisibility(View.VISIBLE);
                break;

            case R.id.btn_ok_nurse_call:
                OK_NurseCall();
                break;

            case R.id.btn_cancel_nurse_call:
                Cancel_NurseCall();
                break;

            case R.id.btn_confirm:
                if (b_confirm == true) {
                    Block_button();
                    Check_output();
                }
                break;

            case R.id.btn_ok_lotout:
                if (b_confirm == true) {
                    Block_button();
                    Update_Output();
                }
                break;

            case R.id.btn_cancel_lotout:
                Cancel_LotOut();
                break;
        }
    }

    private void Block_button() {
        b_confirm = false;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_backgroup_blue);
    }

    private void Update_Output() {
        if (txt_leader_lotout.getText().toString().trim().equals("")) {
            Unblock_button();
            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        } else {
            layout_lotout.setVisibility(View.GONE);
            Update_mold_wait();
        }
    }

    private void Cancel_LotOut() {//P3
        txt_leader_lotout.setText("");
        lot_out = false;
        layout_lotout.setVisibility(View.GONE);
        Unblock_button();
    }

    private void Check_output() {
        int i_output;
        if (txt_output.getText().toString().trim().equals("")){
            i_output = 0;
        }else{
            String str_output = txt_output.getText().toString().trim();
            i_output = Integer.parseInt(str_output);
        }

        if (i_output <= 0){
            Unblock_button();
                lot_out = true;
                layout_lotout.setVisibility(View.VISIBLE);

        }else {
            Update_mold_wait();
        }
    }



    @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 (lot_out == true){
                if (data.trim().length() == 6){
                    Check_User(data.trim());

                }else {
                    new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR code ไม่ถูกต้อง!")
                            .show();
                }
            }else if (Finish == true) {
                return;
            }else {
                String str_scan = data.trim();
                str_ng_code = "";
                Log.d(getString(R.string.tag), "scan data : " + data.substring(0, 2));

                if (str_scan.substring(0, 2).equals("NG")) {
                    if (edt_qty_ng.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาใส่จำนวน NG")
                                .show();
                    } else {
                        str_ng_code = str_scan;
                        Log.d(getString(R.string.tag), "str_ng_code : " + str_ng_code);

                        if (map_code_ng.containsKey(str_scan)) {
                            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_scan_ng.setText(str_ng_code);
                                Get_OutputCode outputCode = map_code_ng.get(str_ng_code);
                                String s_nurse_call = outputCode.getNurse_call();

                                if (s_nurse_call.trim().equals("1")) {
                                    nurse_call = true;
                                    layout_output.setVisibility(View.GONE);
                                    layout_nurse_call.setVisibility(View.VISIBLE);

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

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

                } else {
                    new SweetAlertDialog(Mold_Output_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, String nurse_call) {
        Log.d(getString(R.string.tag), "Add_map_ng_scan : " + ng_code+"|"+nurse_call);

        Get_OutputCode outputCode = map_code_ng.get(ng_code);
        map_ng_scan.put(ng_code, new NG_Lists(
                str_sch_id,
                outputCode.getCode(),
                outputCode.getName(),
                edt_qty_ng.getText().toString().trim(),
                str_process,
                nurse_call,
                outputCode.getCalculate()));

        Set_View_NG_Scan();
        Log.e(getString(R.string.tag), "map_ng_scan: " + map_ng_scan.size());

        txt_scan_ng.setText("");
        edt_qty_ng.setText("");
        txt_leader.setText("");
    }
    private void Set_View_NG_Scan() {
        list_ng.clear();
        for (String key : map_ng_scan.keySet()){
            NG_Lists lists = map_ng_scan.get(key);
            list_ng.add(new NG_Lists(
                    lists.getSch_id(),
                    lists.getNg_code(),
                    lists.getNg_name(),
                    lists.getNg_qty(),
                    lists.getProcess(),
                    lists.getNurse_call_user_id(),
                    lists.getCalculate()));
        }

        ng_adapter = new NG_Adapter(list_ng, Mold_Output_Activity.this, str_process);
        view_ng.setAdapter(ng_adapter);
    }

    private void Cancel_NurseCall() {
        nurse_call = false;
        layout_output.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);
        txt_scan_ng.setText("");
        txt_header.setText("");
    }

    private void OK_NurseCall() {
        nurse_call = false;
        layout_output.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);

        str_leader = txt_leader.getText().toString().trim();
        str_ng_code = txt_scan_ng.getText().toString().trim();
        if (str_leader.equals("")){
            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสleader!")
                    .show();
        }else {
            Add_map_ng_scan(str_ng_code, str_leader);
        }
    }
    private void Return_Layout() {
        Finish = false;
        layout_sum.setVisibility(View.GONE);
        btn_confirm.setVisibility(View.GONE);
        layout_scan.setVisibility(View.VISIBLE);
        btn_finish.setVisibility(View.VISIBLE);
        layout_remark.setBackgroundResource(R.drawable.button_backgroup_menu);
        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
        edt_remark.setEnabled(true);



    }
    private void Set_Layout_view() {
        btn_finish.setVisibility(View.GONE);
        layout_scan.setVisibility(View.GONE);
        btn_confirm.setVisibility(View.VISIBLE);
        layout_sum.setVisibility(View.VISIBLE);
        txt_user.setBackgroundResource(R.drawable.img_backgroup);
        layout_remark.setBackgroundResource(R.drawable.img_backgroup);
        edt_remark.setEnabled(false);

        //sum output
        sum_output = 0; total = 0;
        if(map_ng_scan.size() == 0){//????? NG
            sum_output = 0;
        }else {
            for (String key : map_ng_scan.keySet()) {
                NG_Lists lists = map_ng_scan.get(key);
                String output_qty = lists.getNg_qty();
                output = Integer.parseInt(output_qty);
                Log.d(getString(R.string.tag), "sum_output" + sum_output + "+" + output);
                sum_output = (sum_output + output);
                Log.d(getString(R.string.tag), "sum_output" + sum_output);
            }
        }
        total = (input - sum_output);
        Log.d(getString(R.string.tag), "total :" + total+"="+input+"-"+sum_output);
        txt_output.setText(String.valueOf(total));


    }
    private void Update_mold_wait() {
        Log.d(getString(R.string.tag), "Update_mold_wait : ");
            Block_button();

            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_mold_wait");
                json.put("remark", encode);
                json.put("output", txt_output.getText().toString().trim());
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_id);
                if (lot_out == false){//????????? lotout ??? update last_output_qty
                    json.put("last_output", txt_output.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 {
                            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) {
                                if (map_ng_scan.size() >0) {
                                    Insert_NGList();
                                }else{
                                    Toast.makeText(Mold_Output_Activity.this,"บันทึกข้อมูลเรียบร้อยแล้ว",Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            } else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                Unblock_button();
                new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Insert_NGList() {
        Block_button();
        Log.d(getString(R.string.tag), "Insert_NGList : " + map_ng_scan.size());

        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());

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

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

            for (String key : map_ng_scan.keySet()){
                NG_Lists lists = map_ng_scan.get(key);

                String ng = lists.getNg_name();
                String ng_name = URLEncoder.encode(ng,"UTF-8");

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", lists.getSch_id());
                jsonParams.put("ng_code", lists.getNg_code());
                jsonParams.put("ng_name", ng_name);
                jsonParams.put("qty", lists.getNg_qty());
                jsonParams.put("process", lists.getProcess());
                jsonParams.put("nurse_call_user_id", lists.getNurse_call_user_id());
                jsonParams.put("create_dt", dt_to_server);
                jsonParams.put("create_user_id", txt_user.getText().toString().trim());
                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);
            }
            json.put("ng_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ng_factor_list.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) {
                            if (lot_out == true){
                                Update_LotOut();

                            }else{
                                Toast.makeText(Mold_Output_Activity.this,"บันทึกข้อมูลเรียบร้อยแล้ว",Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert NGFactorList")
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Update_LotOut() {
        Block_button();

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

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", str_sch_id);
                jsonParams.put("process", str_process);
                jsonParams.put("remark", encode);
                jsonParams.put("user_id", txt_leader_lotout.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(Mold_Output_Activity.this, "บันทึกข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                                finish();

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

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/output_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(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ NG code!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    DefectName =  jArray.getJSONObject(i).getString("DefectName").trim();
                                    Log.d(getString(R.string.tag), "DefectName: " + DefectName);
                                    DefectName =  URLDecoder.decode(DefectName, "UTF-8");
                                    Log.d(getString(R.string.tag), "DefectName_decode: " + DefectName);

                                }catch (Exception e){
                                    layout_alert.setVisibility(View.GONE);
                                    new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("ERROR")
                                            .setContentText(e.getMessage())
                                            .show();
                                }
                                map_code_ng.put(jArray.getJSONObject(i).getString("Code").trim(),
                                        new Get_OutputCode(
                                                jArray.getJSONObject(i).getString("Process").trim(),
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                DefectName,
                                                jArray.getJSONObject(i).getString("Status").trim(),
                                                jArray.getJSONObject(i).getString("NurseCall").trim(),
                                                jArray.getJSONObject(i).getString("Calculate").trim()));
                            }
                            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(Mold_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){

            if (nurse_call == true || lot_out == true){//scan leader
                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")){
                    if (lot_out == true){
                        txt_leader_lotout.setText(data);
                    }else {
                        txt_leader.setText(data);
                    }
                }else {
                    new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!")
                            .show();
                }
            }else {
                if (Settings.getMap_user().get(data).getMold().trim().equals("1")) {
                    txt_user.setText(data);

                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่อนุญาตให้ทำงานใน "+str_process)
                            .show();
                }
            }

        }else {
            txt_user.setText("");
            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    @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 (Finish == true){
                        Return_Layout();
                    }else{
                        Intent i = new Intent(Mold_Output_Activity.this, Process_Activity.class);
                        startActivity(i);
                        finish();
                    }
                    break;

                case P2:
                    if (lot_out == true){
                        if (b_confirm == true) {
                            Block_button();
                            Update_Output();
                        }
                    }else if (nurse_call == true) {
                        OK_NurseCall();

                    }else if(Finish == true){
                        if (b_confirm == true) {
                            Block_button();
                            Check_output();
                        }

                    }else if (Overdue == true){
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_output.setVisibility(View.VISIBLE);
                    }else {
                        if (txt_user.getText().toString().equals("")) {
                            new SweetAlertDialog(Mold_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                                    .show();
                        }else {
                            Finish = true;
                            Set_Layout_view();
                            btn_finish.setVisibility(View.GONE);
                            btn_confirm.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                case P3:
                    if (lot_out == true){
                        Cancel_LotOut();

                    }else if (nurse_call == true){
                        Cancel_NurseCall();
                    }
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}