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.content.Intent;
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.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.Adapter.RandomCheckNG_Adapter;
import com.tomas.pcs_asi.ListData.Get_OutputCode;
import com.tomas.pcs_asi.ListData.NG_Lists;
import com.tomas.pcs_asi.ListData.RandomCheck_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 Ins_Output_Activity extends Scanner implements View.OnClickListener {
    TextView txt_message, txt_header, txt_ics, txt_lot_no, txt_job_order, txt_check_time, txt_mag_no, txt_user, txt_overdue_title,
            txt_overdue_dt, txt_input, txt_scan, txt_leader, txt_total_input, txt_total_output, txt_leader_lotout,
            txt_qty_ng_process2, txt_qty_ng_process1, txt_process1, txt_process2;
    String str_process, str_status, str_overdue_dt, str_overdue_title, str_sch_id, str_ics, str_job, str_lot, str_check_time, str_mag_no, machine_type, str_input, dt_to_server, str_role, str_ng_code, str_leader, str_machine,
            DefectName, Machine_Ins, str_bonding_ng, str_cmd;
    EditText edt_qty_ng, edt_remark;
    ConstraintLayout layout_alert, layout_alert_plan, layout_nurse_call, layout_lotout;
    LinearLayout layout_process, layout_ng_his, layout_scan_ng, layout_btn_choose, layout_btn_confirmed, layout_btn_finished, layout_sum,
             layout_remark, layout_mag_no, layout_ng_random;
    Map<String, Get_OutputCode> map_code_ng;
    Map<String, NG_Lists>map_ng_scan;
    List<NG_Lists>list_ng;
    List<NG_Lists>list_ng_his;
    List<RandomCheck_NG_Lists>list_random_ng;
    int check_time, update_check_time, sum_output, output, total, input, sum_process1 = 0, sum_process2 = 0,
            RC_NGDB17, RC_NGWB, SUM_RC_NG;
    boolean Overdue, nurse_call, confirmed, finished, lot_out, b_confirm, Alert_qty_ng;
    Calendar calendar;
    SimpleDateFormat fm_dt_server;
    RecyclerView view_ng, view_ng_his, view_ng_random;
    NG_Adapter ng_adapter;
    RandomCheckNG_Adapter random_ng_adapter;

    Button btn_confirmed, btn_finished;
    int bonding_ng, sum_ng17 = 0, sum_ngwb = 0;

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

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        nurse_call = false;
        Overdue = false;
        confirmed = false;
        finished = false;
        lot_out = false;
        b_confirm = true;
        Alert_qty_ng = false;

        map_code_ng = new LinkedHashMap<>();
        map_ng_scan = new LinkedHashMap<>();

        list_ng = new ArrayList<NG_Lists>();
        list_ng_his = new ArrayList<NG_Lists>();
        list_random_ng = new ArrayList<RandomCheck_NG_Lists>();

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

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_alert_plan = (ConstraintLayout) findViewById(R.id.layout_alert_plan);
        layout_nurse_call = (ConstraintLayout) findViewById(R.id.layout_nurse_call);
        layout_process = (LinearLayout)findViewById(R.id.layout_process);
        layout_ng_his = (LinearLayout)findViewById(R.id.layout_ng_his);
        layout_scan_ng = (LinearLayout)findViewById(R.id.layout_scan_ng);
        layout_btn_choose = (LinearLayout)findViewById(R.id.layout_btn_choose);
        layout_btn_confirmed = (LinearLayout)findViewById(R.id.layout_btn_confirmed);
        layout_btn_finished = (LinearLayout)findViewById(R.id.layout_btn_finished);
        layout_sum = (LinearLayout)findViewById(R.id.layout_sum);
//        layout_input = (LinearLayout)findViewById(R.id.layout_input);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);
        layout_mag_no = (LinearLayout)findViewById(R.id.layout_mag_no);
        layout_ng_random = (LinearLayout)findViewById(R.id.layout_ng_random);

        btn_confirmed = (Button)findViewById(R.id.btn_confirmed);
        btn_finished = (Button)findViewById(R.id.btn_finished);
        txt_header = (TextView) findViewById(R.id.txt_header);
        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_check_time = (TextView) findViewById(R.id.txt_check_time);
        txt_mag_no = (TextView) findViewById(R.id.txt_mag_no);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_input = (TextView)findViewById(R.id.txt_input);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_overdue_title = (TextView) findViewById(R.id.txt_overdue_title);
        txt_overdue_dt = (TextView) findViewById(R.id.txt_overdue_dt);
        txt_scan = (TextView)findViewById(R.id.txt_scan_ng);
        txt_leader = (TextView)findViewById(R.id.txt_leader);
        txt_total_input = (TextView)findViewById(R.id.txt_total_input);
        txt_total_output = (TextView)findViewById(R.id.txt_total_output);
        txt_process1 = (TextView)findViewById(R.id.txt_process1);
        txt_process2 = (TextView)findViewById(R.id.txt_process2);
        txt_qty_ng_process1 = (TextView)findViewById(R.id.txt_qty_ng_process1);
        txt_qty_ng_process2 = (TextView)findViewById(R.id.txt_qty_ng_process2);

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

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

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

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

        view_ng_random = (RecyclerView)findViewById(R.id.view_ng_random);
        view_ng_random.setHasFixedSize(true);
        view_ng_random.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_ng_random.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_ng_random.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_ng_random.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 = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_check_time = Settings.getCheckTime();
        str_mag_no = Settings.getMagNo();
        machine_type = Settings.getMcType();
        str_input = Settings.getQtyInput();
        input = Integer.parseInt(str_input);
        Log.d(getString(R.string.tag), "Ins output Activity : " + str_process+" | "+ str_status+ " | "+str_overdue_dt+"|"+str_mag_no);

        update_check_time = Integer.parseInt(str_check_time);
        update_check_time = (update_check_time + 1);

        txt_header.setText(str_process+" OUTPUT");
        txt_ics.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot);
        txt_check_time.setText(str_check_time);
        txt_input.setText(str_input);
        txt_total_input.setText(str_input);

        if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())){
            str_cmd = "search_mold_dicer";
            txt_process1.setText("Mold");
            txt_process2.setText("Dicer");
            layout_mag_no.setVisibility(View.GONE);
        }else {
            str_cmd = "search_db_wb";
            txt_process1.setText("Diebond");
            txt_process2.setText("Wirebond");
        }

        //get history
        check_time = Integer.parseInt(str_check_time);
        if (check_time > 1){
            Log.d(getString(R.string.tag), "layout_ng_his : " + str_process+" | "+ str_process+ " | "+str_check_time);

            Get_NG_History(str_sch_id, str_process);

        }

        Get_RandomCheck_NG();
        Get_List_Output(str_process);
        Get_Machine();
    }




    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                    Overdue = false;
                    layout_alert_plan.setVisibility(View.GONE);
                    layout_process.setVisibility(View.VISIBLE);
                break;

            case R.id.imb_back:
                Log.d(getString(R.string.tag), "imb_back :" + confirmed+"/"+finished+"/"+Overdue);
                if (Overdue == true && finished == true){
                    Return_Layout();
                    Overdue = false;
                    layout_alert_plan.setVisibility(View.GONE);
                    layout_process.setVisibility(View.VISIBLE);

                }else if (confirmed == true || finished == true){
                    Return_Layout();
                }else {
                    Intent intent = new Intent(Ins_Output_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                }
                break;

            case R.id.btn_confirm:
                Sum_Output("confirm");
                break;

            case R.id.btn_finish:
                Sum_Output("finish");
                break;

            case R.id.btn_confirmed:
                if (b_confirm == true) {
                    Block_button();
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                        Update_BD_Ins_wait();
                    } else {
                        Update_APP_Ins_wait();
                    }
                }
                break;

            case R.id.btn_finished:
                if (b_confirm == true) {
                    Block_button();
                    Check_output_finish();
                }
                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_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_confirmed.setEnabled(false);
        btn_confirmed.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_finished.setEnabled(false);
        btn_finished.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_confirmed.setEnabled(true);
        btn_confirmed.setBackgroundResource(R.drawable.button_backgroup_blue);
        btn_finished.setEnabled(true);
        btn_finished.setBackgroundResource(R.drawable.button_backgroup_green);
    }
    private void Cancel_LotOut() {//P3
        txt_leader_lotout.setText("");
        lot_out = false;
        layout_lotout.setVisibility(View.GONE);
        Unblock_button();
    }

    private void Update_Output() { //lot_out == true
            if (txt_leader_lotout.getText().toString().trim().equals("")) {
                Unblock_button();
                new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกนรหัสพนักงาน!")
                        .show();
            } else {
                layout_lotout.setVisibility(View.GONE);
                if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                    Update_BD_Ins_finish();
                } else {
                    Update_APP_Ins_finish();
                }
            }
    }

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

        if (i_output <= 0){
            if (txt_user.getText().toString().trim().equals("")){
                Unblock_button();
                new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกนรหัสพนักงาน!")
                        .show();
            }else {
                lot_out = true;
                layout_lotout.setVisibility(View.VISIBLE);
            }
        }else {
            if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                Update_BD_Ins_finish();
            }else{
                Update_APP_Ins_finish();
            }
        }
    }


    private void Return_Layout() {
        Log.d(getString(R.string.tag), "Set_Layout_back :" );
        confirmed = false; finished = false;

        if (list_ng_his.size() > 0){
            Log.d(getString(R.string.tag), "layout_ng_his : " + str_process+" | "+ str_process+ " | "+str_check_time);
            layout_ng_his.setVisibility(View.VISIBLE);
        }

        if (list_random_ng.size() > 0){
            layout_ng_random.setVisibility(View.VISIBLE);
        }

        layout_scan_ng.setVisibility(View.VISIBLE);
        layout_btn_choose.setVisibility(View.VISIBLE);
        layout_btn_confirmed.setVisibility(View.GONE);
        layout_btn_finished.setVisibility(View.GONE);
        layout_sum.setVisibility(View.GONE);

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

    private void Set_Layout_view(String click) {

            if (click.trim().equals("finish")) {
                layout_btn_finished.setVisibility(View.VISIBLE);
                layout_btn_confirmed.setVisibility(View.GONE);
            } else {
                layout_btn_confirmed.setVisibility(View.VISIBLE);
                layout_btn_finished.setVisibility(View.GONE);
            }
            layout_scan_ng.setVisibility(View.GONE);
            layout_btn_choose.setVisibility(View.GONE);
            layout_ng_his.setVisibility(View.GONE);//ng history not show
            layout_ng_random.setVisibility(View.GONE);
            layout_sum.setVisibility(View.VISIBLE);

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

    }

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

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

    @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);
            String str_scan = data.trim();
            str_ng_code = "";
            Log.d(getString(R.string.tag), "scan data : " + data.substring(0,2));

            if (lot_out == true) {
                if (data.trim().length() == 6) {
                    Check_User(data.trim());

                } else {
                    new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR code ไม่ถูกต้อง!")
                            .show();
                }
            }else if (confirmed == true && finished == true) {
                return;

            }else {
                //scan NG
                if (str_scan.substring(0, 2).equals("NG")) {
                    if (edt_qty_ng.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(Ins_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.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_process.setVisibility(View.GONE);
                                    layout_nurse_call.setVisibility(View.VISIBLE);
                                } else {
                                    Add_map_ng_scan(str_ng_code, "");
                                }
                            }
                        } else {
                            txt_scan.setText("");
                            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ NG code!")
                                    .show();
                        }
                    }

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

                } else if (str_scan.length() == 4) {//mag_no
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                        Log.d(getString(R.string.tag), "scan machine: " + str_machine);
                        if (str_machine.trim().equals("")) {//check by human
                            if (str_scan.trim().equals(str_mag_no)) {
                                txt_mag_no.setText(str_scan);

                            } else {
                                new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("..........Mag No. ไม่ตรงกัน  !.......... "+" Mag No. = "+str_mag_no)
                                        .show();
                            }
                        }else{ //check by machine
                            txt_mag_no.setText(str_scan);
                        }
                    }else{
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("QR code ไม่ถูกต้อง!")
                                .show();
                    }
                } else {
                    new SweetAlertDialog(Ins_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 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(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!!")
                            .show();
                }
            }else {
                if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())
                        && Settings.getMap_user().get(data).getBonding_ins().trim().equals("1")) {
                    txt_user.setText(data);

                }else if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())
                        && Settings.getMap_user().get(data).getAppearance().trim().equals("1")) {
                    txt_user.setText(data);

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

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

    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+"|"+str_process);

        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()));
        Log.e(getString(R.string.tag), "map_ng_scan: " + map_ng_scan.size());

        if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())) {
            if (ng_code.trim().equals("NGAPP01")) {
                String str_qty_ng = edt_qty_ng.getText().toString().trim();
                int qty_ng = Integer.parseInt(str_qty_ng);

                Check_Code(qty_ng);
            }
        }

        Set_View_NG_Scan();
        txt_scan.setText("");
        edt_qty_ng.setText("");
        txt_leader.setText("");
    }

    private void Check_Code(int qty_ng) {
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            JSONObject json = new JSONObject();
            json.put("cmd", "check_ng");
            json.put("sch_id", str_sch_id);
            json.put("process", ProductionSchedule.PROCESS.BONDING_INS.toString());

            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 {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            bonding_ng = 0;
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                str_bonding_ng =  jArray.getJSONObject(i).getString("bonding_ng").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("bonding_ng").trim();
                            }
                            bonding_ng = Integer.parseInt(str_bonding_ng);
                        }

                        if (qty_ng != bonding_ng){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("BONDING_INS NG = "+bonding_ng)
                                .show();
                        }else {
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


    private void Sum_Output(String click) {
        if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString()) &&
           txt_mag_no.getText().toString().equals("")){
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน mag no.!")
                    .show();

        }else if (txt_user.getText().toString().equals("")) {
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else {
            Log.d(getString(R.string.tag), "Sum_Output : input" + input);
            //sum output
            sum_output = 0;
            sum_ngwb = 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 ng_code = lists.getNg_code();
                    String output_qty = lists.getNg_qty();
                    String calculate = lists.getCalculate();

                    int ng_qty;
                    ng_qty = Integer.parseInt(output_qty);
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())){
                        if (ng_code.trim().equals("NGDB17")){
                            sum_ng17 = (sum_ng17 + ng_qty);
                        }

                        if (ng_code.trim().equals("NGWB15")||ng_code.trim().equals("NGWB16")){
                            sum_ngwb = (sum_ngwb + ng_qty);
                        }
                    }

                    //sum ng : ststus = YES
                    if (calculate.trim().equalsIgnoreCase(ProductionSchedule.STATUS_CAL.YES.toString())) {
                        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);
                    }
                }//for
            }
            total = (input - sum_output);
            Log.d(getString(R.string.tag), "total :" + total + "=" + input + "-" + sum_output);
            Log.d(getString(R.string.tag), "output" + total);
            txt_total_output.setText(String.valueOf(total));

            Log.d(getString(R.string.tag), "sum_ng17 = " + sum_ng17);
            Log.d(getString(R.string.tag), "RC_NGDB17 = " + RC_NGDB17);
            Log.d(getString(R.string.tag), "sum_ngwb = " + sum_ngwb);
            Log.d(getString(R.string.tag), "RC_NGWB = " + RC_NGWB);
            Log.d(getString(R.string.tag), "SUM_RC_NG = " + SUM_RC_NG);
            Log.d(getString(R.string.tag), "sum_ng = " + sum_output);
            Log.d(getString(R.string.tag), "total = " + total);


            if (sum_ng17 < RC_NGDB17){
                Alert_qty_ng = true;
                Alert_NG("จำนวน NGDB17 น้อยกว่าที่พบในการสุ่มตรวจ", click);

            }else if (sum_ngwb < RC_NGWB){
                Alert_qty_ng = true;
                Alert_NG("จำนวน NGWB15 + NGWB16 น้อยกว่าที่พบในการสุ่มตรวจ", click);

            }else if (sum_output < SUM_RC_NG ){
                Alert_qty_ng = true;
                Alert_NG("จำนวนรวม NG น้อยกว่าที่พบในการสุ่มตรวจ", click);

            }else {
                if (click.trim().equals("confirm")) {
                    if (total <= 0) {
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("Output = 0  กรุณากดปุ่ม finish")
                                .show();
                    } else {
                        confirmed = true;
                        Set_Layout_view("confirm");
                    }

                } else if (click.trim().equals("finish")) {
                    finished = true;
                    Set_Layout_view("finish");
                    Alert_plan();
                }
            }
        }
    }

    private void Alert_NG(String msg, String click) {
        SweetAlertDialog dialog = new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("แจ้งเตือน")
                .setContentText(msg)
                .setConfirmText("รับทราบ")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        if (edt_remark.getText().toString().trim().equals("")){
                            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณาใส่ Remark!")
                                    .show();

                        }else {
                            if (click.trim().equals("confirm")) {
                                if (total <= 0) {
                                    new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("Output = 0  กรุณากดปุ่ม finish")
                                            .show();
                                } else {
                                    confirmed = true;
                                    Set_Layout_view("confirm");
                                }

                            } else if (click.trim().equals("finish")) {
                                finished = true;
                                Set_Layout_view("finish");
                                Alert_plan();
                            }
                        }
                    }
                });
        dialog.show();
    }

    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, Ins_Output_Activity.this,str_process);
        view_ng.setAdapter(ng_adapter);
        Log.d(getString(R.string.tag), "setAdapter" + map_ng_scan.size());
    }

    private void Cancel_NurseCall() {
        nurse_call = false;
        layout_process.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);
        txt_scan.setText("");
        txt_leader.setText("");
    }

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

        str_leader = txt_leader.getText().toString().trim();
        str_ng_code = txt_scan.getText().toString().trim();
        if (str_leader.equals("")){
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสleader!")
                    .show();
        }else {
            Add_map_ng_scan(str_ng_code, str_leader);
        }
    }


    private void Update_APP_Ins_wait() {
        if (txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else{
            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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_app_ins");
                json.put("status", ProductionSchedule.STATUS.APPEARANCE_WAIT);
                json.put("process", ProductionSchedule.PROCESS.APPEARANCE);
                json.put("check_time", update_check_time);
                json.put("output", txt_total_output.getText().toString().trim());
                json.put("act_dt", "");
                json.put("sch_id", str_sch_id);

                if (lot_out == false){//ถ้าไม่ใช่ lotout ให้ update last_output_qty
                    json.put("last_output", txt_total_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) {
                                Insert_EventINS();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void Update_APP_Ins_finish() {
        Log.d(getString(R.string.tag), "Update_BD_Ins_finish : " + check_time);

        if (txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else {
            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);
            //update
            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_app_ins");
                json.put("status", ProductionSchedule.STATUS.APPEARANCE_FINISHED);
                json.put("process", ProductionSchedule.PROCESS.APPEARANCE);
                json.put("check_time", check_time);
                json.put("output", txt_total_output.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_total_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) {
                                Insert_EventINS();

                            } else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Ins_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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void Update_BD_Ins_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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_bd_ins");
                json.put("status", ProductionSchedule.STATUS.BONDING_INS_WAIT);
                json.put("process", ProductionSchedule.PROCESS.BONDING_INS);
                json.put("check_time", update_check_time);
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("output", txt_total_output.getText().toString().trim());
                json.put("act_dt", "");
                json.put("sch_id", str_sch_id);
                if (lot_out == false){//ถ้าไม่ใช่ lotout ให้ update last_output_qty
                    json.put("last_output", txt_total_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) {
                                Insert_EventINS();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Update_BD_Ins_finish() {
        Log.d(getString(R.string.tag), "Update_BD_Ins_finish : " + check_time);

        if (txt_mag_no.getText().toString().equals("") || txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information!")
                    .show();
        }else {
            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);
            //update
            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_bd_ins");
                json.put("status", ProductionSchedule.STATUS.BONDING_INS_FINISHED);
                json.put("process", ProductionSchedule.PROCESS.BONDING_INS);
                json.put("check_time", check_time);
                json.put("output", txt_total_output.getText().toString().trim());
                json.put("mag_no", txt_mag_no.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_total_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) {
                                Insert_EventINS();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }


    private void Insert_EventINS() {
        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_event_ins");
            json.put("sch_id", str_sch_id);
            json.put("process", str_process);
            json.put("output", txt_total_output.getText().toString().trim());
            json.put("remark",encode);
            json.put("check_times", str_check_time);
            json.put("end_user_id", txt_user.getText().toString().trim());
            json.put("end_dt", dt_to_server);

            if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())){
                json.put("mag_no_output", txt_mag_no.getText().toString().trim());
            }else{
                json.put("mag_no_output", "");
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/event_ins.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) {
                                if (lot_out == true){
                                    Update_LotOut();
                                }else{
                                    Toast.makeText(Ins_Output_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            }else{
                                Insert_NGList();
                            }
                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert EvenINS")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_NGList() {
        Block_button();
        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("check_times", str_check_time);
                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(Ins_Output_Activity.this, "บันทึกข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Ins_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(Ins_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(Ins_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(Ins_Output_Activity.this, "บันทึกข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Get_List_Output(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(Ins_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("NG code not found!")
                                    .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(Ins_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(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("process", str_process);
            json.put("sch_id", str_sch_id);
            json.put("check_times", str_check_time);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/event_ins.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){
                            for (int i = 0; i < jArray.length(); i++) {
                                str_machine = jArray.getJSONObject(i).getString("machine_code").trim()== "null" ? "" : jArray.getJSONObject(i).getString("machine_code").trim();
                            }
                        }else{
                            str_machine = "";
                        }
                        Log.d(getString(R.string.tag), "str_machine: " + str_machine);
                        layout_alert.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

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

            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 {
                        JSONArray jArray = new JSONArray(response);

                        if (jArray.length() > 0){
                            layout_ng_his.setVisibility(View.VISIBLE);

                            for (int i = 0; i < jArray.length(); i++) {
                                list_ng_his.add(new NG_Lists(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ng_code").trim(),
                                        jArray.getJSONObject(i).getString("ng_name").trim() == "null" ? jArray.getJSONObject(i).getString("ng_code").trim() : jArray.getJSONObject(i).getString("ng_name").trim(),
                                        jArray.getJSONObject(i).getString("qty").trim(),//sum qty
                                        jArray.getJSONObject(i).getString("process").trim(),
                                        "",
                                        ""));
                            }
                            Log.d(getString(R.string.tag), String.valueOf(list_ng_his.size()));
                            ng_adapter = new NG_Adapter(list_ng_his, Ins_Output_Activity.this, str_process);
                            view_ng_his.setAdapter(ng_adapter);
                        }
                        layout_alert.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Get_RandomCheck_NG() {
        list_random_ng.clear();
       sum_process1 = 0; sum_process2 = 0;  RC_NGWB = 0; RC_NGDB17 = 0; SUM_RC_NG = 0;
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/random_check_ng.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){
                            for (int i = 0; i < jArray.length(); i++) {
                                String ng_code = jArray.getJSONObject(i).getString("ng_code").trim();

                                if (ng_code.trim().equals("NGDB17")){
                                    int qty_ngdb17 =   jArray.getJSONObject(i).getInt("qty");
                                    RC_NGDB17 = (RC_NGDB17 + qty_ngdb17);
                                }
                                Log.d(getString(R.string.tag), "RC_NGDB17: " + RC_NGDB17);

                                if (ng_code.trim().equals("NGWB15") || ng_code.trim().equals("NGWB16")){
                                    int qty_ngwb =   jArray.getJSONObject(i).getInt("qty");
                                    RC_NGWB = (RC_NGWB + qty_ngwb);
                                }
                                Log.d(getString(R.string.tag), "RC_NGWB: " + RC_NGWB);

                                String process = jArray.getJSONObject(i).getString("process").trim();
                                int qty =   jArray.getJSONObject(i).getInt("qty");

                                if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                                    if (process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                                        sum_process1 = (sum_process1 + qty);
                                    } else if (process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())) {
                                        sum_process2 = (sum_process2 + qty);
                                    }
                                }else {//App
                                    if (process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())) {
                                        sum_process1 = (sum_process1 + qty);
                                    } else if (process.trim().equals(ProductionSchedule.PROCESS.DICER.toString())) {
                                        sum_process2 = (sum_process2 + qty);
                                    }
                                }

                                list_random_ng.add(new RandomCheck_NG_Lists(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ng_code").trim(),
                                        jArray.getJSONObject(i).getString("ng_name").trim() == "null" ? jArray.getJSONObject(i).getString("ng_code").trim() : jArray.getJSONObject(i).getString("ng_name").trim(),
                                        String.valueOf(qty),//sum qty
                                        process,
                                        ""));


                            }//for
                            Log.d(getString(R.string.tag), String.valueOf(list_random_ng.size()));

                            Log.d(getString(R.string.tag), "total RC_NGDB17: " + RC_NGDB17);
                            Log.d(getString(R.string.tag), "RC_NGWB: " + RC_NGWB);
                            SUM_RC_NG = (sum_process1+sum_process2);
                            random_ng_adapter = new RandomCheckNG_Adapter(list_random_ng, Ins_Output_Activity.this);
                            view_ng_random.setAdapter(random_ng_adapter);

                            if (list_random_ng.size() > 0){
                                layout_ng_random.setVisibility(View.VISIBLE);
                                txt_qty_ng_process1.setText(String.valueOf(sum_process1));
                                txt_qty_ng_process2.setText(String.valueOf(sum_process2));
                            }else {
                                layout_ng_random.setVisibility(View.GONE);
                            }
                            layout_alert.setVisibility(View.GONE);
                        }else {
                            layout_alert.setVisibility(View.GONE);
                            RC_NGWB = 0;
                            RC_NGDB17 = 0;
                        }

                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Ins_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .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:
                    Log.d(getString(R.string.tag), "imb_back :" + confirmed+"/"+finished+"/"+Overdue);
                    if (Overdue == true && finished == true){
                        Return_Layout();
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_process.setVisibility(View.VISIBLE);

                    }else if (confirmed == true || finished == true){
                        Return_Layout();

                    }else {
                        Intent intent = new Intent(Ins_Output_Activity.this, Search_ProcessSheet_Activity.class);
                        startActivity(intent);
                        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 (Overdue == true){
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_process.setVisibility(View.VISIBLE);

                    }else if (confirmed == true){
                        if (b_confirm == true) {
                            Block_button();
                            if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                                Update_BD_Ins_wait();
                            } else {
                                Update_APP_Ins_wait();
                            }
                        }

                    }else if (finished == true){
                        //update finish ins
                        if (b_confirm == true) {
                            Block_button();
                            Check_output_finish();
                        }

                    }else {
                        Sum_Output("finish");
                    }
                    break;

                case P3:
                    if (nurse_call == true){
                        Cancel_NurseCall();

                    }else  if (lot_out == true){
                        Cancel_LotOut();

                    } else {
                        Sum_Output("confirm");
                    }
                    break;
            }
        }

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