package com.fxy.putIn;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.elvishew.xlog.XLog;
import com.fxy.R;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.interfaces.OnRxScanerListener;
import com.fxy.baselibrary.qrcode.ActivityScanerCode;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.baselibrary.views.MarqueeTextView;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.common.CommonDialog;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.constant.SPCache;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.view.FloatingImageView;
import com.google.zxing.Result;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

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

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import sto.android.app.StoJNI;
import sto.android.app.StoPdaKeyEvent;
import sto.android.app.StoTongJNI;

public class TrayMainActivity extends  BaseActivity implements StoJNI.ScanCallBack {
    /**
     * 列表适配器
     */
    Context mContext = this;

    //单号清除
    @BindView(R.id.ib_order_no_clear)
    ImageButton ibOrderNoClear;

    //单号
    @BindView(R.id.et_order_no)
    EditText etOrderNo;

    //单号
    @BindView(R.id.et_ctn)
    EditText etCtn;

    @BindView(R.id.mt_tracking_number)
    MarqueeTextView mtTrackingNumber;

    @BindView(R.id.mt_send_way)
    MarqueeTextView mtSendWay;

    @BindView(R.id.mt_putin_qty)
    MarqueeTextView mtPutinQty;

    @BindView(R.id.mt_customer_code)
    MarqueeTextView mtCustomerCode;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;


    @BindView(R.id.ll_customer_code)
    LinearLayout llCustomerCode;

    //浮动按钮
    @BindView(R.id.iv_drag)
    FloatingImageView iv_drag;

    private View notDataView;   //没有数据显示页
    private View errorView;     //错误显示页
    private View emptyView;     //空显示页
    /**
     * 列表适配器
     */
    private FinishWorkAdapter mAdapter;

    //扫码扫码动作
    private ScanBean scanBean;


    //托盘返回对象
    private JSONObject palletObject;

    private Unbinder unbinder;
    //是否需要显示客户
    private boolean needCustomer;
    //强制更改
    private int isChange=0;

    //是否已经检查数据
    private boolean isCheck = false;

    private String trackingNumber = "";
    private String customerCode = "";
    private  CommonDialog commonDialog;

