package com.tomas.pcs_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.BOM_Adapter;
import com.tomas.pcs_asi.Adapter.Tools_Adapter;
import com.tomas.pcs_asi.ListData.Get_Item_BOM;
import com.tomas.pcs_asi.ListData.Get_Item_Tools;
import com.tomas.pcs_asi.ListData.Get_Machine;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.ConvertStringToCalendar;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.AsyncHttpClientMultipart;
import com.tomas.pcs_asi.lib.common.MyAlertDialog;
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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Process_Activity extends Scanner implements View.OnClickListener {
    BOM_Adapter bom_adapter;
    Tools_Adapter tools_adapter;
    EditText edt_rank, edt_remark_tool;
    TextView txt_header, txt_ics_product, txt_job_order, txt_lot_no, txt_user, txt_ics_part, txt_lot_part, txt_tool, txt_machine,
            txt_overdue_title, txt_overdue_dt, txt_message, txt_mag_no, txt_disbursement, txt_material_exp,
            txt_start_date, txt_service_life;
    String str_process, str_status, str_ics_product, str_job, str_lot, str_overdue_dt, str_overdue_title, dt_to_server, dt_to_photo,
            str_mc_type, str_sch_id, str_user_id, str_machine, str_item_type, str_mag_no = "", str_input, status_material, status_tool, str_eqm,
            str_eqm_exp, str_format_dt = "dd/MM/yyyy HH:mm", str_check_time;
    ConstraintLayout layout_alert_plan, layout_process, layout_alert_save, layout_btn_start, layout_btn_working, layout_btn_edit;
    LinearLayout layout_mag_no, layout_scan_tool, layout_scan_material, layout_material, layout_remark, layout_rank;

    RecyclerView view_bom, view_tools;
    Calendar calendar,  end_calendar, start_calendar;
    boolean scan_part, mode_edit, Overdue, scanner, b_confirm;
    SimpleDateFormat fm_dt_server, fm_dt_photo, dt_format, dt_format_qr;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    Map<String, Get_Item_BOM> map_bom;
    Map<String, Get_Item_BOM> map_material_scan;
    Map<String, Get_Item_Tools> map_tools;
    Map<String, Get_Machine> map_machine;
    Map<String, Get_Item_Tools> map_tools_scan;
    List<Get_Item_BOM>list_material_his;
    List<Get_Item_Tools>list_tool_his;
    List<Get_Item_Tools>list_tools;
    List<Get_Item_BOM>list_bom;
    Button btn_start, btn_save_edit;
    String str_date, str_time, str_frequency, end_dt, start_dt, str_shift;
    int diebond_process = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        fm_dt_photo = new SimpleDateFormat("yyyyMMdd_HHmmss");
        dt_format = new SimpleDateFormat("yyyy-MM-dd");
        dt_format_qr = new SimpleDateFormat("dd/MM/yyyy HH:mm");

        scan_part = false;
        mode_edit = false;
        Overdue = false;
        scanner = true;
        b_confirm = true;

        map_bom = new LinkedHashMap<>();
        map_material_scan = new LinkedHashMap<>();
        map_tools = new LinkedHashMap<>();
        map_tools_scan = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();

        list_tools = new ArrayList<Get_Item_Tools>();
        list_bom = new ArrayList<Get_Item_BOM>();
        list_material_his = new ArrayList<Get_Item_BOM>();
        list_tool_his = new ArrayList<Get_Item_Tools>();

        layout_process = (ConstraintLayout)findViewById(R.id.layout_process);
        layout_alert_plan = (ConstraintLayout)findViewById(R.id.layout_alert_plan);
        layout_alert_save = (ConstraintLayout)findViewById(R.id.layout_alert_save);
        layout_btn_start = (ConstraintLayout)findViewById(R.id.layout_btn_start);
        layout_btn_working = (ConstraintLayout)findViewById(R.id.layout_btn_working);
        layout_btn_edit = (ConstraintLayout)findViewById(R.id.layout_btn_edit);
        layout_mag_no = (LinearLayout)findViewById(R.id.layout_mag_no);
        layout_scan_tool = (LinearLayout)findViewById(R.id.layout_scan_tool);
        layout_scan_material = (LinearLayout)findViewById(R.id.layout_scan_material);
        layout_material = (LinearLayout)findViewById(R.id.layout_material);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);
        layout_rank = (LinearLayout)findViewById(R.id.layout_rank);

        btn_start = (Button)findViewById(R.id.btn_start);
        btn_save_edit = (Button)findViewById(R.id.btn_save_edit);

        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_ics_product = (TextView) findViewById(R.id.txt_ics_product);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_ics_part = (TextView) findViewById(R.id.txt_ics_part);
        txt_lot_part = (TextView) findViewById(R.id.txt_lot_part);
        txt_tool = (TextView) findViewById(R.id.txt_tool);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_overdue_title = (TextView)findViewById(R.id.txt_overdue_title);
        txt_overdue_dt= (TextView)findViewById(R.id.txt_overdue_dt);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_mag_no = (TextView) findViewById(R.id.txt_mag_no);
        txt_disbursement = (TextView) findViewById(R.id.txt_disbursement);
        txt_material_exp = (TextView)findViewById(R.id.txt_material_exp);
        txt_start_date = (TextView)findViewById(R.id.txt_start_date);
        txt_service_life = (TextView)findViewById(R.id.txt_service_life);
        edt_rank = (EditText)findViewById(R.id.edt_rank);
        edt_remark_tool = (EditText)findViewById(R.id.edt_remark_tool);

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

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

        str_process = Settings.getPROCESS();
        str_status  = Settings.getSTATUS();
        str_overdue_dt  = Settings.getOverdueDt();
        str_overdue_title = Settings.getOverdueTitle();
        str_sch_id = Settings.getSchId();
        str_ics_product = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_item_type = Settings.getItemType();
        str_mc_type = Settings.getMcType();
        str_machine = Settings.getMACHINE();
        str_user_id = Settings.getUserId();
        str_mag_no = Settings.getMagNo();
        str_input = Settings.getQtyInput();


        Log.d(getString(R.string.tag), "Process Activity : " + str_process+" | "+ str_status+
                " | "+str_overdue_dt+" | "+str_mag_no+"|"+str_item_type);



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

        //adjust layout
        if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())){
            str_check_time = Settings.getCheckTime();
            diebond_process = Settings.getDbProcessTimes();
            txt_header.setText(str_process+" "+str_check_time+"#");
            layout_material.setVisibility(View.VISIBLE);
            layout_mag_no.setVisibility(View.GONE);

            Log.d(getString(R.string.tag), "DB Times : " + str_check_time+"/"+diebond_process);

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())){
            layout_material.setVisibility(View.GONE);
            layout_mag_no.setVisibility(View.VISIBLE);

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
            layout_material.setVisibility(View.VISIBLE);
            layout_mag_no.setVisibility(View.VISIBLE);
            layout_rank.setVisibility(View.GONE);
        }

        if (str_status.trim().equals(ProductionSchedule.STATUS.IMPORTED.toString()) ||
            str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_AGAIN.toString())||
            str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_FINISHED.toString())||
            str_status.trim().equals(ProductionSchedule.STATUS.PLASMA_FINISHED.toString())||
            str_status.trim().equals(ProductionSchedule.STATUS.BONDING_INS_FINISHED.toString())) {
            status_material = ProductionSchedule.STATUS_TM.NORMAL.toString();
            status_tool = ProductionSchedule.STATUS_TM.NORMAL.toString();
            //plan start DB WB MOLD
                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);
                    txt_overdue_title.setText(str_overdue_title);
                    txt_overdue_dt.setText(str_overdue_dt);
                    layout_alert_plan.setVisibility(View.VISIBLE);
                }
        } else if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())||
                   str_status.trim().equals(ProductionSchedule.STATUS.WIRE_BOND_WORKING.toString())||
                   str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WORKING.toString()) ) {

            //edit material & tool or --> output
                status_material = ProductionSchedule.STATUS_TM.ADD.toString();
                status_tool = ProductionSchedule.STATUS_TM.CHANGE.toString();
                scanner = false;
                txt_user.setBackgroundResource(R.drawable.img_backgroup);
                txt_machine.setBackgroundResource(R.drawable.img_backgroup);
                txt_mag_no.setBackgroundResource(R.drawable.img_backgroup);

                layout_material.setVisibility(View.GONE);
                layout_btn_start.setVisibility(View.GONE);
                layout_scan_material.setVisibility(View.GONE);
                layout_scan_tool.setVisibility(View.GONE);
                layout_btn_working.setVisibility(View.VISIBLE);

                txt_user.setText(str_user_id);
                txt_machine.setText(str_machine);
                txt_mag_no.setText(str_mag_no);


                Get_tool_his();
                Get_material_his();
            }

        Get_Tool(str_ics_product);
        Get_BOM(str_ics_product);
        Get_Machine(str_mc_type, str_item_type);
    }

    @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:
                if(str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())||
                   str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                    Intent intent = new Intent(Process_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                }else{
                    finish();
                }
                break;

            case R.id.btn_start:
                if (b_confirm == true) {
                    Block_button();
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                        Update_Diebond();
                    } else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())) {
                        Update_Wirebond();
                    } else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())) {
                        Update_Mold();
                    }
                }
                break;

            case R.id.btn_clear:
                txt_disbursement.setText("");
                txt_start_date.setText("");
                txt_service_life.setText("");
                txt_material_exp.setText("");

                break;

            case R.id.ibtn_camera:
                dispatchTakePictureIntent();
                break;

            case R.id.btn_edit:
                scanner = true;
                Mode_Edit();
                break;

            case R.id.btn_output:
                if(str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                    Intent i = new Intent(Process_Activity.this, Mold_Output_Activity.class);
                    startActivity(i);
                    finish();
                }else {
                    Intent i = new Intent(Process_Activity.this, Output_Activity.class);
                    startActivity(i);
                    finish();
                }
                break;

            case R.id.btn_save_edit:
                if (b_confirm == true) {
                    CheckData_Completed();
                }
                break;
        }
    }

    private void CheckData_Completed() {
        if (txt_user.getText().toString().trim().equals("")) {
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else if (map_tools_scan.size() == 0 && map_material_scan.size() == 0){
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Material & Tool ให้ครบ!")
                    .show();
        }else if (map_tools_scan.size() > 0 && edt_remark_tool.getText().toString().equals("")) {
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาใส่ Remark!")
                    .show();
        }else{
            Block_button();
            Save_change();
        }
    }

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

    private void Unblock_button() {
        b_confirm = true;
        btn_start.setEnabled(true);
        btn_start.setBackgroundResource(R.drawable.button_backgroup_green);
        btn_save_edit.setEnabled(true);
        btn_save_edit.setBackgroundResource(R.drawable.button_backgroup_green);
    }
    private void Mode_Edit() {
        scanner = true;
        mode_edit = true;
        txt_user.setText("");
        layout_scan_material.setVisibility(View.VISIBLE);
        layout_scan_tool.setVisibility(View.GONE);
        layout_btn_working.setVisibility(View.GONE);
        layout_btn_edit.setVisibility(View.VISIBLE);

        if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
        ||str_process.trim().equals(ProductionSchedule.PROCESS.MOLD .toString())){
            layout_material.setVisibility(View.VISIBLE);

        }

        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);

        list_tool_his.clear();
        list_material_his.clear();

        Set_View_Tools_His();
        Set_View_Material_His();
    }

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

        if (scanner == false)//status is working == true can't scan
            return;
        try {

            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.trim().split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 4){
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
                        ||str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){

                    Check_Material_dt(tokens);

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

            }else {
                if (scan_part == true) {
                    if (txt_ics_part.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกน ICS Code!")
                                .show();
                    } else {
                        scan_part = false;
                        txt_lot_part.setText(data);

                        String str_part = txt_ics_part.getText().toString().trim();
                        String str_lot_part = txt_lot_part.getText().toString().trim();
                        String Key = str_part + str_lot_part;
                        Log.d(getString(R.string.tag), "str_part : " + str_part);
                        Log.d(getString(R.string.tag), "str_lot_part : " + str_lot_part);

                        if (map_material_scan.containsKey(Key)) {//material duplicate --> del
                            map_material_scan.remove(Key);
                            Set_View_Material_Scan();

                        } else {//material
                            Log.d(getString(R.string.tag), "str_lot_part else : " + str_lot_part);
                            Get_Item_BOM bom = map_bom.get(str_part);
                            String m_type = bom.getUnit();
                            String m_process_time = bom.getQty();

                            Log.d(getString(R.string.tag), "material type : " + m_type);
                            Log.d(getString(R.string.tag), "material m_process_time : " + m_process_time);

                            if (diebond_process > 1 && m_type.trim().equals("LED")){//material LED
                                //check chip LED
                                if (str_check_time.trim().equals(m_process_time)){
                                    map_material_scan.put(Key, new Get_Item_BOM(
                                            bom.getICSProductCode(),
                                            bom.getProductName(),
                                            bom.getICSPart(),
                                            bom.getPartName(),
                                            str_lot_part,
                                            edt_rank.getText().toString().trim(),
                                            txt_disbursement.getText().toString().trim(),
                                            txt_start_date.getText().toString().trim(),
                                            txt_service_life.getText().toString().trim(),
                                            txt_material_exp.getText().toString().trim(),
                                            "",
                                            status_material,
                                            "",
                                            "",
                                            ""));
                                    Set_View_Material_Scan();

                                }else {
                                    new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("ไม่สามารถใช้ chip LED นี้ได้!"+"   \n"+str_part)
                                            .show();
                                }
                            }else {
                                map_material_scan.put(Key, new Get_Item_BOM(
                                        bom.getICSProductCode(),
                                        bom.getProductName(),
                                        bom.getICSPart(),
                                        bom.getPartName(),
                                        str_lot_part,
                                        edt_rank.getText().toString().trim(),
                                        txt_disbursement.getText().toString().trim(),
                                        txt_start_date.getText().toString().trim(),
                                        txt_service_life.getText().toString().trim(),
                                        txt_material_exp.getText().toString().trim(),
                                        "",
                                        status_material,
                                        "",
                                        "",
                                        ""));
                                Set_View_Material_Scan();
                            }
                        }
                    }
                } else {
                    if (data.trim().substring(0, 2).trim().equals("TL")) {//tool
                        scan_part = false;
                        txt_tool.setText("");

                        //tool
                        if (map_tools.containsKey(data.trim())) {
                            if (map_tools_scan.containsKey(data.trim())) {//tool duplicate --> del
                                map_tools_scan.remove(data.trim());

                            } else {
                                txt_tool.setText(data.trim());
                                Get_Item_Tools get_item_tools = map_tools.get(data.trim());
                                map_tools_scan.put(data.trim(), new Get_Item_Tools(
                                        get_item_tools.getICSProductCode(),
                                        get_item_tools.getProduction(),
                                        get_item_tools.getTool(),
                                        get_item_tools.getToolName(),
                                        get_item_tools.getToolCode(),
                                        status_tool));

                            }
                            Set_View_Tools_Scan();
                        } else {
                            txt_tool.setText("");
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Tool!")
                                    .show();
                        }
                    } else if (data.trim().contains(str_mc_type)) {//machine
                        if (map_machine.containsKey(data.trim())) {
                            if (mode_edit == true) {
                                new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ไม่สามารถเปลี่ยนเครื่องจักรได้!")
                                        .show();
                            } else {
                                scan_part = false;
                                Get_Machine machine = map_machine.get(data.trim());
                                str_frequency = machine.getFrequency();
                                txt_machine.setText(data.trim());
                                Log.d(getString(R.string.tag), "machine: " + data + "|" + str_frequency);
                            }
                        } else {
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร")
                                    .show();
                        }
                    } else if (data.trim().length() == 10) { //material & BOM
                        if (map_bom.containsKey(data.trim())) {
                            Get_Item_BOM bom = map_bom.get(data.trim());
                            String add = bom.getAdd();
                            String m_type = bom.getUnit();
                            String m_process_time = bom.getQty();

                            if (mode_edit == true) {
                                if (add.trim().equals("YES")) {
                                    scan_part = true;
                                    txt_ics_part.setText(data.trim());
                                } else {
                                    new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("ไม่สามารถเติม Material นี้ได้!")
                                            .show();
                                }
                            } else {

                                Log.d(getString(R.string.tag), "material type : " + m_type);
                                Log.d(getString(R.string.tag), "material m_process_time : " + m_process_time);

                                if (diebond_process > 1 && m_type.trim().equals("LED")){//material LED
                                    //check chip LED
                                    if (str_check_time.trim().equals(m_process_time)){
                                        scan_part = true;
                                        txt_ics_part.setText(data.trim());

                                    }else {
                                        scan_part = false;
                                        txt_ics_part.setText("");
                                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("ไม่สามารถใช้ chip LED นี้ได้!"+"   \n"+data.trim())
                                                .show();
                                    }
                                }else {
                                    scan_part = true;
                                    txt_ics_part.setText(data.trim());
                                }
                            }
                        } else {
                            scan_part = false;
                            txt_ics_part.setText("");
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Material!")
                                    .show();
                        }
                    } else if (data.trim().length() == 6) {//user
                        scan_part = false;
                        Check_User(data.trim());
                    } else if (data.trim().length() == 4) {//mag no
                        scan_part = false;
                        if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString()) ||
                                str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())) {

                            if (mode_edit == true) {
                                new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ไม่สามารถเปลี่ยน Mag no.ได้!")
                                        .show();
                            } else {
                                if (data.trim().equals(str_mag_no)) {
                                    txt_mag_no.setText(data.trim());

                                } else {
                                    new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("..........Mag No. ไม่ตรงกัน!.......... " + " Mag No. = " + str_mag_no)
                                            .show();
                                }
                            }
                        } else {
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("QR code ไม่ถูกต้อง!")
                                    .show();
                        }
                    } else {//remark & other
                        if (mode_edit == true && map_tools_scan.size() > 0) {
                            String remark = edt_remark_tool.getText().toString();
                            edt_remark_tool.setText(remark + " " + data);

                        } else {
                            new SweetAlertDialog(Process_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_Material_dt(String[] tokens) {
        try {
            Calendar now = Calendar.getInstance();
            Calendar now_dt = (Calendar) now.clone();
            Log.d(getString(R.string.tag), "now_dt: " + now_dt);

            for (int i = 0; i < tokens.length; i++){
                String date = tokens[i].trim();
                Log.d(getString(R.string.tag), "tokens[i] =  " + i+" : "+date);

                if (!date.equals("")){
                    if (i == 0){//check disbursement
                        Calendar disbursement_dt = ConvertStringToCalendar.convert(tokens[0].trim(), str_format_dt);
                        String str_disbursement_dt = dt_format_qr.format(disbursement_dt.getTime());
                        Log.d(getString(R.string.tag), "disbursement_dt: " + str_disbursement_dt);

                        if (now_dt.after(disbursement_dt)){
                            txt_disbursement.setText(tokens[0].trim());
                        }else {
                            Alert_Material("ยังไม่ถึงวันกำหนดเบิกใช้งาน",tokens[0].trim());
                            break;
                        }

                    }else if (i == 1){//start_date
                        Calendar start_dt = ConvertStringToCalendar.convert(tokens[1].trim(), str_format_dt);
                        String str_start_dt = dt_format_qr.format(start_dt.getTime());
                        Log.d(getString(R.string.tag), "str_start_dt: " + str_start_dt);

                        if (now_dt.after(start_dt)){
                            txt_start_date.setText(tokens[1].trim());
                        }else {
                            Alert_Material("ยังไม่ถึงกำหนดวันเริ่มใช้งาน",tokens[1].trim());
                            break;
                        }

                    }else if (i == 2){//service_life
                        Calendar service_life = ConvertStringToCalendar.convert(tokens[2].trim(), str_format_dt);
                        String str_service_life = dt_format_qr.format(service_life.getTime());
                        Log.d(getString(R.string.tag), "str_service_life: " + str_service_life);

                        if (now_dt.before(service_life)){
                            txt_service_life.setText(tokens[2].trim());
                        }else {
                            Alert_Material("เกินกำหนดอายุการใช้งาน",tokens[2].trim());
                            break;
                        }

                    }else {//material_exp
                        Calendar exp_dt = ConvertStringToCalendar.convert(tokens[3].trim(), str_format_dt);
                        String str_exp_dt = dt_format_qr.format(exp_dt.getTime());
                        Log.d(getString(R.string.tag), "str_exp_dt: " + str_exp_dt);
                        if (now_dt.before(exp_dt)){
                            txt_material_exp.setText(tokens[3].trim());
                        }else {
                            Alert_Material("หมดอายุเเล้ว",tokens[3].trim());
                            break;
                        }
                    }
                }
            }

        } catch (Exception e) {
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR get_date")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Alert_Material(String msg, String date) {
        txt_disbursement.setText("");
        txt_start_date.setText("");
        txt_service_life.setText("");
        txt_material_exp.setText("");
        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("แจ้งเตือน")
                .setContentText(msg+" \n "+date)
                .show();

    }

    private void Save_change() {
        if (map_tools_scan.size() > 0 && map_material_scan.size() == 0){//edit tool only
            Save_Tools();

        }else{
            Save_Material();
        }
    }

    private void Set_View_Material_Scan() {
        txt_ics_part.setText("");
        txt_lot_part.setText("");
        edt_rank.setText("");

        txt_disbursement.setText("");
        txt_start_date.setText("");
        txt_service_life.setText("");
        txt_material_exp.setText("");

        list_bom.clear();
        for (String key : map_material_scan.keySet()){
            Get_Item_BOM item_bom = map_material_scan.get(key);
            list_bom.add(new Get_Item_BOM(
                    item_bom.getICSProductCode(),
                    item_bom.getProductName(),
                    item_bom.getICSPart(),
                    item_bom.getPartName(),
                    item_bom.getLotNo(),
                    item_bom.getRank(),
                    item_bom.getDisbursement(),
                    item_bom.getStart_date(),
                    item_bom.getService_Life(),
                    item_bom.getMaterial_Exp(),
                    item_bom.getProcess(),
                    item_bom.getStatus(),
                    item_bom.getAdd(),
                    item_bom.getQty(),
                    item_bom.getUnit()));

            Log.d("ASI", "for list : " + item_bom.getLotNo());
        }

        bom_adapter = new BOM_Adapter(list_bom, Process_Activity.this);
        view_bom.setAdapter(bom_adapter);
    }

    private void Set_View_Tools_Scan() {
        list_tools.clear();
        for (String key : map_tools_scan.keySet()){
            Get_Item_Tools tools = map_tools_scan.get(key);
            list_tools.add(new Get_Item_Tools(
                    tools.getICSProductCode(),
                    tools.getProduction(),
                    tools.getTool(),
                    tools.getToolName(),
                    tools.getToolCode(),
                    tools.getStatus()));
        }
        tools_adapter = new Tools_Adapter(list_tools, Process_Activity.this);
        view_tools.setAdapter(tools_adapter);

        if (mode_edit == true){
            if (map_tools_scan.size() > 0){
                layout_remark.setVisibility(View.VISIBLE);
            }else {
                layout_remark.setVisibility(View.GONE);
            }
        }
    }

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/bom.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_save.setVisibility(View.GONE);
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ BOM!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_bom.put(jArray.getJSONObject(i).getString("ICSPart").trim(),
                                        new Get_Item_BOM(
                                                jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                                jArray.getJSONObject(i).getString("ProductName").trim(),
                                                jArray.getJSONObject(i).getString("ICSPart").trim(),
                                                jArray.getJSONObject(i).getString("PartName").trim(),
                                                "",
                                                "",
                                                "",
                                                "",
                                                "",
                                                "",
                                                "",
                                                "",
                                                jArray.getJSONObject(i).getString("Add").trim()== "null" ? "" : jArray.getJSONObject(i).getString("Add").trim(),
                                                jArray.getJSONObject(i).getString("Qty").trim(),
                                                jArray.getJSONObject(i).getString("Unit").trim()));
                            }
                            layout_alert_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_bom.size()));
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_machine");
            json.put("unit", unit);
            json.put("type", type);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/machine_master.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_save.setVisibility(View.GONE);
                            SweetAlertDialog d = new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            d.setCancelable(false);
                            d.setTitleText("แจ้งเตือน");
                            d.setContentText("ไม่พบเครื่องจักร : "+unit+"/"+type +"  \n กรุณาแจ้ง leader");
                            d.setConfirmText("รับทราบ");
                            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                            d.show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Code").trim(),
                                        new Get_Machine(
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Frequency").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Frequency").trim(),
                                                jArray.getJSONObject(i).getString("Max_line_SP").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Max_line_SP").trim(),
                                                jArray.getJSONObject(i).getString("Cavity").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Cavity").trim()));
                            }
                            layout_alert_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_machine.size()));
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tools.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_save.setVisibility(View.GONE);
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Tool!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_tools.put(jArray.getJSONObject(i).getString("ToolCode").trim(),
                                        new Get_Item_Tools(
                                                jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                                jArray.getJSONObject(i).getString("Production").trim(),
                                                jArray.getJSONObject(i).getString("Tool").trim(),
                                                jArray.getJSONObject(i).getString("ToolName").trim(),
                                                jArray.getJSONObject(i).getString("ToolCode").trim(),
                                              ""));
                            }
                            layout_alert_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_tools.size()));
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
                && Settings.getMap_user().get(data).getDiebond().trim().equals("1")){
                txt_user.setText(data);

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

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

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

    private void Update_Mold() {
        if ( txt_machine.getText().toString().trim().equals("")
             ||txt_user.getText().toString().trim().equals("")
             ||txt_mag_no.getText().toString().equals("")
             ||map_material_scan.size() == 0
             ||map_tools_scan.size() == 0) {

            Unblock_button();
            new SweetAlertDialog(Process_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());
            try {
                layout_alert_save.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_mold_working");
                json.put("machine", txt_machine.getText().toString().trim());
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_id);

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

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


    private void Update_Wirebond() {
        if ( txt_machine.getText().toString().trim().equals("")
                || txt_mag_no.getText().toString().equals("")
                || txt_user.getText().toString().trim().equals("")
//                || txt_equipment.getText().toString().trim().equals("")
//                || txt_equipment_exp.getText().toString().trim().equals("")
                || map_material_scan.size() == 0
                || map_tools_scan.size() == 0) {

            Unblock_button();
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();

        }else {
            calendar = Calendar.getInstance();
            calendar = (Calendar) calendar.clone();
            dt_to_server = fm_dt_server.format(calendar.getTime());
            try {
                layout_alert_save.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_wb_working");
                json.put("machine", txt_machine.getText().toString().trim());
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("user_id", txt_user.getText().toString().trim());
//                json.put("wirebond_equipment", txt_equipment.getText().toString().trim());
//                json.put("wirebond_equipment_exp",txt_equipment_exp.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_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 {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
                                Save_Material();

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


    private void Update_Diebond() {
        if ( txt_machine.getText().toString().trim().equals("") ||
             txt_user.getText().toString().trim().equals("")||
             map_material_scan.size() == 0||
             map_tools_scan.size() == 0) {

            Unblock_button();
            new SweetAlertDialog(Process_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());
            try {
                layout_alert_save.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_db_working");
                json.put("machine", txt_machine.getText().toString().trim());
                json.put("last_output", str_input);
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_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 {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
//                                Save_Material();
                                Insert_EventINS();

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

//        if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())){
//            str_mag_no = txt_mag_no.getText().toString().trim();
//        }else{//app
//            str_mag_no = "";
//        }
        try {
            layout_alert_save.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

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

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("sch_id", str_sch_id);
            jsonParams.put("process", str_process);
            jsonParams.put("check_times", str_check_time);
            jsonParams.put("mag_no_input", "");
            jsonParams.put("mag_no_output", "");
            jsonParams.put("input", str_input);
            jsonParams.put("output", "");
            jsonParams.put("machine_code", txt_machine.getText().toString().trim());
            jsonParams.put("start_user_id", txt_user.getText().toString().trim());
            jsonParams.put("start_dt", dt_to_server);
            JSONObject jsonObj = new JSONObject(jsonParams);
            jsonArray.put(jsonObj);

            json.put("ins_datas",jsonArray);

            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);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            Save_Material();

                        } else {
                            layout_alert_save.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert EvenINS")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void Save_Material() {
        Block_button();

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

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

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

            for (String key : map_material_scan.keySet()){
                Get_Item_BOM item = map_material_scan.get(key);

                Map<String, String> jsonParams = new HashMap<>();
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                    jsonParams.put("check_times", str_check_time);
                }else{
                    jsonParams.put("check_times", "1");
                }
                jsonParams.put("sch_id", str_sch_id);
                jsonParams.put("ics_part", item.getICSPart());
                jsonParams.put("part_name", item.getPartName());
                jsonParams.put("lot_no", item.getLotNo());
                jsonParams.put("rank", item.getRank());
                jsonParams.put("disbursement_dt", item.getDisbursement());
                jsonParams.put("start_use_dt", item.getStart_date());
                jsonParams.put("service_life_dt", item.getService_Life());
                jsonParams.put("expiration_date", item.getMaterial_Exp());
                jsonParams.put("process", str_process);
                jsonParams.put("status", item.getStatus());
                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("m_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/material_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);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            if (mode_edit == true){
                                if (map_tools_scan.size() == 0) {//edit material only
                                    if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                                        finish();
                                        Toast.makeText(Process_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                    }else {//process diebond & wirebond only
                                        Insert_RandomCheck_Edit();
                                    }
                                }else{
                                    Save_Tools();
                                }
                            }else {
                                Save_Tools();
                            }
                        }else {
                            layout_alert_save.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert MaterialFactorList")
                                    .show();
                        }
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        Unblock_button();
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Save_Tools() {
        Block_button();
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());

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


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

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

            for (String key : map_tools_scan.keySet()){
                Get_Item_Tools item = map_tools_scan.get(key);

                Map<String, String> jsonParams = new HashMap<>();
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                    jsonParams.put("check_times", str_check_time);
                }else{
                    jsonParams.put("check_times", "1");
                }
                jsonParams.put("sch_id", str_sch_id);
                jsonParams.put("tool_code", item.getToolCode());
                jsonParams.put("tool_name", item.getToolName());
                jsonParams.put("process", str_process);
                jsonParams.put("status", item.getStatus());
                jsonParams.put("remark",encode);
                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("t_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tool_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);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success") && affected_rows > 0) {
                            if (mode_edit == true) {// mode : edit
                                if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                                    finish();
                                    Toast.makeText(Process_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();

                                }else {//process diebond & wirebond only
                                    Insert_RandomCheck_Edit();
                                }
                            }else {
                                RandomCheck_Status();
                            }
                        }else {
                            layout_alert_save.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert ToolFactorList")
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_RandomCheck_Edit() {
        try {
            layout_alert_save.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังตรวจสอบการสุ่มตรวจ...");

            JSONObject json = new JSONObject();
            json.put("cmd", "random_check_edit");
            json.put("sch_id", str_sch_id);
            json.put("process", str_process);
            json.put("machine_code", txt_machine.getText().toString().trim());

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/random_check.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        layout_alert_save.setVisibility(View.GONE);

                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status").trim();
                        String message = jsonObject.getString("message").trim();

                        if (status.trim().equals("error")){
                            Unblock_button();
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(message)
                                    .show();
                        }else {//success
                            SweetAlertDialog pDialog = new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            pDialog.setTitleText("แจ้งเตือนการสุ่มตรวจสอบ");
                            pDialog.setContentText(message);
                            pDialog.setCancelable(false);
                            pDialog.setConfirmText("รับทราบ");
                            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                            pDialog.show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }

    }

    private void RandomCheck_Status() {
        //get start_dt end_dt
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        try {//check date time before 8:00AM
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String current_time = sdf.format(today);
            Date day_start = sdf.parse("08:00:00");
            Date day_end = sdf.parse("20:00:00");
            Date midnight = sdf.parse("00:00:00");
            Date current = sdf.parse(current_time);

            Log.d("current_time", current_time );
            if (current.after(day_start) && current.before(day_end) ) {
                Log.d("get_start_dt", "shift_day" );
                str_shift = "Shift_Day";
                start_dt = dt_format.format(start_calendar.getTime());
                end_dt = dt_format.format(end_calendar.getTime());
                start_dt = start_dt + " 08:00:00";
                end_dt = end_dt + " 19:59:59";

            }else{
                Log.d("get_start_dt", "Shift_Night" );
                str_shift = "Shift_Night";
                if (current.after(midnight) && current.before(day_start) ){
                    start_calendar.add(Calendar.DATE, -1);
                    start_dt = dt_format.format(start_calendar.getTime());
                    start_dt = start_dt + " 20:00:00";

                    end_dt = dt_format.format(end_calendar.getTime());
                    end_dt = end_dt + " 07:59:59";
                    Log.d("after midnight", start_dt );
                    Log.d("after midnight", end_dt );
                }else {
                    start_dt = dt_format.format(start_calendar.getTime());
                    start_dt = start_dt + " 20:00:00";

                    end_calendar.add(Calendar.DATE, +1);
                    end_dt = dt_format.format(end_calendar.getTime());
                    end_dt = end_dt + " 07:59:59";
                    Log.d("before midnight", start_dt );
                    Log.d("before midnight", end_dt );
                }
            }

        } catch (ParseException e) {
            // Invalid date was entered
            Unblock_button();
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR get_date")
                    .setContentText(e.getMessage())
                    .show();
        }
        try {
            layout_alert_save.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังตรวจสอบการสุ่มตรวจ...");

            JSONObject json = new JSONObject();
            json.put("cmd", "random_check");
            json.put("sch_id", str_sch_id);
            json.put("model", str_ics_product);
            json.put("process", str_process);
            json.put("machine_code", txt_machine.getText().toString().trim());
            json.put("frequency", str_frequency);
            json.put("shift", str_shift);
            json.put("start_dt", start_dt);
            json.put("end_dt", end_dt);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/random_check.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        layout_alert_save.setVisibility(View.GONE);
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status").trim();
                        String message = jsonObject.getString("message").trim();

                        if (status.trim().equals("error")){
                            Unblock_button();
                            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(message+"\n กรุณาติดต่อ leader")
                                    .show();
                        }else {//success
                            if (message.trim().equals("Not checking")){
                                finish();
                            }else if (message.trim().equals("Check Now")){
                                Get_RandomCheck_List();

                            }else {
                                SweetAlertDialog pDialog = new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.WARNING_TYPE);
                                pDialog.setTitleText("แจ้งเตือนการสุ่มตรวจสอบ");
                                pDialog.setContentText(message);
                                pDialog.setCancelable(false);
                                pDialog.setConfirmText("รับทราบ");
                                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        finish();
                                    }
                                });
                                pDialog.show();
                            }
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/random_check.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            finish();
                        }else {
                            String id = jArray.getJSONObject(0).getString("id").trim();
                            String sch_id = jArray.getJSONObject(0).getString("sch_id").trim();
                            String machine_code = jArray.getJSONObject(0).getString("machine_code").trim();
                            String random_type = jArray.getJSONObject(0).getString("random_type").trim();
                            String check_time = jArray.getJSONObject(0).getString("check_time").trim();

                            Intent intent = new Intent(Process_Activity.this, RandomCheck_Activity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("sch_id",sch_id);
                            intent.putExtra("machine_code",machine_code);
                            intent.putExtra("random_type",random_type);
                            intent.putExtra("check_time",check_time);
                            startActivity(intent);
                            finish();
                        }
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

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

            if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())){
                json.put("check_times", str_check_time);
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/material_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){
                            list_material_his.clear();
                            layout_alert_save.setVisibility(View.GONE);
                        }else {
                            for(int i=0; i<jArray.length(); i++) {

                                    list_material_his.add(new Get_Item_BOM(
                                        "",
                                        "",
                                        jArray.getJSONObject(i).getString("ics_part").trim(),
                                        jArray.getJSONObject(i).getString("part_name").trim(),
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                        jArray.getJSONObject(i).getString("rank") == "null" ? "" : jArray.getJSONObject(i).getString("rank").trim(),
                                        jArray.getJSONObject(i).getString("disbursement_dt") == "null" ? "" : jArray.getJSONObject(i).getString("disbursement_dt").trim(),
                                        jArray.getJSONObject(i).getString("start_use_dt") == "null" ? "" : jArray.getJSONObject(i).getString("start_use_dt").trim(),
                                        jArray.getJSONObject(i).getString("service_life_dt") == "null" ? "" : jArray.getJSONObject(i).getString("service_life_dt").trim(),
                                        jArray.getJSONObject(i).getString("expiration_date") == "null" ? "" : jArray.getJSONObject(i).getString("expiration_date").trim(),
                                        jArray.getJSONObject(i).getString("process").trim(),
                                        jArray.getJSONObject(i).getString("status").trim(),
                                            "","",""));
                            }
                            layout_alert_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(list_material_his.size()));
                            Set_View_Material_His();
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Set_View_Material_His() {
        bom_adapter = new BOM_Adapter(list_material_his, Process_Activity.this);
        view_bom.setAdapter(bom_adapter);

    }

    private void Get_tool_his() {
        list_tool_his.clear();

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

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

            if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())){
                json.put("check_times", str_check_time);
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tool_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){
                            list_tool_his.clear();
                            layout_alert_save.setVisibility(View.GONE);
                        }else {
                            for(int i=0; i<jArray.length(); i++) {
                                list_tool_his.add(new Get_Item_Tools(
                                        "",
                                        "",
                                        "",
                                        jArray.getJSONObject(i).getString("tool_name").trim(),
                                        jArray.getJSONObject(i).getString("tool_code").trim(),
                                        jArray.getJSONObject(i).getString("status").trim()));
                            }
                            layout_alert_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(list_tool_his.size()));
                        Set_View_Tools_His();
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Process_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Set_View_Tools_His() {
        tools_adapter = new Tools_Adapter(list_tool_his, Process_Activity.this);
        view_tools.setAdapter(tools_adapter);

    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        Boolean ItIsEmu = true;
        if (takePictureIntent.resolveActivity(getPackageManager()) != null
                || ItIsEmu) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.tomas.pcs_asi.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            } else {
                Toast.makeText(getApplicationContext(), "Photo file cannot be created!!", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Camera activity not found!!", Toast.LENGTH_LONG).show();
        }
    }

    private Bitmap getPic() {

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(currentPhotoPath, bmOptions);

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        //int scaleFactor = Math.max(1, Math.min(photoW/targetW, photoH/targetH));
        int scaleFactor = 1; // not scale

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
        return bitmap;
    }

    String currentPhotoPath;
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SIGN_INVOICE_ACTIVITY:
            case SIGN_DO_ACTIVITY:

                if (resultCode == Activity.RESULT_OK) {

                    finish();
                }
                break;
            case REQUEST_IMAGE_CAPTURE:
                if (resultCode == Activity.RESULT_OK) {
                    layout_alert_save.setVisibility(View.VISIBLE);
                    txt_message.setText("กรุณารอสักครู่ กำลังบันทึกรูปถ่าย...");

                    //Bitmap photo = (Bitmap) data.getExtras().get("data");
                    Bitmap photo = getPic();

                    // Save picture to server
                    calendar = Calendar.getInstance();
                    calendar = (Calendar) calendar.clone();
                    dt_to_photo = fm_dt_photo.format(calendar.getTime());
                    Log.d(getString(R.string.tag), "datetime_to_server: " + dt_to_photo);

                    try {
                        Map<String, Object> params = new HashMap<>();
                        String filename = str_process+"_"+str_lot+"_"+dt_to_photo+".jpeg";;
                                Log.d(getString(R.string.tag), "filename: " + filename);

                        String url = Settings.getMgmtList().get("web_api") + "/save_image.php";
                        JSONObject json = new JSONObject();
                        json.put("image_file", filename);
                        params.put("json", json.toString());

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        byte[] bytes = Base64.getEncoder().encode(bos.toByteArray());
                        params.put(filename, bytes);

                        new AsyncHttpClientMultipart(getApplicationContext()
                                ,url
                                , params
                        ) {
                            @Override
                            public void onFinished(String response, int resp_code) {
                                Log.d(getString(R.string.tag), "response: " + response);
                                // update mapItems
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    Log.d(getString(R.string.tag), "response : " + jsonObject.getString("status"));
                                    if (jsonObject.getString("status").equals("success")) {
                                        Toast.makeText(getApplicationContext(), "Photo saved.", Toast.LENGTH_LONG).show();

                                        // Try delete temporary file
                                        File file = new File(currentPhotoPath);
                                        boolean deleted = file.delete();
                                        Log.d(getString(R.string.tag), "file currentPhotoPath: " + currentPhotoPath);
                                        Log.d(getString(R.string.tag), "file deleted: " + deleted);
                                        deleteImage(currentPhotoPath);

                                    } else {

                                        MyAlertDialog dialog = new MyAlertDialog(
                                                Process_Activity.this
                                                , "Error"
                                                , "Please report the problems to Tomas Tech."
                                                , new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }
                                        );
                                    }
                                    layout_alert_save.setVisibility(View.GONE);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    public void deleteImage(String PhotoPath) {
        String file_dj_path = Environment.getExternalStorageDirectory() + PhotoPath;
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

    @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(str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())||
                        str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                        Intent intent = new Intent(Process_Activity.this, Search_ProcessSheet_Activity.class);
                        startActivity(intent);
                        finish();
                    }else{
                        finish();
                    }
                    break;

                case P2:
                    if (Overdue == true){
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_process.setVisibility(View.VISIBLE);

                    }else {
                        if (b_confirm == true) {
                            if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                                if (str_status.trim().equals(ProductionSchedule.STATUS.IMPORTED.toString())) {
                                    if (b_confirm == true){
                                        Block_button();
                                        Update_Diebond();
                                    }
                                } else if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())) {
                                    if (mode_edit == true) {//save_edit
                                        if (b_confirm == true) {
                                            CheckData_Completed();
                                        }

                                    } else { //intent next page output
                                        Intent i = new Intent(Process_Activity.this, Output_Activity.class);
                                        startActivity(i);
                                        finish();
                                    }
                                }
                            } else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())) {
                                if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_FINISHED.toString()) ||
                                        str_status.trim().equals(ProductionSchedule.STATUS.PLASMA_FINISHED.toString())) {
                                    if (b_confirm == true) {
                                        Block_button();
                                        Update_Wirebond();
                                    }

                                } else if (str_status.trim().equals(ProductionSchedule.STATUS.WIRE_BOND_WORKING.toString())) {
                                    if (mode_edit == true) {//save_edit
                                        if (b_confirm == true) {
                                            CheckData_Completed();
                                        }

                                    } else { //intent next page output
                                        Intent i = new Intent(Process_Activity.this, Output_Activity.class);
                                        startActivity(i);
                                        finish();
                                    }
                                }
                            } else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())) {
                                if (str_status.trim().equals(ProductionSchedule.STATUS.BONDING_INS_FINISHED.toString())) {
                                    if (b_confirm == true) {
                                        Block_button();
                                        Update_Mold();
                                    }

                                } else if (str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WORKING.toString())) {
                                    if (mode_edit == true) {//save_edit
                                        if (b_confirm == true) {
                                            CheckData_Completed();
                                        }

                                    } else { //intent next page output
                                        Intent i = new Intent(Process_Activity.this, Mold_Output_Activity.class);
                                        startActivity(i);
                                        finish();
                                    }
                                }
                            }
                        }
                    }
                    break;

                case P3:
                    if (str_status.trim().equals(ProductionSchedule.STATUS.IMPORTED.toString()) ||
                            str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_FINISHED.toString())||
                            str_status.trim().equals(ProductionSchedule.STATUS.PLASMA_FINISHED.toString())||
                            str_status.trim().equals(ProductionSchedule.STATUS.BONDING_INS_FINISHED.toString())) {

                        dispatchTakePictureIntent();

                    }else if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())||
                            str_status.trim().equals(ProductionSchedule.STATUS.WIRE_BOND_WORKING.toString())||
                            str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WORKING.toString())){
                       //Edit
                        scanner = true;
                        Mode_Edit();
                    }
                    break;

                case P4:
                    txt_disbursement.setText("");
                    txt_start_date.setText("");
                    txt_service_life.setText("");
                    txt_material_exp.setText("");
//                    txt_equipment.setText("");
//                    txt_equipment_exp.setText("");
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}