package com.fxy.fms.putIn;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.google.zxing.Result;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
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.R;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.view.FloatingImageView;

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

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;

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

public class PutAwayMainActivity 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.iv_drag)
    FloatingImageView iv_drag;

    @BindView(R.id.tv_already_location)
    TextView tvAlreadyLocation;

    @BindView(R.id.ms_location_list)
    MaterialSpinner LocationSpinner;



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

    protected String action;

    //订单信息对象
    private JSONObject inboundObject;

    private Unbinder unbinder;


    //库位列
    private JSONArray locationList;

    private Integer selectId=0;


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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {
        action = bundle.getString("action","putaway");
    }

    /**
     * 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("扫描上架");
        initEdit();

        //loadServiceData();
        initData();

        //监听浮动按钮
        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(){

        try {
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_LOCATION_LIST)
                    .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);
                                List<String> spinnerList = new ArrayList<String>();
                                spinnerList.add("请选择上架库位");
                                if(bean.code == 1){
                                    //JSONObject data = new JSONObject(bean.data);
                                    locationList = new JSONArray(bean.data);
                                    for (int i = 0;i < locationList.length(); i++){
                                        JSONObject jsonObject =locationList.getJSONObject(i);
                                        spinnerList.add(jsonObject.getString("name"));
                                    }
                                    LocationSpinner.setItems(spinnerList);

                                }else{
                                    showWarningToast(bean.msg);
                                }

                                LocationSpinner.setSelectedIndex(selectId);
                                initSpinner();

                            } catch (Exception e) {
                                showWarningToast("请配置上架库位基础数据");
                                e.printStackTrace();
                                XLog.e("获取上架库位解析错误",e.getMessage());
                            }
                        }
                    });
        }catch (Exception e){
            showWarningToast(e.getMessage());
            XLog.e("请求上架库位信息错误:",e);
        }
    }

    /**
     *  初始化下拉框控件值
     */
    private void initSpinner() {
        LocationSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                // XLog.e(id);XLog.e(item);
                selectId = position;
                if (position>0){
                    setEditTextNormal(LocationSpinner,false);
                }
            }
        });
    }






    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //XLog.e("event:"+event.getKeyCode());
        if ((event.getKeyCode()==KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode()==KeyEvent.KEYCODE_ENTER )  && event.getAction() == KeyEvent.ACTION_DOWN){
            //按确定键
            if(this.validate()){
                addPutAway();
            }
        }
        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());
        }
    }

    private void initEdit() {

        //
        etOrderNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String orderNo = etOrderNo.getText().toString().trim();
                    if (StringUtils.isEmpty(orderNo)) {
                        setEditTextFocused(v,true);
                        showWarningToast(v.getHint().toString());
                        return false;
                    }
                    getInboundInfo();//获取订单信息
                    return false;
                }
                return false;
            }
        });
        etOrderNo.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                s = s.toString().trim();
                if (s.length() > 0 ) {
                    if (etOrderNo.isEnabled()){
                        ibOrderNoClear.setVisibility(View.VISIBLE);
                    }
                    setEditTextNormal(etOrderNo,true);

                } else {
                    ibOrderNoClear.setVisibility(View.INVISIBLE);
                    setEditTextFocused(etOrderNo,true);
                }
            }

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

            public void afterTextChanged(Editable s) {

            }
        });
        ibOrderNoClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etOrderNo.requestFocus();
                etOrderNo.getText().clear();
            }
        });



    }

    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){
        //获取焦点的view对象
        View view=getWindow().getDecorView().findFocus();
        //如果是EditText
        if(view instanceof EditText)
        {
            ((EditText) view).setText(scanResult);

            switch (view.getId()) {
                case R.id.et_order_no:
                    getInboundInfo();
                    break;
            }


        }
    }


    private void getInboundInfo(){
        final String orderNumber = etOrderNo.getText().toString().trim();
        if (orderNumber.isEmpty()){
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("order_number",orderNumber);
            jsonObject.put("action",action);
            if (!checkRepeat(Urls.FMS_CHECK_ORDER+(jsonObject.toString()))){
                Toast.makeText(this, getString(R.string.error_data_processed), Toast.LENGTH_LONG).show();
                return;
            }

            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_CHECK_ORDER).upJson(jsonObject)
                    .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);
                                if(bean.code == 1){
                                    showSuccessToast(bean.msg);
                                    inboundObject = new JSONObject(bean.data);
                                    tvAlreadyLocation.setText(inboundObject.getString("domestic_wms_location"));
                                }else{
                                    inboundObject = null;
                                    showWarningToast(bean.msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                showEmptyView("入库订单信息解析错误:"+e.getMessage());
                                XLog.e("获取入库订单信息解析错误",e.getMessage());
                            }
                        }
                    });
        }catch (Exception e){
            inboundObject = null;
            XLog.e("请求出库订单信息错误:",e);
        }
    }


    private void addPutAway() {

        //校验数据
        if (!validate()){
            return;
        }

        String orderNumber = etOrderNo.getText().toString().trim();


        try {
            //locationList.getJSONObject(i);
            JSONObject jsonObject = locationList.getJSONObject(selectId-1);
            String locationNumber = jsonObject.getString("code");

            JSONObject param = new JSONObject();
            param.put("order_number",orderNumber);
            param.put("domestic_wms_location",locationNumber);

            if (!checkRepeat(Urls.FMS_PUT_AWAY+(param.toString()))){return;}
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_PUT_AWAY).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);
                                if(bean.code == 1){
                                    showSuccessToast(bean.msg);
                                    clearData();
                                }else{
                                    showWarningToast(bean.msg);
                                }
                            } catch (Exception e) {
                                showErrorToast("数据解析失败"+e.getMessage());//不需要翻译
                                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 (selectId==0){
            setEditTextFocused(LocationSpinner,false);
            showWarningToast("请选择上架库位");
            return false;
        }
        return true;
    }


    //清除订单信息
    private void clearData() {
        etOrderNo.setText("");
        etOrderNo.requestFocus();
    }

    @OnClick({R.id.ima_or_code,R.id.btn_confirm})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_confirm:
                addPutAway();

                break;
            case R.id.ima_or_code:
                if(etOrderNo.isEnabled()){
                    etOrderNo.requestFocus();
                    ActivityScanerCode.setScanerListener(mScanerListener);
                    ActivityScanerCode.intent2Activity(mContext, BaseConfig.COMMON_SCANNER_ONLY);
                }
                break;
            default:
                break;
        }
    }

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


}