    //托盘数据
    private List<JSONObject> tallyDataList = new ArrayList<>()   ;
    //托盘对象
    private JSONObject tallyInfo = null;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_fxy_tray;
    }

    @Override
    public boolean showToolBar() {
        return true;
    }

    @Override
    public boolean openEventBus() {
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle bundle) {

    }
    //finish的返回监听
    //这里的requestCode参数，就是上面设置的 1 ，当跳转的页面返回的时候，通过这个加以判断
    //resultCode ,这个参数是在跳转的页面里面规定的，它也是一个int类型的标志
    //第三个参数包含了返回的值
    //如果不需要所跳转的页面返回值，也就不需要这个方法了
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        XLog.e("requestCode："+requestCode);
//        XLog.e("resultCode："+resultCode);
        if (requestCode == 200 && resultCode == 200)//之前提到的两个标志，在这里显示出了作用
        {
        }else if (resultCode==0){
        }
    }


    /**
     * EventBus接收信息的方法，开启后才会调用(非粘性事件)
     *
     * @param event
     */
    @Override
    protected void EventBean(BaseEventBusBean event) {
//        XLog.e("----------接收返回--------------");
//        XLog.e("接收返回："+event.getEventCode());
        if (event != null && event.getEventCode() == EventCode.displacement_refresh){

        }
    }

    @Override
    public boolean isPlayMusic() {
        return true;
    }

    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("托盘入库");

        initAdapter();
        initData();
        initEdit();
        initDialog();
        //监听浮动按钮
        iv_drag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!iv_drag.isDrag()){
                    ActivityScanerCode.setScanerListener(mScanerListener);
                    ActivityScanerCode.intent2Activity(mContext, BaseConfig.COMMON_SCANNER_ONLY);
                }
            }
        });



    }


    private void initData(){

    }

    private void initDialog(){
        commonDialog = new CommonDialog(mContext, R.style.dialog, "need_customer", new CommonDialog.OnCloseListener() {
            @Override
            public void onClickCancel(Dialog dialog, boolean confirm) {

                dialog.dismiss();
            }
            @Override
            public void onClickSubmit(Dialog dialog, boolean confirm) {
                customerCode = commonDialog.contentTxt.getText().toString().trim();
                mtCustomerCode.setText(customerCode);
                //tv1.setText(name);
                dialog.dismiss();
                //校验数据
                if (validate()){
                    doPutIn();
                }

            }
        });

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //XLog.e("event:"+event.getKeyCode());
//        if ((event.getKeyCode()==KeyEvent.KEYCODE_DPAD_CENTER )  && event.getAction() == KeyEvent.ACTION_DOWN){
//            //按确定键
//            if(validate()){
//                doPutIn();
//            }
//            return true;
//        }
        return super.dispatchKeyEvent(event);
    }

    //监听按键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //XLog.e("监听按键："+keyCode);XLog.e(event);
        if (scanBean.getIsBroadcast()==0 && StoTongJNI.getIns(mContext).getEventFuction(keyCode)  == StoPdaKeyEvent.KEYCODE_SCAN
                && event.getRepeatCount() == 0) {

            if (StoTongJNI.getIns(mContext).GetScannerIsScanning()) {
//
            } else {
                StoTongJNI.getIns(mContext).SetScannerStart();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("HandlerLeak")
    Handler scanHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.obj != null) {

                String scanResult = msg.obj.toString().trim();
                if (!scanResult.isEmpty()){
                    setScanResult(scanResult);
                }
            }

        }

    };
    @Override
    public void onScanResults(String str) {
        Message msg = new Message();
        msg.obj = str;
        scanHandler.sendMessage(msg);


    }


    @Override
    public void onScanResults(String str, int type) {

    }
    /**
     * 定义广播接受
     */
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String scanResult = intent.getStringExtra(scanBean.getDataName());
            if (scanResult==null){return; }
            String scanStatus = "";
            if (!scanBean.getStatusName().isEmpty()){
                scanStatus = intent.getStringExtra(scanBean.getStatusName());
            }else{
                scanStatus = scanResult.isEmpty()? "" : "ok"; //有值 默认是扫码成功;
            }

            //新大陆(MT65,MT90) 需要手动关闭
            if (!scanBean.getActionStop().isEmpty()){
                Intent stopIntent = new Intent(scanBean.getActionStop());
                mContext.sendBroadcast(stopIntent);
            }

            if ("ok".equals(scanStatus)){
                setScanResult(scanResult);
            }else{
                showErrorToast(getString(R.string.scan_failed));
            }
        }
    };

    /**
     * 注册广播
     */
    private void initReceiver(){

        try {

            String scanStr = getScanSetting();
            scanBean = JsonUtil.getObject(scanStr, ScanBean.class);
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播

            if (is_broadcast ==1){
                IntentFilter mFilter = new IntentFilter(scanBean.getAction());
                this.registerReceiver(mReceiver, mFilter);
            }else{
                //不广播进行处理 jni模式
                String pdaBrand = StoTongJNI.getmPdaBrand();
                if (!pdaBrand.isEmpty()){
                    StoTongJNI.getIns(this).setmScanCB(this);
                    StoTongJNI.getIns(this).SetScannerOn();
                }
            }


        }catch (Exception e) {
            showErrorToast("获取扫码配置失败"+e.getMessage());
            XLog.e("获取扫码配置失败:" + e.getMessage());
        }
    }


    //统一按钮回调
    public void callbackEditor(View v){
        switch (v.getId()) {
            case R.id.et_ctn:
                if (!validate()){
                    break;
                }
            case R.id.et_order_no:
                doPutIn();
                break;
            default:
        }
    }





    private void initEdit() {
        List<EditText> list = new ArrayList<>();
        list.add(etOrderNo);
        list.add(etCtn);
        unifyEdit(list);
    }

    private OnRxScanerListener mScanerListener = new OnRxScanerListener() {
        @Override
        public void onSuccess(String type, Result result) {
            String scanResult = result.getText();
            switch (type){
                case BaseConfig.COMMON_SCANNER_ONLY:
                    setScanResult(scanResult);

                    break;
            }
        }
        @Override
        public void onFail(String type, String message) {

        }
    };

    //把扫描结果赋值
    private void setScanResult(String scanResult){
        if (commonDialog!=null && commonDialog.isShowing()){
            commonDialog.setContent(scanResult);
            return;
        }
        //获取焦点的view对象
        View view=getWindow().getDecorView().findFocus();
        //如果是EditText
        if(view instanceof EditText)
        {
            ((EditText) view).setText(scanResult);
            //执行回调
            callbackEditor(view);
        }
    }


    private void doPutIn() {


        try {
            trackingNumber = etOrderNo.getText().toString().trim();
            JSONObject param = new JSONObject();
            param.put("tracking_number",trackingNumber);
            param.put("ctn",etCtn.getText().toString().trim());

            if (needCustomer){
                param.put("customer_code",customerCode);
            }
            if (isChange>0){
                param.put("is_change",isChange);
            }

            if (!checkRepeat(Urls.FXY_SCAN_PALLET_TRACKING+(param.toString()))){return;}

            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_SCAN_PALLET_TRACKING)
                    .upJson(param)
                    .execute(new MyDialogCallback(this, true, true) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            super.onSuccess(response);
                            try {
                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                JSONObject result = new JSONObject();
                                if (bean.data!=null && !bean.data.isEmpty() && !bean.data.equals("[]")){
                                    result = new JSONObject(bean.data);
                                }


                                setPageViewData(result);
                                if(bean.code == 1){
                                    showSuccessToast(bean.msg);
                                    if (result.has("is_success") && result.getInt("is_success")==1){
                                        //提交数据
                                        clearData();
                                    }else{
                                        //标记已检查通过
                                        isCheck = true;
                                        //检查订单号
                                        etCtn.setEnabled(true);
                                        etCtn.requestFocus();
                                    }
                                }else{

                                    if (result.has("tag") && result.getString("tag").equals("need_customer")){
                                        needCustomer = true;
                                        commonDialog.setTitle("客户编号","请输入客户编号").setContent("").show();
                                        llCustomerCode.setVisibility(View.VISIBLE);
                                    }else if (result.has("is_change") && result.getInt("is_change")==1){
                                        new AlertDialog.Builder(mContext)
                                                .setTitle(R.string.dl_hint)
                                                .setMessage(bean.msg)
                                                .setNegativeButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                                                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        isChange = 1;
                                                        doPutIn();
                                                    }
                                                }).setPositiveButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //取消不做操作

                                            }
                                        }).show();
                                    }else {
                                        showWarningToast(bean.msg);
                                        //当输入编号时
                                        if (needCustomer){
                                            commonDialog.setTitle("客户编号","请输入客户编号").show();
                                            commonDialog.setContent(customerCode);
                                            showWarningToast("请输入客户编号");
                                        }
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("请求入库返回错误",e.getMessage());
                            }
                        }
                    });
        } catch (JSONException e) {
            showEmptyView("请求入库失败:"+e.getMessage());
            e.printStackTrace();
        }


    }

    /*
     * 校验必录
     */
    private boolean validate(){


        if(!checkNull(etOrderNo)){
            setEditTextFocused(etOrderNo,true);
            showWarningToast(etOrderNo.getHint().toString());
            return false;
        }
        if (needCustomer){
            if(customerCode.isEmpty()){
                commonDialog.setTitle("客户编号","请输入客户编号").setContent("").show();
                showWarningToast("请输入客户编号");
                return false;
            }
        }

        if (isCheck){
            if(!checkNull(etCtn)){
                setEditTextFocused(etCtn,true);
                showWarningToast(etCtn.getHint().toString());
                return false;
            }

            if (!isNumeric(etCtn.getText().toString().trim())){
                showWarningToast("请输入正整数");
                return false;
            }
        }



        return true;
    }

    private class FinishWorkAdapter extends BaseQuickAdapter<JSONObject, BaseViewHolder>{
        public FinishWorkAdapter(List<JSONObject> data){
            super(R.layout.item_putin_scan, data);
        }


        public void setNewData(List<JSONObject> tallyDataList) {
        }

        @Override
        protected void convert(BaseViewHolder helper, JSONObject item) {
            helper.addOnClickListener(R.id.ib_clear);//定义setOnItemChildClickListener 事件点击
            try {
                String number    = item.has("tracking_number")?item.getString("tracking_number"):"";
                helper.setText(R.id.tv_number,number);
                helper.getView(R.id.ib_clear).setVisibility(View.GONE);
            } catch (Exception e) {
                XLog.e("列表赋值错误",e);
                e.printStackTrace();
            }
        }
    }
    private void initAdapter(){
        emptyView = this.getLayoutInflater().inflate(R.layout.pager_empty, (ViewGroup) recyclerView.getParent(), false);
        errorView = this.getLayoutInflater().inflate(R.layout.pager_error, (ViewGroup) recyclerView.getParent(), false);
        notDataView = emptyView;

        mAdapter  = new FinishWorkAdapter(tallyDataList);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

    }

    /**
     * 显示
     * @param str
     */
    private void showList(String str){

    }

    private void setPageViewData(JSONObject jsonObject){
        try {
            String send_way = "";
            String putin_qty = "";
            if (jsonObject.has("list")){
                String listStr = jsonObject.getString("list");
                if ( !listStr.isEmpty() && !listStr.equals("[]")){
                    tallyDataList.clear();
                    JSONArray jsonArray = new JSONArray(listStr);
                    for (int i = 0;i < jsonArray.length(); i++){
                        JSONObject tallyObject = jsonArray.getJSONObject(i);
                        tallyDataList.add(tallyObject);
                    }
                    mAdapter.setNewData(tallyDataList);
                    mAdapter.notifyDataSetChanged();
                }
            }
            if (jsonObject.has("send_way")){
                send_way = jsonObject.getString("send_way");
            }
            if (jsonObject.has("qty")){
                putin_qty = String.valueOf(jsonObject.getInt("qty"));
            }
            mtTrackingNumber.setText(trackingNumber);
            mtSendWay.setText(send_way);
            mtPutinQty.setText(putin_qty);

        }catch (JSONException e) {
            XLog.e("获取理货缓存数据错误",e);
            e.printStackTrace();
        }
    }
    //清除订单信息
    private void clearData() {


        llCustomerCode.setVisibility(View.GONE);

        etOrderNo.setText("");
        needCustomer = false;
        isChange = 0;
        trackingNumber = "";
        customerCode = "";
        isCheck = false;
        etCtn.setText("");
        etOrderNo.setEnabled(true);
        etCtn.setEnabled(false);
        etOrderNo.requestFocus();


        setEditTextNormal(etCtn,true);
        setEditTextNormal(etOrderNo,true);
    }

    @OnClick({R.id.ib_ctn_clear,R.id.tv_edit_customer})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_edit_customer:
                commonDialog.setTitle("客户编号","请输入客户编号")
                        .setTypeCode("need_customer")
                        .setContent(mtCustomerCode.getText().toString())
                        .show();
                break;
            case R.id.ib_ctn_clear:

                break;
            default:
                break;
        }
    }

    /**
     * 统一设置Edit监听
     * @param  list
     */
    public void unifyEdit(List<EditText> list){
        for (int i=0;i<list.size();i++){
            EditText editText = list.get(i);

            LinearLayout linearLayout = (LinearLayout)editText.getParent();
            ImageButton imageButton = getChildImageButton(linearLayout);


            //监听按确定
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    XLog.e("actionId："+actionId);
                    if (event!=null){
                        XLog.e("KeyCode:"+event.getKeyCode()+"--ActionCode:"+event.getAction());
                    }

                    //|| (actionId == KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_ENTER )
                    if (actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE ||
                            (actionId == KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_ENTER )) {
                        if (v.getText().toString().trim().isEmpty()) {
                            setEditTextFocused(v,true);
                            showWarningToast(v.getHint().toString());
                            return true;
                        }else{
                            setEditTextNormal(v,true);
                        }
                        callbackEditor(v);
                        return false;
                    }
                    return  false;

                    //返回true，保留软键盘。false，隐藏软键盘
                }
            });
            editText.addTextChangedListener(new TextWatcher() {
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    EditText currentEditText = null;
                    ImageButton currentImage = null;
                    //获取焦点的view对象
                    View view=getWindow().getDecorView().findFocus();
                    //如果是EditText
                    if(view instanceof EditText){
                        currentEditText = (EditText) view;
                        currentImage = getChildImageButton((LinearLayout)currentEditText.getParent());
                    }

                    if (s.length() > 0  ) {

                        if (currentImage !=null ){
                            currentImage.setVisibility(View.VISIBLE);
                        }
                        if (currentEditText!=null){
                            setEditTextNormal(currentEditText,true);
                        }

                    } else {
                        if (currentImage !=null ){
                            currentImage.setVisibility(View.INVISIBLE);
                        }
                        if (currentEditText!=null){
                            setEditTextFocused(currentEditText,true);
                        }
                    }
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void afterTextChanged(Editable s) {

                }
            });

            if (imageButton !=null ){
                unifyClearEdit(imageButton);
            }
        }
    }


    @Override
    protected void onDestroy() {
        unbinder.unbind();


        super.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        initReceiver();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        try {
            //停止扫描
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播
            if (is_broadcast==0){
                StoTongJNI.getIns(mContext).SetScannerStop();
                StoTongJNI.getIns(mContext).SetScannerOff();
            }else{
                unregisterReceiver(mReceiver);
            }
        }catch (Exception e){
            XLog.e("销毁广播失败：",e.getMessage());
        }
    }


}
