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.Oven_Adapter;
import com.tomas.pcs_asi.ListData.Get_OutputCode;
import com.tomas.pcs_asi.ListData.Item_Dicer;
import com.tomas.pcs_asi.ListData.Item_Oven;
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 Dicer_Output_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_scan_process_sheet, txt_scan_ng, txt_input, txt_output, txt_message, txt_leader,txt_leader_lotout;
    EditText edt_qty, edt_remark;
    RecyclerView view_process_sheet, view_ng;
    LinearLayout layout_scan_ng, layout_sum, layout_btn_finish, layout_btn_confirm, layout_dicer, layout_remark;
    ConstraintLayout layout_alert, layout_nurse_call, layout_lotout;
    Calendar calendar;
    SimpleDateFormat fm_dt_server;
    String str_process, str_ics, str_job_order, str_lot_no, str_dicer_id, str_role, scan_ics, scan_job, scan_lot, SCH_ID, dt_to_server, DefectName;
    List<Item_Oven> list_dicer;
    List<NG_Lists>list_ng;
    Map<String, Item_Dicer> map_item_dicer;
    Map<String, NG_Lists>map_ng_scan;
    Map<String, Get_OutputCode> map_code_ng;
    Oven_Adapter oven_adapter;
    boolean nurse_call, confirmed, lot_out, b_confirm;
    int scan = 0,output, total, input, sum_output, sum_input, balance;
    NG_Adapter ng_adapter;
    Button btn_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dicer_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;
        nurse_call = false;
        confirmed = false;
        lot_out = false;
        scan = 0;
        SCH_ID = "";

        list_ng = new ArrayList<NG_Lists>();
        list_dicer = new ArrayList<Item_Oven>();
        map_item_dicer = new LinkedHashMap<>();
        map_ng_scan = new LinkedHashMap<>();
        map_code_ng = new LinkedHashMap<>();

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

        layout_dicer = (LinearLayout)findViewById(R.id.layout_dicer);
        layout_scan_ng = (LinearLayout) findViewById(R.id.layout_scan_ng);
        layout_sum = (LinearLayout) findViewById(R.id.layout_sum);
        layout_btn_finish = (LinearLayout) findViewById(R.id.layout_btn_finish);
        layout_btn_confirm = (LinearLayout) findViewById(R.id.layout_btn_confirm);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_nurse_call = (ConstraintLayout)findViewById(R.id.layout_nurse_call);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);

        btn_confirm = (Button)findViewById(R.id.btn_confirm);
        txt_user = (TextView)findViewById(R.id.txt_user);
        txt_scan_process_sheet = (TextView)findViewById(R.id.txt_scan_ps);
        txt_scan_ng = (TextView)findViewById(R.id.txt_scan_ng);
        txt_input = (TextView)findViewById(R.id.txt_total_input);
        txt_output = (TextView)findViewById(R.id.txt_total_output);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_leader = (TextView)findViewById(R.id.txt_leader);

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

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

        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_ics = Settings.getICS();
        str_job_order  = Settings.getJobOrder();
        str_lot_no = Settings.getLotNo();
        str_dicer_id = Settings.getDicerId();
        Log.d(getString(R.string.tag), "Dicer ID : " + str_dicer_id);

        Get_List_Output(str_process);
        Search_ProcessSheet_DICER();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imb_back:
                if (confirmed == true){
                    Return_Layout();
                }else {
                    Intent intent = new Intent(Dicer_Output_Activity.this, Dicer_Activity.class);
                    startActivity(intent);
                    finish();
                }
                break;

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

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

            case R.id.btn_confirm:
                if (b_confirm == true) {
                    Check_Lotout();
                }
                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) {
                    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("")) {
            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        } else {
            layout_lotout.setVisibility(View.GONE);
            Update_Dicer_finish();
        }
    }

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

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

                }else{
                    new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR code ไม่ถูกต้อง!")
                            .show();
                }
            }else if (confirmed == true){
                return;
            }else {
                if (scan == 0) {//scan ics
                    if (str_scan.length() == 10) {
                        SCH_ID = "";
                        scan = 1;
                        scan_ics = data.trim();
                        scan_job = "";
                        scan_lot = "";
                        txt_scan_ng.setText("");
                        edt_qty.setText("");
                        txt_scan_process_sheet.setText(scan_ics);

                    } else if (str_scan.substring(0, 2).equals("NG")) {
                        if (SCH_ID.trim().equals("") || txt_scan_process_sheet.getText().toString().trim().equals("")) {
                            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณา process sheet")
                                    .show();
                        } else {
                            if (edt_qty.getText().toString().trim().equals("")) {
                                new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("กรุณาใส่จำนวน NG")
                                        .show();
                            } else {
                                if (map_code_ng.containsKey(str_scan)) {
                                    if (map_ng_scan.containsKey(SCH_ID + str_scan)) {//ng code duplicate -->del
                                        new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("กรุณากดปุ่ม CLEAR[2]")
                                                .show();

                                    } else {//add map ng_list
                                        txt_scan_ng.setText(str_scan);
                                        Get_OutputCode outputCode = map_code_ng.get(str_scan);
                                        String s_nurse_call = outputCode.getNurse_call();

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

                                        } else {
                                            Add_map_ng_scan(str_scan, "");
                                        }
                                    }
                                } else {
                                    txt_scan_ng.setText("");
                                    new SweetAlertDialog(Dicer_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(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("QR code ไม่ถูกต้อง!")
                                .show();
                    }
                } else if (scan == 1) {//scan job order
                    if (!data.trim().equals("")) {
                        SCH_ID = "";
                        scan = 2;
                        scan_job = data.trim();
                    }
                    txt_scan_process_sheet.setText(scan_ics + "  " + scan_job);

                } else if (scan == 2) {//scan job order
                    if (!data.trim().equals("")) {
                        SCH_ID = "";
                        scan = 0;
                        str_lot_no = data.trim();
                        txt_scan_process_sheet.setText(scan_ics + "  " + scan_job + "  " + str_lot_no);

                        String sch_id = scan_ics + scan_job + str_lot_no;
                        if (map_item_dicer.containsKey(sch_id)) {
                            SCH_ID = sch_id;

                        } else {
                            txt_scan_process_sheet.setText("");
                            SCH_ID = "";
                            scan = 0;
                            scan_ics = "";
                            scan_job = "";
                            scan_lot = "";
                            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Process sheet!")
                                    .show();
                        }
                    }
                } else {
                    new SweetAlertDialog(Dicer_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 Update_Dicer_finish() {
            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_dicer_finish");
                JSONArray jsonArray = new JSONArray();

                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                for (String key : map_item_dicer.keySet()) {
                    Item_Dicer item = map_item_dicer.get(key);
                    int output = Integer.parseInt(item.getOutput());
                    json.put("output", output);

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("sch_id", item.getSch_id());
                    jsonParams.put("output", item.getOutput());
                    jsonParams.put("remark", encode);
                    jsonParams.put("user_id", txt_user.getText().toString().trim());
                    jsonParams.put("act_dt", dt_to_server);
                    if (output > 0){
                        jsonParams.put("last_output", item.getOutput());
                    }

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
                json.put("dicer_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);
                            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();
                                    layout_alert.setVisibility(View.GONE);
                                }else {
                                    layout_alert.setVisibility(View.GONE);
                                    Toast.makeText(Dicer_Output_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Dicer_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(Dicer_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(Dicer_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("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 {
                                Log.d(getString(R.string.tag), "Insert_NGList: " + "finish");
                                Toast.makeText(Dicer_Output_Activity.this, "บันทึกข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert NGFactorList")
                                    .show();
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_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(Dicer_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();

                for (String key : map_item_dicer.keySet()) {
                    Item_Dicer item = map_item_dicer.get(key);
                    int output = Integer.parseInt(item.getOutput());

                    if (output <= 0){ //put json ???????? output <=0
                        Map<String, String> jsonParams = new HashMap<>();
                        jsonParams.put("sch_id", item.getSch_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(Dicer_Output_Activity.this, "บันทึกข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                Unblock_button();
                                new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                            layout_alert.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Dicer_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(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

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

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

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

    private void Return_Layout() {
        lot_out = false; //??????????????????????????????
        confirmed = false;
        layout_scan_ng.setVisibility(View.VISIBLE);
        layout_btn_finish.setVisibility(View.VISIBLE);
        layout_btn_confirm.setVisibility(View.GONE);
        layout_sum.setVisibility(View.GONE);
        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
        layout_remark.setBackgroundResource(R.drawable.button_backgroup_menu);
        edt_remark.setEnabled(true);
    }

    private void Set_Layout_view() {
        layout_scan_ng.setVisibility(View.GONE);
        layout_btn_finish.setVisibility(View.GONE);
        layout_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 ????????????????????? ???????????????? ng ???
        sum_output = 0; total = 0; sum_input = 0; balance = 0;
        int ng_qty, ng_qty_scan, int_ng;
        if(map_ng_scan.size() == 0){//????? NG
            sum_output = 0;
        }else {
            for (String key : map_ng_scan.keySet()) {//for insert ng
                Log.d(getString(R.string.tag), "for insert ng");
                NG_Lists lists = map_ng_scan.get(key);
                String output_qty = lists.getNg_qty();
                String sch_id = lists.getSch_id();

                Log.d(getString(R.string.tag), "sch_id" + sch_id);
                if (map_item_dicer.containsKey(sch_id)) {
                    Item_Dicer item_dicer = map_item_dicer.get(sch_id);
                    ng_qty = Integer.parseInt(item_dicer.getNg_qty());
                    ng_qty_scan = Integer.parseInt(output_qty);
                    int_ng = (ng_qty + ng_qty_scan);

                    Log.d(getString(R.string.tag), "map_item_dicer" + int_ng +"="+ng_qty +"+"+ng_qty_scan);

                    item_dicer.setNg_qty(String.valueOf(int_ng));
                    map_item_dicer.put(sch_id, item_dicer);

                }
            }
        }

        for (String key : map_item_dicer.keySet()) {//for sum ng
            Item_Dicer lists = map_item_dicer.get(key);
            String sch_id = lists.getSch_id();
            String output_qty = lists.getNg_qty();
            Log.d(getString(R.string.tag), "sch_id" + sch_id);

            output = Integer.parseInt(output_qty);
            Log.d(getString(R.string.tag), "output = " + output);
            sum_output = (sum_output + output);
            Log.d(getString(R.string.tag), "sum_output = " + sum_output);

            String str_input  = lists.getInput();
            input = Integer.parseInt(str_input);
            Log.d(getString(R.string.tag), "input = " + input);
            sum_input = (sum_input + input);
            Log.d(getString(R.string.tag), "sum_output = " + sum_input);

            balance = (input - output);
            Log.d(getString(R.string.tag), "balance  " + balance+"="+input+"-"+output);
            lists.setOutput(String.valueOf(balance));
            map_item_dicer.put(sch_id, lists);
        }

        total = (sum_input - sum_output);
        Log.d(getString(R.string.tag), "total :" + total+"="+input+"-"+sum_output);
        txt_output.setText(String.valueOf(total));
        txt_input.setText(String.valueOf(sum_input));


    }

    private void Check_Lotout() {

        lot_out = false;
        int count = 0;
        for (String key : map_item_dicer.keySet()) {
            Item_Dicer lists = map_item_dicer.get(key);
            int output = Integer.parseInt(lists.getOutput());
            Log.d(getString(R.string.tag), "Check_Lotout: " + String.valueOf(output));
//
            if (output <= 0) {
                lot_out = true;
                count = count + 1;
                Log.d(getString(R.string.tag), "count lotout: " + count);
            }
        }

        if (lot_out == true){
            layout_lotout.setVisibility(View.VISIBLE);
        }else {
            Update_Dicer_finish();
        }
    }

    private void Clear_NG() {
        map_ng_scan.clear();
        for (String key : map_item_dicer.keySet()) {
            Item_Dicer lists = map_item_dicer.get(key);
            String sch_id = lists.getSch_id();
            int input = Integer.parseInt(lists.getInput());
            Log.d(getString(R.string.tag), "Clear_NG: " + String.valueOf(input));

            lists.setOutput(String.valueOf(input));
            lists.setNg_qty("0");
            map_item_dicer.put(sch_id, lists);
        }

        Set_View_NG_Scan();
    }
    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(SCH_ID+ng_code, new NG_Lists(
                SCH_ID,
                outputCode.getCode(),
                outputCode.getName(),
                edt_qty.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.setText("");
        txt_leader.setText("");
    }

    private void Set_View_NG_Scan() {
        Log.d(getString(R.string.tag), "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, Dicer_Output_Activity.this,str_process);
        view_ng.setAdapter(ng_adapter);
    }

    private void Set_view_dicer() {
        //set view
        list_dicer.clear();
        for (String key : map_item_dicer.keySet()) {
            Item_Dicer item = map_item_dicer.get(key);
            list_dicer.add(new Item_Oven(
                    item.getSch_id(),
                    item.getIcs_code(),
                    item.getJob_order(),
                    item.getLot_no(),
                    item.getOutput()));//??? output ??? magno ????? dicer ??????? output ???????????? ???output <=0
        }
        Log.d(getString(R.string.tag), "list_dicer: " + String.valueOf(list_dicer.size()));
        oven_adapter = new Oven_Adapter(list_dicer, Dicer_Output_Activity.this,str_process);
        view_process_sheet.setAdapter(oven_adapter);
    }

    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(Dicer_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();
                                    DefectName =  URLDecoder.decode(DefectName, "UTF-8");
                                    Log.d(getString(R.string.tag), "DefectName_decode: " + DefectName);

                                }catch (Exception e){
                                    new SweetAlertDialog(Dicer_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(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_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(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!!")
                            .show();
                }
            }else {
                if (Settings.getMap_user().get(data).getDicer().trim().equals("1")){
                    txt_user.setText(data);

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

//    private void Check_User(String user_id) {
//        try {
//            layout_alert.setVisibility(View.VISIBLE);
//            txt_message.setText("Please wait, searching data...");
//
//            JSONObject json = new JSONObject();
//            json.put("cmd", "search");
//            json.put("user_id", user_id);
//
//            new AsyncHttpClient(getApplicationContext(),
//                    Settings.getMgmtList().get("web_api")+ "/users.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(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("User ID not found!")
//                                    .show();
//                        }else {
//                            if (nurse_call == true || lot_out == true){//scan leader
//                                for (int i = 0; i < jArray.length(); i++) {
//                                    str_role = jArray.getJSONObject(i).getString("Role").trim();
//                                }
//                                if (str_role.trim().equals("LEADER")){
//                                    if (lot_out == true){
//                                        txt_leader_lotout.setText(user_id);
//                                    }else {
//                                        txt_leader.setText(user_id);
//                                    }
//                                    layout_alert.setVisibility(View.GONE);
//                                }else {
//                                    layout_alert.setVisibility(View.GONE);
//                                    new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                            .setTitleText("WARNING")
//                                            .setContentText("User isn't leader!")
//                                            .show();
//                                }
//                            }else {
//                                txt_user.setText(user_id);
//                                layout_alert.setVisibility(View.GONE);
//                            }
//                        }
//                    }catch (JSONException e) {
//                        layout_alert.setVisibility(View.GONE);
//                        new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText("ERROR")
//                                .setContentText(e.getMessage())
//                                .show();
//                    }
//                }
//            }.execute();
//        }catch (JSONException e) {
//            layout_alert.setVisibility(View.GONE);
//            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                    .setTitleText("ERROR")
//                    .setContentText(e.getMessage())
//                    .show();
//        }
//    }

    private void Search_ProcessSheet_DICER() {
        list_dicer.clear();
        map_item_dicer.clear();

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search_dicer");
            json.put("dicer_id", str_dicer_id);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/production_plan.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Dicer ID : "+str_dicer_id+" not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_item_dicer.put(jArray.getJSONObject(i).getString("sch_id").trim(), new Item_Dicer(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        jArray.getJSONObject(i).getString("job_order").trim(),
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                        jArray.getJSONObject(i).getString("mold_output").trim(),//input
                                        jArray.getJSONObject(i).getString("mold_output").trim(),//output
//                                        "0",
                                        "0"));//ng
                                Log.d(getString(R.string.tag), "map_item_dicer: " + String.valueOf(map_item_dicer.size()));
                            }
                            Set_view_dicer();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_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:
                    if (confirmed == true){
                        Return_Layout();
                    }else {
                        Intent intent = new Intent(Dicer_Output_Activity.this, Dicer_Activity.class);
                        startActivity(intent);
                        finish();
                    }
                    break;

                case P2:
                     if (nurse_call == true){
                        OK_NurseCall();

                    }else if(lot_out == true){
                         if (b_confirm == true) {
                             Update_Output();
                         }

                    }else if (confirmed == true) {
                         if (b_confirm == true) {
                             Check_Lotout();
                         }

                    }else{
                         if (txt_user.getText().toString().trim().equals("")){
                             new SweetAlertDialog(Dicer_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                     .setTitleText("แจ้งเตือน")
                                     .setContentText("กรุณาสแกนรหัสพนักงาน!")
                                     .show();
                         }else {
                             confirmed = true;
                             Set_Layout_view();
                         }
                    }
                    break;

                case P3:
                    if (lot_out == true){
                        Cancel_LotOut();

                    }else if (nurse_call == true){
                        Cancel_NurseCall();

                    }else {
                        Clear_NG();
                    }
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}