package com.tomas.pcs_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

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.text.Editable;
import android.text.TextWatcher;
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.ListData.User_Lists;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.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.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Output_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics_product, txt_job_order, txt_lot_no, txt_user, txt_mag_no, txt_input, txt_overdue_title, txt_overdue_dt,
            txt_message, txt_leader_lotout;
    EditText edt_output, edt_remark, edt_ng;
    String str_process, str_status, str_overdue_dt, str_overdue_title, str_sch_id, str_ics_product, str_job, str_lot, str_input,
            dt_to_server, str_role, dt_to_photo, str_check_time;
    ConstraintLayout layout_alert, layout_alert_plan, layout_output, layout_lotout;
    LinearLayout layout_ng;
    boolean Overdue, lot_out, b_confirm;
    Calendar calendar;
    SimpleDateFormat fm_dt_server, fm_dt_photo;
    Button btn_finish;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    int diebond_process = 0, diebond_check_times = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_output);
        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");

        b_confirm = true;
        Overdue = false;
        lot_out = false;

        layout_output = (ConstraintLayout)findViewById(R.id.layout_output);
        layout_alert_plan = (ConstraintLayout)findViewById(R.id.layout_alert_plan);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert_save);
        layout_ng = (LinearLayout)findViewById(R.id.layout_ng);

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

        btn_finish = (Button)findViewById(R.id.btn_finish);
        txt_header = (TextView) findViewById(R.id.txt_output_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_mag_no = (TextView) findViewById(R.id.txt_mag_no);
        txt_input = (TextView) findViewById(R.id.txt_input);
        edt_output = (EditText) findViewById(R.id.edt_output);
        edt_remark = (EditText) findViewById(R.id.edt_remark);
        edt_ng = (EditText)findViewById(R.id.edt_ng);
        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);

        edt_output.requestFocus();
        edt_output.setShowSoftInputOnFocus(false);

        edt_ng.requestFocus();
        edt_ng.setShowSoftInputOnFocus(false);
        edt_ng.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int input, output, ng;
                input = Integer.parseInt(txt_input.getText().toString().trim()) ;

                if (edt_ng.getText().toString().trim().equals("")){
                    ng = 0;
                }else {
                    ng = Integer.parseInt(edt_ng.getText().toString().trim()) ;
                }

                output = (input - ng);
                edt_output.setText(String.valueOf(output));
            }
        });

        str_process = Settings.getPROCESS();
        str_status  = Settings.getSTATUS();
        str_overdue_dt  = Settings.getOverdueDt();
        str_overdue_title = Settings.getOverdueTitle();
        str_sch_id = Settings.getSchId();
        str_ics_product = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_input = Settings.getQtyInput();

        Log.d(getString(R.string.tag), "DB Output Activity : " + str_process+" | "+ str_status+ " | "+str_overdue_dt);
        Log.d(getString(R.string.tag), "str_sch_id : " + str_sch_id);

        txt_header.setText(str_process+" OUTPUT");
        txt_ics_product.setText("ICS : "+str_ics_product);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot);
        txt_input.setText(str_input);
        edt_output.setBackgroundResource(R.drawable.img_backgroup);
        edt_output.setText(str_input);
        edt_output.setEnabled(false);

        if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())){
            str_check_time = Settings.getCheckTime();
            diebond_check_times = Integer.parseInt(str_check_time);
            diebond_process = Settings.getDbProcessTimes();
            txt_header.setText(str_process+" OUTPUT "+str_check_time+ "#");
        }

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

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


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                    Intent i = new Intent(Output_Activity.this, Process_Activity.class);
                    startActivity(i);
                    finish();
                break;

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

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

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

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

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

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

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

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

            } else if (str_scan.length() == 4) {//mag no
                txt_mag_no.setText(data.trim());

            } else {
                String old_data = edt_remark.getText().toString().trim();
                edt_remark.setText(old_data+" "+data.trim());
//                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("WARNING")
//                        .setContentText("Invalid QR code!")
//                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

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

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

    private void Update_LotOut() {
            calendar = Calendar.getInstance();
            calendar = (Calendar) calendar.clone();
            dt_to_server = fm_dt_server.format(calendar.getTime());
            Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

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

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

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

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", str_sch_id);
                jsonParams.put("process", str_process);
                jsonParams.put("remark", encode);
                jsonParams.put("user_id", txt_leader_lotout.getText().toString().trim());
                jsonParams.put("act_dt", dt_to_server);

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);

                json.put("lotout_datas", jsonArray);

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

                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");
                            if (status.equals("success") && affected_rows > 0) {
                                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                                    Toast.makeText(Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
                                    finish();
                                }else{
                                    Toast.makeText(Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
//                                    Intent intent = new Intent(Output_Activity.this, Search_ProcessSheet_Activity.class);
//                                    startActivity(intent);
                                    finish();
                                }
                            } else {
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }
    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            if (lot_out == true){//scan leader
                User_Lists lists = Settings.getMap_user().get(data);
                String nameEng = lists.getNameEng();
                str_role = lists.getRole();
                Log.d(getString(R.string.tag), "nameEng : " + nameEng);
                Log.d(getString(R.string.tag), "str_role : " + str_role);

                if (str_role.trim().equals("LEADER")){
                    txt_leader_lotout.setText(data);
                }else {
                    new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!")
                            .show();
                }
            }else {
                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 {
                    txt_user.setText("");
                    new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่อนุญาตให้ทำงานใน "+str_process)
                            .show();
                }
            }
        }else {
            txt_user.setText("");
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Save_Output_WB() {
        int qty_ng = 0;
        if (edt_ng.getText().toString().trim().equals("")|| edt_ng.getText().toString().trim().equals("0")){
            qty_ng = 0;
        }else {
            qty_ng = Integer.parseInt(edt_ng.getText().toString());
        }

        if (txt_user.getText().toString().trim().equals("") || edt_output.getText().toString().trim().equals("")){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
            return;
        }else if(qty_ng > 0 && edt_remark.getText().toString().trim().equals("")){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาใส่ Remark!")
                    .show();
            return;
        }

        if(lot_out == false) {
            if (txt_mag_no.getText().toString().equals("")) {
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกน Mag No!")
                        .show();
                return;
            }
        }

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

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "update_wb_finish");
            json.put("sch_id", str_sch_id);
            json.put("mag_no", txt_mag_no.getText().toString().trim());
            json.put("output", edt_output.getText().toString().trim());
            json.put("ng", edt_ng.getText().toString().trim());
            json.put("remark", encode);
            json.put("user_id", txt_user.getText().toString().trim());
            json.put("act_dt", dt_to_server);
            if (lot_out == false){//????????? lotout ??? update last_output_qty
                json.put("last_output", edt_output.getText().toString().trim());
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/production_plan.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success") && affected_rows > 0) {
                            if (lot_out == true){
                                Update_LotOut();
                            }else {
                                Toast.makeText(Output_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }else {
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't update ProductionPlan")
                                    .show();
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Save_Output_DB() {

        int qty_ng = 0;
        if (edt_ng.getText().toString().trim().equals("")|| edt_ng.getText().toString().trim().equals("0")){
            qty_ng = 0;
        }else {
            qty_ng = Integer.parseInt(edt_ng.getText().toString());
        }

         if(qty_ng > 0 && edt_remark.getText().toString().trim().equals("")){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาใส่ Remark!")
                    .show();
            return;
        }

        if (txt_user.getText().toString().trim().equals("") || edt_output.getText().toString().trim().equals("")){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
            return;
        }
        if(lot_out == false) {
            if (txt_mag_no.getText().toString().equals("")) {
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกน Mag No!")
                        .show();
                return;
            }
        }
            Block_button();
            calendar = Calendar.getInstance();
            calendar = (Calendar) calendar.clone();
            dt_to_server = fm_dt_server.format(calendar.getTime());

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

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

                JSONObject json = new JSONObject();
                json.put("cmd", "update_db_wait");
                json.put("sch_id", str_sch_id);
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("output", edt_output.getText().toString().trim());
                json.put("remark", encode);
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                if (lot_out == false) {//????????? lotout ??? update last_output_qty
                    json.put("last_output", edt_output.getText().toString().trim());
                }

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/production_plan.php",
                        json.toString()) {
                    @Override
                    protected void onFinished(String response, int resp_code) {
                        Log.d(getString(R.string.tag), "response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
                                if (lot_out == true) {
                                    Update_LotOut();
                                } else {
                                    Update_EventINS();
//                                    Toast.makeText(Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
//                                    finish();
                                }

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

    private void Save_Output_DB_AGAIN() {
        if (txt_user.getText().toString().trim().equals("") || edt_output.getText().toString().trim().equals("")){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
            return;
        }
        if(lot_out == false) {
            if (txt_mag_no.getText().toString().equals("")) {
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกน Mag No!")
                        .show();
                return;
            }
        }
        Block_button();
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "update_db_again");
            json.put("sch_id", str_sch_id);
            json.put("mag_no", txt_mag_no.getText().toString().trim());
            json.put("output", edt_output.getText().toString().trim());
//            json.put("remark", encode);
            json.put("user_id", txt_user.getText().toString().trim());
//            json.put("act_dt", dt_to_server);
            if (lot_out == false) {//????????? lotout ??? update last_output_qty
                json.put("last_output", edt_output.getText().toString().trim());
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/production_plan.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success") && affected_rows > 0) {
                            if (lot_out == true) {
                                Update_LotOut();
                            } else {
                                Update_EventINS();
//                                    Toast.makeText(Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
//                                    finish();
                            }

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

    private void Update_EventINS() {
        Block_button();

        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "update_event_ins");
            json.put("sch_id", str_sch_id);
            json.put("process", str_process);
            json.put("output", edt_output.getText().toString().trim());
            json.put("remark",encode);
            json.put("check_times", str_check_time);
            json.put("end_user_id", txt_user.getText().toString().trim());
            json.put("end_dt", dt_to_server);
            json.put("mag_no_output", txt_mag_no.getText().toString().trim());

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

                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            Toast.makeText(Output_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert EvenINS")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Cancel_LotOut() {//P3
        txt_leader_lotout.setText("");
        lot_out = false;
        layout_lotout.setVisibility(View.GONE);
        Unblock_button();
    }
    private void Check_output() {
        int i_output, i_input;
        i_input = Integer.parseInt(str_input);

        if (edt_output.getText().toString().trim().equals("")){
            i_output = 0;
        }else{
            String str_output = edt_output.getText().toString().trim();
            i_output = Integer.parseInt(str_output);
        }
        if (i_output > i_input){
            new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("จำนวน Output ไม่ถูกต้อง!")
                    .show();

        }else if (i_output <= 0){
            if (txt_user.getText().toString().trim().equals("")){
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกนรหัสพนักงาน")
                        .show();
            }else {
                lot_out = true;
                layout_lotout.setVisibility(View.VISIBLE);
            }
        }else {
            if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                Log.d(getString(R.string.tag), "diebond_check_times" + diebond_process +":"+diebond_check_times);
                if (diebond_process == diebond_check_times){//update status = DIE_BOND_WAIT
                    Save_Output_DB();

                }else {////update status = DIE_BOND_AGAIN
                    Save_Output_DB_AGAIN();

                }
            } else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())) {
                Save_Output_WB();
            }
        }
    }

    private void Update_Output() { //lot_out == true
            if (txt_leader_lotout.getText().toString().trim().equals("")) {
                new SweetAlertDialog(Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("กรุณาสแกนรหัสพนักงาน")
                        .show();
            } else {
                Log.d(getString(R.string.tag), "lot out = true: " + str_process);
                layout_lotout.setVisibility(View.GONE);
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())) {
                    Save_Output_DB();

                } else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())) {
                    Save_Output_WB();
                }
            }
    }

    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.setVisibility(View.VISIBLE);
                    txt_message.setText("Please wait, saving photo...");

                    //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+"_OUTPUT_"+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(
                                                Output_Activity.this
                                                , "Error"
                                                , "Please report the problems to Tomas Tech."
                                                , new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }
                                        );
                                    }
                                    layout_alert.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:
                    Intent i = new Intent(Output_Activity.this, Process_Activity.class);
                    startActivity(i);
                    finish();
                    break;

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

                    }else if (lot_out == true){
                        Log.d("ASI", "P2 lot_out == true");
                        if (b_confirm == true) {
                            Update_Output();
                        }
                    }else {
                        if (b_confirm == true) {
                            Check_output();
                        }
                    }

                    break;
                case P3:
                    if (lot_out == true) {
                        Cancel_LotOut();
                    }else{
                        dispatchTakePictureIntent();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}