package com.fxy.detection;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
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.util.JsonUtil;
import com.fxy.baselibrary.views.dialog.RxDialogZoomImageView;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.detection.bean.BtnInfoBean;
import com.fxy.detection.bean.ConfirmGoodsBean;
import com.fxy.detection.bean.ConfirmPartsBean;
import com.fxy.detection.bean.PartsBean;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.ToolUtils;
import com.fxy.view.FullyGridLayoutManager;
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.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 DetectionConfirmPartsMainActivity extends BaseActivity implements StoJNI.ScanCallBack {
    /**
     * 列表适配器
     */
    Context mContext = this;
    Activity mActivity = this;

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


    @BindView(R.id.ll_btn_center)
    LinearLayout llBtnCenter;


    @BindView(R.id.tv_content)
    TextView tvContent;


    @BindView(R.id.ll_btn_not_center)
    LinearLayout llBtnNotCenter;

    @BindView(R.id.ll_default)
    LinearLayout llDefault;

    @BindView(R.id.btn_default)
    TextView btnDefault;

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

    private JSONObject submitData = new JSONObject();

    private ConfirmGoodsBean confirmGoodsBean;

    private ConfirmPartsBean confirmPartsBean;



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

    private List<PartsBean> partsBeanList;

    private boolean isDefault = false;


    private float density = 0;


    private Unbinder unbinder;
    

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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {
        confirmGoodsBean = JsonUtil.jsonString2Bean(bundle.getString("data",""),ConfirmGoodsBean.class);
        confirmPartsBean = JsonUtil.jsonString2Bean(bundle.getString("confirm_parts",""),ConfirmPartsBean.class);
        partsBeanList = confirmPartsBean.getPartsList();
    }

    //finish的返回监听
    //这里的requestCode参数，就是上面设置的 1 ，当跳转的页面返回的时候，通过这个加以判断
    //resultCode ,这个参数是在跳转的页面里面规定的，它也是一个int类型的标志
    //第三个参数包含了返回的值
    //如果不需要所跳转的页面返回值，也就不需要这个方法了
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }


    /**
     * 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("装箱确认");
        density = ToolUtils.getDensity(this);
        initAdapter();
        initData();
        initEdit();
    }



    private void initData() {

        tvContent.setText(confirmPartsBean.getContent());
        for (int i =0;i<confirmPartsBean.getBtnsQue().size();i++){
            llBtnCenter.addView(getTextView(confirmPartsBean.getBtnsQue().get(i)));
        }
        for (int i =0;i<confirmPartsBean.getBtnsNoQue().size();i++){
            llBtnNotCenter.addView(getTextView(confirmPartsBean.getBtnsNoQue().get(i)));
        }

    }


    private void setBtnCenter(){

        boolean isSelect = false;
        for (int i=0;i<partsBeanList.size();i++){
            if (partsBeanList.get(i).getChecked()){
                isSelect = true;
            }
        }

        if (isDefault){

            llDefault.setVisibility(View.GONE);
            if (isSelect){
                llBtnCenter.setVisibility(View.VISIBLE);
                llBtnNotCenter.setVisibility(View.GONE);
            }else{
                llBtnCenter.setVisibility(View.GONE);
                llBtnNotCenter.setVisibility(View.VISIBLE);
            }


        }else{


            llDefault.setVisibility(View.VISIBLE);
            btnDefault.setText(isSelect?"缺配件":"不缺配件");
            llBtnCenter.setVisibility(View.GONE);
            llBtnNotCenter.setVisibility(View.GONE);
        }


    }

    private TextView  getTextView(BtnInfoBean btnInfoBean){
        TextView textView = new TextView(mContext);
        textView.setText(btnInfoBean.getTxt());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, // 宽度
                LinearLayout.LayoutParams.WRAP_CONTENT);// 高度

        int margin = ToolUtils.getDpValue(10,this);
        layoutParams.setMargins(margin,margin,margin,margin);


        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // 使用sp单位
        textView.setLayoutParams(layoutParams);
        textView.setPadding(margin,margin,margin,margin);
        textView.setTextColor(getResources().getColor(R.color.white));
        textView.setBackgroundResource(R.drawable.bg_orange_item);
        textView.setVisibility(View.VISIBLE);
        textView.setGravity(View.TEXT_ALIGNMENT_CENTER);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirmParts();
            }
        });
        return textView;
    }


    private void initAdapter(){

        int columnCount = 2; // 默认列数
// 根据屏幕宽度动态调整列数
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int screenWidth = displayMetrics.widthPixels;
// 这里可以根据屏幕宽度动态计算列数，例如每列200dp
        float dpWidth = screenWidth / (displayMetrics.densityDpi / 160f);
        columnCount = (int) (dpWidth / 200); // 假设每列期望宽度为200dp

        emptyView = this.getLayoutInflater().inflate(R.layout.pager_empty, (ViewGroup) recyclerView.getParent(), false);
        errorView = this.getLayoutInflater().inflate(R.layout.pager_error, (ViewGroup) recyclerView.getParent(), false);

        mAdapter  = new FinishWorkAdapter(partsBeanList);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        recyclerView.setLayoutManager(new FullyGridLayoutManager(mContext, columnCount, GridLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mAdapter);

         mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PartsBean partsBean = partsBeanList.get(position);
                partsBean.setChecked(!partsBean.getChecked());
                partsBeanList.set(position,partsBean);
                adapter.notifyDataSetChanged();
                isDefault = false;
                setBtnCenter();
            }
        });
    }


    public static class FinishWorkAdapter extends BaseQuickAdapter<PartsBean, BaseViewHolder> {

        public FinishWorkAdapter(List<PartsBean> data){
            super(R.layout.item_preview_image, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, PartsBean item) {
            //定义setOnItemChildClickListener 事件点击

            helper.addOnClickListener(R.id.cb_select);
            helper.addOnClickListener(R.id.ivp_img);


            ImageView  mImg = helper.getView(R.id.ivp_img);
            CheckBox cbSelect = helper.getView(R.id.cb_select);
            TextView tvName = helper.getView(R.id.tv_name);

            tvName.setText(item.getPartsName());


            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .placeholder(R.color.color_f6)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);

            Glide.with(helper.itemView.getContext())
                    .load(item.getUrl())
                    .apply(options)
                    .into(mImg);

            cbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    RelativeLayout parentLinearLayout = (RelativeLayout) buttonView.getParent();

                    View overlayView =  parentLinearLayout.findViewById(R.id.overlay_view);

                    // 当checkbox1的选中状态改变时执行
                    if (isChecked) {
                        overlayView.setVisibility(View.VISIBLE);
                    } else {
                        overlayView.setVisibility(View.GONE);
                    }
                }
            });

            mImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    XLog.e("--------setOnClickListener------");
                    int position = RecyclerView.NO_POSITION;
                    position = Math.max(position, 0);
//                List<LocalMedia> mediasList = new ArrayList<>();
//                for (int i = 0; i < mData.size(); i++) {
//                    LocalMedia media = new LocalMedia (mData.get(i).getUrl(), 0, PictureConfig.TYPE_IMAGE, "");
//                    media.setCut(false);
//                    mediasList.add(media);
//                }
//                com.luck.picture.lib.PictureSelector.create(mActivity).externalPicturePreview(position, mediasList);

                    RxDialogZoomImageView rxDialogZoomImageView = new RxDialogZoomImageView(mContext);
//                rxDialogZoomImageView.setImagePath(mData.get(position));
                    rxDialogZoomImageView.show();

                }
            });
        }
    }

    @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()) {

            
            default:
        }
    }

    private void initEdit() {


 
    }

    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);
            //执行回调
            callbackEditor(view);
        }
    }


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

        try {
            submitData.put("box_number",confirmGoodsBean.getBoxNumber());
            submitData.put("goods_id",confirmGoodsBean.getGoodsId());
            submitData.put("unit_code",confirmGoodsBean.getUnitCode());
            submitData.put("node_code",confirmGoodsBean.getNodeCode());
            submitData.put("tan_kuang",1);

            JSONArray steps = new JSONArray();

            for (int i=0;i<partsBeanList.size();i++){
                JSONObject item = new JSONObject();
                item.put("node_code",confirmGoodsBean.getNodeCode());
                item.put("attr_id",partsBeanList.get(i).getPartsId());
                steps.put(item);
            }

            submitData.put("steps",steps);




        } catch (JSONException e) {
            e.printStackTrace();
            showErrorToast(e.getMessage());
            return false;
        }


        return true;
    }

    /**
     * 检查打托信息
     */
    private void confirmParts() {

        if (!validate()){
            return;
        }


        String postJson = submitData.toString();;
        if (!checkRepeat(Urls.FXY_DETECTION_COMPLETED + (postJson))) {
            return;
        }
        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_COMPLETED).upJson(postJson)
                .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);
                                Intent intent = new Intent();
                                setResult(200, intent);//返回值，200 是改返回的标志，也会返回
                                finish();

                            } else {
                                showWarningToast(bean.msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("请求返回打托信息错误", e.getMessage());
                        }
                    }
                });


    }


    //清除订单信息
    private void clearData() {

    }

    @OnClick({R.id.btn_default})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_default:
                isDefault = true;
                setBtnCenter();
                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());
        }
    }


}
