package com.tomas.ht_mast;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.ScheduleInbound_Adapter;
import com.tomas.ht_mast.Adapter.ScheduleQc_Adapter;
import com.tomas.ht_mast.ListData.ItemMaster_list;
import com.tomas.ht_mast.ListData.Location_list;
import com.tomas.ht_mast.ListData.ScheduleInbound_Item;
import com.tomas.ht_mast.ListData.ScheduleQc_Item;
import com.tomas.ht_mast.ListData.Supplier_list;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class QCSchedule_Activity extends Scanner implements View.OnClickListener {

    EditText edt_date_from, edt_date_to;
    TextView txt_supplier, txt_part_no;
    Dialog dialog;
    RecyclerView view_schedule;
    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;

    List<ScheduleQc_Item> list_item_sch;
    Map<String, ScheduleQc_Item> map_sch_item;
    ScheduleQc_Adapter itemSchedule_adapter;
    String str_date_from, str_date_to, t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box;
    SwipeRefreshLayout swipeContainer;
    Spinner spinner_status;
    JSONObject label_detail = null;

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

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        map_sch_item = new LinkedHashMap<>();
        list_item_sch = new ArrayList<>();

        calendar = Calendar.getInstance();
        calendar_from = Calendar.getInstance();
//        calendar_from.add(Calendar.DATE, -7);
        calendar_to = Calendar.getInstance();
//        calendar_to.add(Calendar.DATE, +7);
        date = new SimpleDateFormat("yyyy-MM-dd");
        str_date_from = date.format(calendar_from.getTime());
        str_date_to = date.format(calendar_to.getTime());

        spinner_status = (Spinner)findViewById(R.id.spinner_status);

        txt_part_no = (TextView)findViewById(R.id.txt_part_no);
        txt_part_no.setText("All");
        txt_part_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_part();
            }
        });

        txt_supplier = (TextView) findViewById(R.id.txt_supplier);
        txt_supplier.setText("All");
        txt_supplier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_supplier();
            }
        });

        edt_date_from = (EditText)findViewById(R.id.edt_date_from);
        edt_date_from.setText(str_date_from);
        edt_date_from.setInputType(InputType.TYPE_NULL);
        edt_date_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(QCSchedule_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_from = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_from.setText(str_date_from);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_date_to = (EditText) findViewById(R.id.edt_date_to);
        edt_date_to.setText(str_date_to);
        edt_date_to.setInputType(InputType.TYPE_NULL);
        edt_date_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(QCSchedule_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_to = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_to.setText(str_date_to);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

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


        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeContainer.setRefreshing(false);
                        //Refresh
                        Load_Schedule();
                    }
                },2000);

            }
        });

        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

    }

    @Override
    protected void onStart() {
        super.onStart();

        Load_Schedule();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                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), "data read:" + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            if (tokens.length == 7) {//scan label
                t_order = tokens[0].trim();
                t_part = tokens[1].trim();
                t_dwg = tokens[2].trim();
                t_lot_no = tokens[3].trim();
                t_qty = tokens[4].trim();
                t_rank = tokens[5].trim();
                t_box = tokens[6].trim();

                Label_Inquiry(tokens[0].trim(), tokens[1].trim(), tokens[3].trim(), tokens[6].trim(), tokens);

            }else {
                if (Settings.getMap_supplier().containsKey(data.trim())){
                    txt_supplier.setText(data.trim());

                }else{
                    new SweetAlertDialog(QCSchedule_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 Label_Inquiry(String order_no, String parts_no, String lot_no, String box, String[] tokens) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/LABEL/INQUIRY");
            json.put("order_no", order_no);
            json.put("parts_no", parts_no);
            json.put("lot_no", lot_no);
            json.put("serial_no", box);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.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 value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0){
                            new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Not found label!!")
                                    .show();
                            return;
                        }

                        String status_label = jArray.getJSONObject(0).getString("status").trim();

                        if (status_label.trim().equals("5")) {
                            label_detail = jArray.getJSONObject(0);
                            Settings.setJS_label_detail(label_detail);
                            Check_Schedule_list(tokens);

                        } else {
                            new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Invalid Label!")
                                    .show();
                            return;
                        }

                    }catch (JSONException e) {
                        new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_Schedule_list(String[] tokens) {
        Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
        t_order = tokens[0].trim();
        t_part = tokens[1].trim();
        t_dwg = tokens[2].trim();
        t_lot_no = tokens[3].trim();
        t_qty = tokens[4].trim();
        t_rank = tokens[5].trim();
        t_box = tokens[6].trim();
        int count = 0;

        if (map_sch_item.containsKey(t_part)) {
            Intent i = new Intent(this, QCCheck_Activity.class);

            //count item part
            for (String key_map : map_sch_item.keySet()) {
                ScheduleQc_Item sch_item = map_sch_item.get(key_map);
                if (sch_item.getPart_no().trim().equals(t_part)) {
                    count = count + 1;
                }
            }

            Log.d(getString(R.string.tag), "map_sch_item count: " +count);

            if (count > 1){
                set_view_data(t_part.substring(4,11));

            }else if (count == 1){
                for (String key_map : map_sch_item.keySet()) {
                    ScheduleQc_Item item = map_sch_item.get(key_map);

                    if (item.getPart_no().trim().equals(t_part) && !item.getStatus().trim().equals("COMPLETED")) {
                        i.putExtra("scan", true);
                        i.putExtra("mode", ActionType.Mode.SCHEDULE.toString());
                        i.putExtra("schedule_id", item.getSchedule_id());
                        i.putExtra("order_no", item.getOrder_no());
                        i.putExtra("part_no", item.getPart_no());
                        i.putExtra("part_name", item.getPart_name());
                        i.putExtra("lot_no", item.getLot_no());
                        i.putExtra("rank", item.getRank());
                        i.putExtra("location", item.getLocation());
                        i.putExtra("plan_qty", item.getPlan_qty());
                        i.putExtra("act_qty", item.getAct_qty());
                        i.putExtra("unit", item.getUnit());
                        i.putExtra("supplier_id", item.getSupplier_id());
                        i.putExtra("supplier_name", item.getSupplier_name());
                        i.putExtra("inspection_flg", item.getInspection_flg());
                        i.putExtra("ref_id", item.getRef_id());
                        i.putExtra("t_box", t_box);
                        startActivity(i);
                        break;
                    }
                }
                // Discard the ScanManager class instance.
                mScanManager.removeDataListener(QCSchedule_Activity.this);
                // Discard the ScanManager class instance to release the resources.
                mScanManager.releaseScanManager();
            }else {
                new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Not found Schedule!")
                        .show();
            }



        } else {
            new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("This label was not found")
                    .show();
        }
//        }
    }

    private void search_part() {
        // Initialize dialog
        dialog = new Dialog(QCSchedule_Activity.this);
        dialog.setContentView(R.layout.dialog_searchable_spinner);
        dialog.getWindow().setLayout(300, 300);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        // Initialize and assign variable
        EditText editText = dialog.findViewById(R.id.edit_text);
        ListView listView = dialog.findViewById(R.id.list_view);

//         Initialize array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>
                (QCSchedule_Activity.this, android.R.layout.simple_list_item_1, Settings.getSub_item());

        // set adapter
        listView.setAdapter(adapter);
        editText.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) {
                adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item_code = adapter.getItem(position);
                txt_part_no.setText(item_code);
                dialog.dismiss();

                if (item_code.trim().equals("All")){
                    Load_Schedule();
                }else {
                    set_view_data(item_code);
                }
            }
        });
    }

    private void search_supplier() {
        // Initialize dialog
        dialog = new Dialog(QCSchedule_Activity.this);
        dialog.setContentView(R.layout.dialog_searchable_spinner);
        dialog.getWindow().setLayout(300,300);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        // Initialize and assign variable
        EditText editText=dialog.findViewById(R.id.edit_text);
        ListView listView=dialog.findViewById(R.id.list_view);

        // Initialize array adapter
        ArrayAdapter<String> adapter=new ArrayAdapter<>
                (QCSchedule_Activity.this, android.R.layout.simple_list_item_1,Settings.getList_supplier());

        // set adapter
        listView.setAdapter(adapter);
        editText.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) {
                adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String supplier = adapter.getItem(position);
                if (!supplier.trim().equals("All")) {
                    supplier = supplier.substring(0, 5);

                    Log.d(getString(R.string.tag), "supplier: " +supplier);
                    if (Settings.getMap_supplier().containsKey(supplier)){
                        txt_supplier.setText(supplier);
                        dialog.dismiss();
                    }
                }else {
                    txt_supplier.setText(supplier);
                    dialog.dismiss();
                }
            }
        });
    }

    private void Load_Schedule() {
        try {//check date from-to

            String Supplier = "";
            if (txt_supplier.getText().toString().trim().equals("All")){
                Supplier = "";
            }else {
                Supplier = txt_supplier.getText().toString().trim();
            }

            Date date_from = date.parse(str_date_from);
            Date date_to = date.parse(str_date_to);
            Log.d(getString(R.string.tag), "check date from-to: " + str_date_from+"-"+str_date_to);
            if (date_to.before(date_from)) {
                new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {
                map_sch_item.clear();
                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", "QC/SCHEDULE");
                    json.put("action_plan_date_from", str_date_from);
                    json.put("action_plan_date_to", str_date_to);
                    json.put("supplier", Supplier);
                    json.put("incharge", Settings.getLoginUser().getDepartment());
                    json.put("except_complete", spinner_status.getSelectedItem().toString().trim());

                    new AsyncHttpClient(getApplicationContext(),
                            Settings.getMgmtList().get("web_api") + "/ht_api.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 value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);

                                if (jArray.length() == 0){
                                    Toast.makeText(QCSchedule_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {
                                    for(int i = 0; i < jArray.length(); i++){
                                        map_sch_item.put(jArray.getJSONObject(i).getString("parts_no").trim(),
                                                new ScheduleQc_Item(
                                                        jArray.getJSONObject(i).getString("id"),
                                                        jArray.getJSONObject(i).getString("order_no"),
                                                        jArray.getJSONObject(i).getString("supplier_id"),
                                                        "",
                                                        jArray.getJSONObject(i).getString("parts_no"),
                                                        jArray.getJSONObject(i).getString("parts_name").trim(),
                                                        "",
                                                        jArray.getJSONObject(i).getString("rank"),
                                                        "",
                                                        jArray.getJSONObject(i).getString("qty"),
                                                        jArray.getJSONObject(i).getString("action_act_qty"),
                                                        jArray.getJSONObject(i).getString("status"),
                                                        jArray.getJSONObject(i).getString("unit_qty"),
                                                        jArray.getJSONObject(i).getString("inspection_flg"),
                                                        jArray.getJSONObject(i).getString("ref_id")));

                                    }
                                }
                                Log.d(getString(R.string.tag), String.valueOf(list_item_sch.size()));
                                update_map_sch();
                            }catch (JSONException e) {
                                new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();

                }catch (JSONException e) {
                    new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                }

            }
        }catch (ParseException e){
            new SweetAlertDialog(QCSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR : check date from-to ")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void update_map_sch() {
        String Location_QC = "";
        //get location qc
        for (String kk : Settings.getMap_location().keySet()){
            Location_list location_list = Settings.getMap_location().get(kk);
            if (location_list.getQc_area().trim().equals("1")){
                Location_QC = location_list.getId();
                Log.d(getString(R.string.tag),"Location"+ Location_QC);
                break;
            }
        }
        Log.d(getString(R.string.tag),"Location for rank A B:"+ Location_QC);
        Log.d(getString(R.string.tag), String.valueOf(map_sch_item.size()));
        if (map_sch_item.size() > 0) {
            for (String key : map_sch_item.keySet()) {
                ScheduleQc_Item item = map_sch_item.get(key);
                String supplier_code = item.getSupplier_id();
                String part_no = item.getPart_no();
                String rank = item.getRank();
                String supplier_name = "", location;
                Log.d(getString(R.string.tag), "supplier_code:" + supplier_code);

                //supplier_name
                if (Settings.getMap_supplier().containsKey(supplier_code)) {
                    Supplier_list sup = Settings.getMap_supplier().get(supplier_code);
                    supplier_name = sup.getName();
                } else {
                    supplier_name = "";
                }
                Log.d(getString(R.string.tag), "supplier_name:" + supplier_name);

                if (Settings.getMap_items().containsKey(part_no)) {
                    ItemMaster_list item_master = Settings.getMap_items().get(part_no);
                    location = item_master.getLocation();
                } else {
                    location = "";
                }

                item.setLocation(location);
                item.setSupplier_name(supplier_name);
                map_sch_item.put(key, item);
            }
            Log.d(getString(R.string.tag), "no Check" + String.valueOf(list_item_sch.size()));
        }
        set_view_data("");
    }

    private void set_view_data(String search_part) {
        list_item_sch.clear();
        for (String key : map_sch_item.keySet()) {
            ScheduleQc_Item item = map_sch_item.get(key);
            String part_no = item.getPart_no();
            Log.d(getString(R.string.tag), part_no.substring(4, 11).trim() + "/" + search_part);

            if (search_part.trim().equals("")){
                list_item_sch.add(new ScheduleQc_Item(
                        item.getSchedule_id(),
                        item.getOrder_no(),
                        item.getSupplier_id(),
                        item.getSupplier_name(),
                        item.getPart_no(),
                        item.getPart_name(),
                        item.getLot_no(),
                        item.getRank(),
                        item.getLocation(),
                        item.getPlan_qty(),
                        item.getAct_qty(),
                        item.getStatus(),
                        item.getUnit(),
                        item.getInspection_flg(),
                        item.getRef_id()));
            }else {
                if (part_no.substring(4, 11).trim().equals(search_part)) {
                    list_item_sch.add(new ScheduleQc_Item(
                            item.getSchedule_id(),
                            item.getOrder_no(),
                            item.getSupplier_id(),
                            item.getSupplier_name(),
                            item.getPart_no(),
                            item.getPart_name(),
                            item.getLot_no(),
                            item.getRank(),
                            item.getLocation(),
                            item.getPlan_qty(),
                            item.getAct_qty(),
                            item.getStatus(),
                            item.getUnit(),
                            item.getInspection_flg(),
                            item.getRef_id()));
                }
            }
        }
        Log.d(getString(R.string.tag), "no Check" + String.valueOf(list_item_sch.size()));

        itemSchedule_adapter = new ScheduleQc_Adapter(list_item_sch, this);
        view_schedule.setAdapter(itemSchedule_adapter);
        Log.d(getString(R.string.tag), "set adapter");

    }

    @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:
                    finish();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}