package com.tomas.pcs_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
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.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
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.format.Time;
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.Classify_Adapter;
import com.tomas.pcs_asi.Adapter.Oven_Adapter;
import com.tomas.pcs_asi.ListData.Item_Classify;
import com.tomas.pcs_asi.ListData.Item_Oven;
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.text.SimpleDateFormat;
import java.util.ArrayList;
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 Classify_Activity extends Scanner implements View.OnClickListener {
    TextView txt_ics, txt_lot_cls, txt_job_order, txt_lot_no, txt_machine, txt_user, txt_total_input, txt_overdue_title, txt_overdue_dt, txt_message;
    LinearLayout layout_classify, layout_lot_classify, layout_cls_input, layout_btn_start, layout_btn_confirm, layout_btn_output;
    String str_process, str_main_ics, str_job_order, str_lot_no, str_mc_type, str_max_cls, str_cls_lot, str_status,dt_to_photo,dt_format = "yyyy-MM-dd HH:mm:ss",
            dt_to_server, str_user, str_machine, SCH_ID, ICS, JOB_ORDER, LOT_NO, PROCESS, STATUS, CLS_PLAN_START, INPUT, GEN_LOT_CLS,dt_classify,
            Machine_No, Machine_Code, Machine_Job_No, Item_Type;
    ConstraintLayout layout_alert_plan,layout_alert;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    RecyclerView view_classify;
    Classify_Adapter classify_adapter;
    Calendar calendar;
    boolean scanner, Overdue, confirmed, update_data, intent_output, b_confirm;
    SimpleDateFormat fm_dt_server, fm_dt_photo, fm_dt_classify;
    int scan = 0, MAX_CLS, input, sum_input;
    Map<String, Item_Classify>map_item_cls;
    List<Item_Classify>list_classify;
    Button btn_confirm, btn_close;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify);
        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");
        fm_dt_classify = new SimpleDateFormat("yyyyMMdd");

        scan = 0;
        b_confirm = true;
        scanner = true;
        confirmed = false;
        update_data = false;
        intent_output = false;

        map_item_cls = new LinkedHashMap<>();
        list_classify = new ArrayList<Item_Classify>();

        layout_classify = (LinearLayout)findViewById(R.id.layout_classify);
        layout_lot_classify = (LinearLayout)findViewById(R.id.layout_lot_classify);
        layout_cls_input = (LinearLayout)findViewById(R.id.layout_cls_input);
        layout_btn_start = (LinearLayout)findViewById(R.id.layout_btn_start);
        layout_btn_confirm = (LinearLayout)findViewById(R.id.layout_btn_confirm);
        layout_btn_output = (LinearLayout)findViewById(R.id.layout_btn_output);
        layout_alert_plan = (ConstraintLayout)findViewById(R.id.layout_alert_plan);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);

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

        txt_user = (TextView)findViewById(R.id.txt_user);
        txt_ics = (TextView)findViewById(R.id.txt_ics);
        txt_lot_cls = (TextView)findViewById(R.id.txt_lot_cls);
        txt_job_order = (TextView)findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView)findViewById(R.id.txt_lot_no);
        txt_machine = (TextView)findViewById(R.id.txt_machine);
        txt_total_input = (TextView)findViewById(R.id.txt_total_input);
        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);

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

        str_process = Settings.getPROCESS();
        str_main_ics = Settings.getICS();
        str_job_order  = Settings.getJobOrder();
        str_lot_no = Settings.getLotNo();
        str_mc_type = Settings.getMcType();
        str_status = Settings.getSTATUS();
        str_max_cls = Settings.getClsMax();
        MAX_CLS = Integer.parseInt(str_max_cls);
        Item_Type = Settings.getItemType();
        Log.d(getString(R.string.tag), "Classify Activity : " + str_process+" | "+ str_status+"|"+str_mc_type);

        txt_ics.setText(str_main_ics);
        txt_ics.setTextColor(Color.parseColor("#BDBBBB"));

        if (str_status.trim().equals(ProductionSchedule.STATUS.APPEARANCE_FINISHED.toString())
            ||str_status.trim().equals(ProductionSchedule.STATUS.DICER_FINISHED.toString())){
            txt_job_order.setText(str_job_order);
            txt_lot_no.setText(str_lot_no);
            Check_ProcessSheet();

        }else if (str_status.trim().equals(ProductionSchedule.STATUS.CLASSIFY_WORKING.toString())){
            intent_output = true;
            scanner = false;
            str_cls_lot = Settings.getClsLot();
            str_user = Settings.getUser();
            str_machine = Settings.getMACHINE();

            layout_cls_input.setVisibility(View.GONE);
            layout_btn_start.setVisibility(View.GONE);
            layout_btn_output.setVisibility(View.VISIBLE);
            layout_lot_classify.setVisibility(View.VISIBLE);

            txt_user.setText(str_user);
            txt_machine.setText(str_machine);
            txt_lot_cls.setText(str_cls_lot);

            //search classify group
            Search_ProcessSheet_CLS(str_cls_lot);
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                if (confirmed == true){
                    Return_Layout();
                }else {
                    Finish_Activity();
                }
                break;

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

            case R.id.btn_start:
                Set_layout_view();
                break;

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

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

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

            case R.id.btn_close:
                Finish_Activity();
                break;
            case R.id.btn_output:
                Intent intent = new Intent(Classify_Activity.this, Classify_Output_Activity.class);
                startActivity(intent);
                finish();
                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);

            if (scanner == false){
                return;

            }else {
                if (scan == 0){
//                    if (map_item_cls.size() == MAX_CLS){
//                        new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                .setTitleText("แจ้งเตือน")
//                                .setContentText("สแกนครบแล้ว!")
//                                .show();
//                    }else {
                        if (data.trim().length() == 10) { //ics
                            if (map_item_cls.size() == MAX_CLS){
                                new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("สแกนครบแล้ว!")
                                    .show();
                            }else {
                                if (data.trim().equals(str_main_ics)) {//same ICS Product
                                    scan = 1;
                                    txt_ics.setText(data.trim());
                                    txt_ics.setTextColor(Color.parseColor("#FF000000"));
                                    txt_job_order.setText("");
                                    txt_lot_no.setText("");

                                } else {
                                    Reset_view();
                                    new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("ICS Code ไม่ตรงกัน!")
                                            .show();
                                }
                            }
                        } else if (data.trim().contains(str_mc_type)) {
                            Check_Machine(data.trim());

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

                        } else {
                            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("QR code ไม่ถูกต้อง!")
                                    .show();
                        }
//                    }
                }else if (scan == 1){
                    if (!data.trim().equals("")) {//job order
                        txt_job_order.setText(data.trim());
                        scan = 2;
                    }
                }else {
                    if (!data.trim().equals("")) {//lot no
                        scan = 0;
                        txt_lot_no.setText(data.trim());
                        Check_ProcessSheet();
                    }
                }
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            if (Settings.getMap_user().get(data).getClassify().trim().equals("1")) {
                txt_user.setText(data);
                User_Lists lists = Settings.getMap_user().get(data);
                String nameEng = lists.getNameEng();
                Log.d(getString(R.string.tag), "nameEng : " + nameEng);

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search_classify_lot");
            json.put("classify_lot", classify_lot);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Classify Lot : "+classify_lot+" not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                list_classify.add(new Item_Classify(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        jArray.getJSONObject(i).getString("job_order").trim(),
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                    ""));
                            }
                            classify_adapter = new Classify_Adapter(list_classify, Classify_Activity.this,str_process);
                            view_classify.setAdapter(classify_adapter);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

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


    private void Gen_Lot_Classify() {
        //get count machine_code where date
        Block_button();

        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_classify = fm_dt_classify.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_classify: " + dt_classify);//yyyyMMdd

        String year1, year2, month, date;
        year1 = dt_classify.substring(3,4);
        year2 = dt_classify.substring(2,4);
        month =  dt_classify.substring(4,6);
        date = dt_classify.substring(6,8);
        GEN_LOT_CLS = "";

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_job");
            json.put("machine_code", Machine_Code);
            json.put("date", dt_classify);
            json.put("type",Item_Type);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Machine Job No. not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                Machine_Job_No = jArray.getJSONObject(i).getString("mc_job_no").trim();
                            }

//                            GEN_LOT_CLS = "E" + year1 + year2 + month + date + Machine_Job_No + Machine_No + "V";
                            GEN_LOT_CLS = "E" + year1 + month + date + Machine_Job_No + Machine_No + "V";
                            Log.d(getString(R.string.tag), "GEN_LOT_CLS: " + GEN_LOT_CLS);
                            txt_lot_cls.setText(GEN_LOT_CLS);
                            Update_ProductionPlan();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_ClassifyLot() {
        Block_button();

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

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

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

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("machine_code", txt_machine.getText().toString().trim());
            jsonParams.put("type", Item_Type);
            jsonParams.put("classify_lot",GEN_LOT_CLS);
            jsonParams.put("input", txt_total_input.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("cls_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/classify_lot.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) {
                            Toast.makeText(Classify_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                            update_data = true;
                            confirmed = false;//???????? P1 finish activity
                            btn_confirm.setVisibility(View.GONE);
                            layout_lot_classify.setVisibility(View.VISIBLE);
                            btn_close.setVisibility(View.VISIBLE);
                            layout_alert.setVisibility(View.GONE);

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

    private void Update_ProductionPlan() {
        Block_button();

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

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

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

                for (String key : map_item_cls.keySet()) {
                    Item_Classify item = map_item_cls.get(key);

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("sch_id", item.getSch_id());
                    jsonParams.put("classify_lot", GEN_LOT_CLS);
                    jsonParams.put("machine", txt_machine.getText().toString().trim());
                    jsonParams.put("user_id", txt_user.getText().toString().trim());
                    jsonParams.put("act_dt", dt_to_server);

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
                json.put("cls_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) {
                            Insert_ClassifyLot();

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

    private void Clear_classify() {
        map_item_cls.clear();
        Set_view_classify();
    }

    private void Check_ProcessSheet() {
        if (txt_ics.getText().toString().trim().equals("")
                ||txt_job_order.getText().toString().trim().equals("")
                ||txt_lot_no.getText().toString().trim().equals(""))
            return;

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", txt_ics.getText().toString().trim());
            json.put("job_order", txt_job_order.getText().toString().trim());
            json.put("lot_no", txt_lot_no.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 {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            Reset_view();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Process Sheet!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                PROCESS = jArray.getJSONObject(i).getString("process").trim();
                                STATUS = jArray.getJSONObject(i).getString("status").trim();
                                SCH_ID = jArray.getJSONObject(i).getString("sch_id").trim();
                                ICS = jArray.getJSONObject(i).getString("ICSProductCode").trim();
                                JOB_ORDER = jArray.getJSONObject(i).getString("job_order").trim();
                                LOT_NO = jArray.getJSONObject(i).getString("lot_no").trim();
                                INPUT = jArray.getJSONObject(i).getString("appearance_output").trim() == "null" ? jArray.getJSONObject(i).getString("dicer_output").trim() : jArray.getJSONObject(i).getString("appearance_output").trim();
                                Log.d(getString(R.string.tag), "INPUT: " + INPUT);

                                JSONObject obj = jArray.getJSONObject(i);
                                JSONObject array_start_dt = obj.getJSONObject("classify_plan_start_dt");
                                CLS_PLAN_START = array_start_dt.getString("date");
                                CLS_PLAN_START = CLS_PLAN_START.substring(0,19);
                                Log.d(getString(R.string.tag), "CLS_PLAN_START: " + CLS_PLAN_START);
                            }
                            Check_status();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_status() {
        if(map_item_cls.containsKey(SCH_ID)){
            Log.d(getString(R.string.tag), "remove: " + SCH_ID);

            map_item_cls.remove(SCH_ID);
            Set_view_classify();
            Reset_view();

        }else {
            if (STATUS.trim().equals(ProductionSchedule.STATUS.APPEARANCE_FINISHED.toString())) {
                Check_Overdue(CLS_PLAN_START, "Start Plan Classify");

            } else if (STATUS.trim().equals(ProductionSchedule.STATUS.DICER_FINISHED.toString())) {
                SweetAlertDialog pDialog = new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE);
                pDialog.setTitleText("Status : DICER_FINISHED");
                pDialog.setContentText("คุณต้องการทำงานข้าม Process Appearance");
                pDialog.setCancelable(false);
                pDialog.setCancelText("ยกเลิก");
                pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        txt_job_order.setText("");
                        txt_lot_no.setText("");
                    }
                });
                pDialog.setConfirmText("ตกลง");
                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        Check_Overdue(CLS_PLAN_START, "Start Plan Classify");
                    }
                });
                pDialog.show();

            }else {
                Reset_view();
                new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ Process sheet : "+STATUS)
                        .show();
            }
        }
    }

    private void Check_Overdue(String PLAN_DT, String Title) {
        calendar = ConvertStringToCalendar.convert(PLAN_DT, dt_format);
        String p_date1 = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date1);

        calendar.add(Calendar.MINUTE, 30);
        String p_date2 = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date2);

        Calendar now = Calendar.getInstance();
        Calendar now_dt = (Calendar) now.clone();
        String str_now = fm_dt_server.format(now_dt.getTime());
        Log.d(getString(R.string.tag), "now_dt: " + str_now);

        if (now_dt.after(calendar)){
            Log.d(getString(R.string.tag), "if alert");
            Overdue = true;
            txt_overdue_dt.setText(PLAN_DT);
            txt_overdue_title.setText(Title);
            layout_alert_plan.setVisibility(View.VISIBLE);
            layout_classify.setVisibility(View.GONE);

        } else {
            Log.d(getString(R.string.tag), "else");
            Overdue = false;
            layout_alert_plan.setVisibility(View.GONE);
            layout_classify.setVisibility(View.VISIBLE);

        }
        Log.d(getString(R.string.tag), "Add_mapItem: " + String.valueOf(map_item_cls.size()));
        //add map
        map_item_cls.put(SCH_ID, new Item_Classify(
                SCH_ID,
                ICS,
                JOB_ORDER,
                LOT_NO,
                INPUT));
        Log.d(getString(R.string.tag), "else: " + String.valueOf(map_item_cls.size()));
        Set_view_classify();
    }

    private void Set_view_classify() {
        //set view
        list_classify.clear();
        for (String key : map_item_cls.keySet()) {
            Item_Classify item = map_item_cls.get(key);
            list_classify.add(new Item_Classify(
                    item.getSch_id(),
                    item.getIcs_code(),
                    item.getJob_order(),
                    item.getLot_no(),
                    item.getInput()));
        }
        Log.d(getString(R.string.tag), "list_dicer: " + String.valueOf(list_classify.size()));
        classify_adapter = new Classify_Adapter(list_classify, Classify_Activity.this,str_process);
        view_classify.setAdapter(classify_adapter);
        Reset_view();

    }

    private void Reset_view() {
        scan = 0;
        txt_ics.setTextColor(Color.parseColor("#BDBBBB"));
        txt_job_order.setText("");
        txt_lot_no.setText("");

    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("machine_code", machine_code);
            json.put("type", Item_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.setVisibility(View.GONE);
                            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                Machine_No = jArray.getJSONObject(i).getString("MachineNo").trim() == "null" ? "" : jArray.getJSONObject(i).getString("MachineNo").trim();
                                Machine_Code = jArray.getJSONObject(i).getString("Code").trim() == "null" ? "" : jArray.getJSONObject(i).getString("Code").trim();

                            }
                            Log.d(getString(R.string.tag), "response: " + response);
                            if (Machine_No.trim().equals("")){
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ไม่พบหมายเลขเครื่องจักร \n ไม่สามารถ gen Lot Classify ได้!" )
                                        .show();
                            }else{
                                txt_machine.setText(Machine_Code);
                                layout_alert.setVisibility(View.GONE);
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    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;
    }

    @SuppressLint("StaticFieldLeak")
    @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("กรุณารอสักครู่ กำลังบันทึกรูปถ่าย...");

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

                                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(
                                                Classify_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();
                                    Log.d(getString(R.string.tag), "catch:1 ");
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(getString(R.string.tag), "catch:2 ");
                    }
                }
                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())));
        }
    }

    private void Finish_Activity() {
//        Intent intent = new Intent(Classify_Activity.this, Search_ProcessSheet_Lot_Activity.class);
//        startActivity(intent);
        finish();
    }

    private void Return_Layout() {
        confirmed = false;
        scanner = true;
        layout_cls_input.setVisibility(View.VISIBLE);
        layout_btn_start.setVisibility(View.VISIBLE);
        layout_btn_confirm.setVisibility(View.GONE);
        txt_ics.setTextColor(Color.parseColor("#BDBBBB"));
        txt_ics.setBackgroundResource(R.drawable.button_backgroup_menu);
        txt_machine.setBackgroundResource(R.drawable.button_backgroup_menu);
        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
    }

    private void Set_layout_view() {
        if (map_item_cls.size() == 0||
                txt_machine.getText().toString().trim().equals("")||
                txt_user.getText().toString().trim().equals("")){
            new SweetAlertDialog(Classify_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else {
            confirmed = true;
            scanner = false;
            txt_ics.setTextColor(Color.parseColor("#FF000000"));
            layout_cls_input.setVisibility(View.GONE);
            layout_btn_start.setVisibility(View.GONE);
            layout_btn_confirm.setVisibility(View.VISIBLE);
            txt_ics.setBackgroundResource(R.drawable.img_backgroup);
            txt_machine.setBackgroundResource(R.drawable.img_backgroup);
            txt_user.setBackgroundResource(R.drawable.img_backgroup);
        }
        //sum input
        input = 0; sum_input = 0;
        for (String key : map_item_cls.keySet()){
            Item_Classify item = map_item_cls.get(key);
            String str_input = item.getInput();

            input = Integer.parseInt(str_input);
            Log.d(getString(R.string.tag), "input = " + input);
            sum_input = (sum_input + input);
            Log.d(getString(R.string.tag), "sum_output = " + sum_input);
        }
        txt_total_input.setText(String.valueOf(sum_input));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    if (confirmed == true){
                        Return_Layout();
                    }else {
                        Finish_Activity();
                    }
                    break;

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

                    }else if (confirmed == true){
                        if (b_confirm == true) {
                            Block_button();
                            Gen_Lot_Classify();
                        }
                    }else if (update_data == true){
                        Finish_Activity();
                    }else if (intent_output == true){
                        Intent intent = new Intent(Classify_Activity.this, Classify_Output_Activity.class);
                        startActivity(intent);
                        finish();
                    }else{
                        Set_layout_view();
                    }
                    break;

                case P3:
                    dispatchTakePictureIntent();
                    break;

                case P4:
                    Clear_classify();
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}