package com.fxy.detection;

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.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

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.MarqueeTextView;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.common.ConfirmDialog;
import com.fxy.common.PictureSelectorUpload;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.detection.bean.BtnInfoBean;
import com.fxy.detection.bean.BaseBean;
import com.fxy.detection.bean.ConfirmGoodsBean;
import com.fxy.detection.bean.NeedPhotoBean;
import com.fxy.detection.bean.OptionsBean;
import com.fxy.detection.bean.RepairConfirmBean;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.CollUtil;
import com.fxy.utils.ToolUtils;
import com.fxy.view.FullyGridLayoutManager;
import com.google.gson.Gson;
import com.google.zxing.Result;
import com.luck.picture.lib.config.PictureConfig;
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.HashMap;
import java.util.List;
import java.util.Map;

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 DetectionWorkMainActivity extends BaseActivity implements StoJNI.ScanCallBack {
    /**
     * 列表适配器
     */
    Context mContext = this;


    @BindView(R.id.btn_result)
    TextView btnResult;

    @BindView(R.id.mt_box_number)
    MarqueeTextView mtBoxNumber;

    @BindView(R.id.mt_unit_code)
    MarqueeTextView mtUnitCode;

    @BindView(R.id.ll_details)
    LinearLayout llDetails;

    @BindView(R.id.ll_step2)
    LinearLayout llStep2;


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


    @BindView(R.id.result_recyclerview)
    RecyclerView resultRecyclerview;


    @BindView(R.id.btn_suspend)
    TextView btnSuspend;

//    @BindView(R.id.btn_confirm)
//    TextView btnConfirm;
//
    @BindView(R.id.ll_recycler_view)
    LinearLayout llRecyclerView;


    private BaseQuickAdapter adapter;
    private RecyclerAdapter recyclerAdapter;
    private RepairAdapter repairAdapter;

    private BaseBean baseBean ;
    private ConfirmGoodsBean confirmGoodsBean;
    private List<OptionsBean> optionsBeanList;
    private List<OptionsBean> resultOptionsList = new ArrayList<>();

    private String nodeCode = "";

    private String currentPicture = "";

    private HashMap<Integer,String> mapStepsAttrId  = new HashMap<>();

    private HashMap<String,PictureSelectorUpload> mapPictureSelector = new HashMap<>();

    private HashMap<String,Object> mapInput = new HashMap<>();
    private HashMap<String,String> mapUploadAttrId = new HashMap<>();

    private JSONObject submitData = new JSONObject();

    //是否中断
    private String interruptCause = "";


    private ConfirmDialog confirmDialog;

    private ScanBean scanBean;

    private Unbinder unbinder;



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

    @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);
        nodeCode = confirmGoodsBean.getNodeCode();
    }

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

        // 图片选择结果回调
        if (resultCode == RESULT_OK) {
            // 图片选择结果回调
            if (requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == PictureConfig.REQUEST_CAMERA) {
                PictureSelectorUpload filedUpload = mapPictureSelector.get(currentPicture);
                if (filedUpload != null){
                    filedUpload.getSelectImg(data);
                }
            }
        }else if (requestCode == 200)
        {
            //
            if (resultCode == 200){
                stepInitData();
            }else{
                finish();
            }

        }

    }


    /**
     * 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("");
        stepInitData();
    }


    private void stepInitData(){
        initData();
    }

    private void initData() {
        String postJson = (new Gson()).toJson(confirmGoodsBean);
        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_ASSIGN_DATA).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) {
                                baseBean = JsonUtil.jsonString2Bean(bean.data,BaseBean.class);
                                setTitleName(baseBean.getNodeName());

                                //更新页面显示数据
                                mtBoxNumber.setText(baseBean.getBoxNumber());
                                mtUnitCode.setText(baseBean.getUnitCode());
                                confirmGoodsBean.setNodeName(baseBean.getNodeName());

                                optionsBeanList = baseBean.getOptions();
                                btnResult.setText(baseBean.getResult());

                                JSONObject jsonObject = new JSONObject(bean.data);
                                llStep2.setVisibility(nodeCode.equals("step_3")?View.VISIBLE:View.GONE);


                                if (nodeCode.equals("step_4") && jsonObject.has("tan_kuang") && !jsonObject.getString("tan_kuang").equals("[]")){
                                    Bundle bundle = new Bundle();
                                    bundle.putString("data",(new Gson()).toJson(confirmGoodsBean));
                                    bundle.putString("confirm_parts",jsonObject.getString("tan_kuang"));
                                    intentPageResult(DetectionWorkMainActivity.this, DetectionConfirmPartsMainActivity.class, bundle,200);
                                }

                                initAdapter();

                            } else {
                                showWarningToast(bean.msg);

                                //获取数据失败
                                Intent intent = new Intent();
                                setResult(199, intent);
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("请求返回错误", e.getMessage());
                        }
                    }
                });

    }


    private void initAdapter() {


        int itemCount = 2;

        if (nodeCode.equals("step_2") || nodeCode.equals("step_3")){
            itemCount = 3;
        }else if (nodeCode.equals("step_4")){
            itemCount = 1;
        }

        XLog.e("");
        //recyclerAdapter = new RecyclerAdapter(baseBean,  mContext);
        adapter = new BaseQuickAdapter<OptionsBean, BaseViewHolder>(R.layout.item_card, optionsBeanList){
            @Override
            protected void convert(BaseViewHolder helper, OptionsBean item) {

                if (item.getType().equals("camera")){
                    addCamera(helper,item);
                }else{
                    switch (baseBean.getNodeCode()){
                        case "step_1":
                        case "step_2":
                        case "step_3":
                            addTab(helper,item);
                            break;
                        case "step_4":
                            if (resultOptionsList != null && recyclerAdapter!=null){
                                resultOptionsList = new ArrayList<>();
                                recyclerAdapter.notifyDataSetChanged();
                            }

                            addTab2(helper,item);
                        default:
                            break;
                    }
                }


            }
        };
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, itemCount, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);


        // 设置点击事件监听器
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (baseBean.getNodeCode()){
                    case "step_2":
                    case "step_3":
                        setSelectOptions(position) ;
                        break;
                }
            }
        });

        //处理结果
        repairAdapter = new RepairAdapter(resultOptionsList,  mContext);
        FullyGridLayoutManager resultManager = new FullyGridLayoutManager(this, 1, GridLayoutManager.VERTICAL, false);
        resultRecyclerview.setLayoutManager(resultManager);
        resultRecyclerview.setAdapter(repairAdapter);

    }

    private void serResultOptionsList(){
        //第三步需要显示结果
        if (nodeCode.equals("step_3")){
            resultOptionsList.clear();
            for (int i=0;i<optionsBeanList.size();i++){
                if (optionsBeanList.get(i).getChecked()){
                    resultOptionsList.add(optionsBeanList.get(i));
                }
            }
            repairAdapter.notifyDataSetChanged();
        }
    }
    /**
     * 处理选中
     * @param optionsInx 第几个元素
     */
    private void setSelectOptions(final int optionsInx){
        OptionsBean tmpOptionsBean = optionsBeanList.get(optionsInx);
        final boolean checkedOld = tmpOptionsBean.getChecked();
        String result = tmpOptionsBean.getResult();
        List<BtnInfoBean> btnBeanList = tmpOptionsBean.getBtns();
        List<NeedPhotoBean> needPhotoBeanList = tmpOptionsBean.getNeedPhoto();

        //定义是否需要重置
        boolean needReset = true;
        // 需要弹窗
        if (btnBeanList.size()>0 && !checkedOld){
            String showContent = "";
            List<RepairConfirmBean> confirmBeanList = tmpOptionsBean.getConfirm();
            for (int i = 0; i < confirmBeanList.size(); i++) {
                if (!showContent.isEmpty()){
                    showContent = showContent.concat("\n");
                }
                showContent = showContent.concat(confirmBeanList.get(i).getName())
                        .concat(confirmBeanList.get(i).getTxt());
            }
            confirmDialog = new ConfirmDialog(mContext,btnBeanList);
            confirmDialog.setOnCallbackListener(new ConfirmDialog.OnCallbackListener() {
                @Override
                public void OnCallback(String v,int position) {
                    OptionsBean tmpOptionsBean = optionsBeanList.get(optionsInx);
                    tmpOptionsBean.setChecked(true);
                    tmpOptionsBean.setResult(v);
                    optionsBeanList.set(optionsInx,tmpOptionsBean);
                    confirmDialog.dismiss();

                    //单选取消
                    if (baseBean.getOptionsType().equals("radio")){
                        setCancelSelectOptions(optionsInx);
                    }

                    adapter.notifyDataSetChanged();

                    serResultOptionsList();
                }
            });
            confirmDialog.showDialog(showContent);
            needReset = false;
        }else{
            result = "";
            tmpOptionsBean.setChecked(!checkedOld);
        }

        LinearLayout pictureLinearLayout = llRecyclerView;
        //需要拍照
        if (needPhotoBeanList.size()>0){
            editPictureView(tmpOptionsBean,pictureLinearLayout,checkedOld);
        }


        //需要重置
        if (needReset){
            if (baseBean.getOptionsType().equals("radio")){
                setCancelSelectOptions(optionsInx);
            }
            tmpOptionsBean.setResult(result);
            optionsBeanList.set(optionsInx,tmpOptionsBean);
            adapter.notifyDataSetChanged();
        }
        serResultOptionsList();
    }

    /**
     *设置选项
     * @param optionsInx 第几个选项
     */
    private void setCancelSelectOptions(int optionsInx){
        for (int i=0;i<optionsBeanList.size();i++){

            if (optionsInx==i){
                continue;
            }
            OptionsBean tmpOptionsBean = optionsBeanList.get(i);
            if (tmpOptionsBean.getNeedPhoto().size()>0){
                editPictureView(tmpOptionsBean,llRecyclerView,true);
            }

            tmpOptionsBean.setResult("");
            tmpOptionsBean.setChecked(false);
            optionsBeanList.set(optionsInx,tmpOptionsBean);
        }
    }

    /**
     * 编辑图片上传视图
     * @param tmpOptionsBean  Bean
     * @param pictureLinearLayout  视图
     * @param isDel  是否删除
     */
    private void editPictureView(OptionsBean tmpOptionsBean, LinearLayout pictureLinearLayout,boolean isDel){

        for (int i=0;i<tmpOptionsBean.getNeedPhoto().size();i++){

            NeedPhotoBean needPhotoBean = tmpOptionsBean.getNeedPhoto().get(i);
            String tagKey = getTagKey(needPhotoBean.getFieldKey());
            if (isDel){

                if (mapPictureSelector!=null){
                    mapPictureSelector.remove(needPhotoBean.getFieldKey());
                    mapUploadAttrId.remove(needPhotoBean.getFieldKey());
                }
                // 或者，如果你需要遍历并删除满足某个条件的视图
                for (int j = 0; j < pictureLinearLayout.getChildCount(); j++) {
                    View child = pictureLinearLayout.getChildAt(j);
                    if (tagKey.equals(child.getTag().toString())) {
                        pictureLinearLayout.removeViewAt(j);
                    }
                }
            }else{
                addPictureSelectorUpload(pictureLinearLayout,needPhotoBean,tmpOptionsBean.getAttrId());
            }

        }
    }


    //添加拍照
    private void addCamera(BaseViewHolder helper, OptionsBean item){
        LinearLayout clModel = helper.getView(R.id.cl_model);
        for (int i=0;i<item.getNeedPhoto().size();i++){
            addPictureSelectorUpload(clModel,item.getNeedPhoto().get(i),item.getAttrId());
        }

    }

    //添加
    private void addTab(BaseViewHolder helper, OptionsBean item){
        LinearLayout clModel = helper.getView(R.id.cl_model);

        // 检查LinearLayout是否不为null且包含子视图
        if (clModel.getChildCount() > 0) {
            clModel.removeAllViews();
        }


        View itemView =  View.inflate(mContext, R.layout.item_card_tab, null);
        TextView tvTitle = itemView.findViewById(R.id.tv_title);
        TextView tvDescribe = itemView.findViewById(R.id.tv_describe);





        if (item.getTitle().isEmpty()){
            tvTitle.setVisibility(View.GONE);
        }else{
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(item.getTitle());
        }
        tvDescribe.setText(item.getContent());

        if (item.getChecked()){
            itemView.setBackgroundResource(R.drawable.bg_blue_item);
        }else{
            itemView.setBackgroundResource(R.drawable.bg_white_et);
        }

        clModel.addView(itemView);


    }

    //添加
     private void addTab2(BaseViewHolder helper, OptionsBean item){
        LinearLayout clModel = helper.getView(R.id.cl_model);

        // 检查LinearLayout是否不为null且包含子视图
        if (clModel.getChildCount() > 0) {
            clModel.removeAllViews();
        }


        View itemView =  View.inflate(DetectionWorkMainActivity.this, R.layout.item_card_tab_two, null);
        TextView tvContent = itemView.findViewById(R.id.tv_content);
        LinearLayout llInput = itemView.findViewById(R.id.ll_input);
        LinearLayout llBtnCenter = itemView.findViewById(R.id.ll_btn_center);

        LinearLayout llTip = itemView.findViewById(R.id.ll_tip);
        TextView tvTip = itemView.findViewById(R.id.tv_tip);
        EditText etInput = itemView.findViewById(R.id.et_input);


        tvContent.setText(item.getContent());

        if (item.getTip().isEmpty()){
            tvTip.setText("");
            llTip.setVisibility(View.GONE);

        }else{
            tvTip.setText(item.getTip());
            llTip.setVisibility(View.VISIBLE);
        }


        final String inputName = item.getName();
        if (item.getType().equals("input")){
            llInput.setVisibility(View.VISIBLE);

            if (mapInput.containsKey(inputName)){
                etInput.setText(mapInput.get(inputName).toString());
            }
            etInput.addTextChangedListener(new TextWatcher() {
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    mapInput.put(inputName,s.toString().trim());
                }
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                public void afterTextChanged(Editable s) {

                }
            });

        }else{
            llInput.setVisibility(View.GONE);
        }


        if (item.getBtns().size()>0){

            llBtnCenter.setVisibility(View.VISIBLE);
            int margin = ToolUtils.getDpValue(10,this);

            for (int i=0;i<item.getBtns().size();i++){
                BtnInfoBean btnInfoBean = item.getBtns().get(i);

                TextView textViewBtn = (TextView)llBtnCenter.getChildAt(i);
                textViewBtn.setText(btnInfoBean.getTxt());
                textViewBtn.setVisibility(View.VISIBLE);

                textViewBtn.setTag((new Gson()).toJson(btnInfoBean));

                textViewBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        String tagVal = view.getTag().toString();
                        BtnInfoBean itemBean= JsonUtil.jsonString2Bean(tagVal, BtnInfoBean.class);


                        LinearLayout llBtnModule = (LinearLayout)view.getParent();
                        for (int j = 0; j < llBtnModule.getChildCount(); j++) {
                            View child = llBtnModule.getChildAt(j);
                            String tmpTag = (String) child.getTag();
                            if (!tagVal.equals(tmpTag)){
                                child.setBackgroundResource(R.drawable.text_border);
                                BtnInfoBean tmp = JsonUtil.jsonString2Bean(child.getTag().toString(), BtnInfoBean.class);
                                tmp.setChecked(false);
                                child.setTag((new Gson()).toJson(tmp));
                            }
                        }


                        if (itemBean.getChecked()){
                            view.setBackgroundResource(R.drawable.text_border_select);
                        }else{
                            view.setBackgroundResource(R.drawable.text_border);
                        }
                        itemBean.setChecked(!itemBean.getChecked());
                        view.setTag((new Gson()).toJson(itemBean));





                        LinearLayout itemRoot = (LinearLayout)view.getParent().getParent();
                        LinearLayout llUploadView = itemRoot.findViewById(R.id.ll_upload_view);


                        List<NeedPhotoBean> needPhotoBeanList = itemBean.getNeedPhotos();
                        String attrId = itemBean.getValue();
                        XLog.e("点击按钮");


                        for (int i=0;i<needPhotoBeanList.size();i++){
                            NeedPhotoBean needPhotoBean = needPhotoBeanList.get(i);
                            String tagKey = getTagKey(needPhotoBean.getFieldKey());
                            if (mapPictureSelector.containsKey(needPhotoBean.getFieldKey())){
                                mapPictureSelector.remove(needPhotoBean.getFieldKey());
                                mapUploadAttrId.remove(needPhotoBean.getFieldKey());
                                // 或者，如果你需要遍历并删除满足某个条件的视图
                                for (int j = 0; j < llUploadView.getChildCount(); j++) {
                                    View child = llUploadView.getChildAt(j);
                                    if (tagKey.equals(child.getTag().toString())) {
                                        llUploadView.removeViewAt(j);
                                    }
                                }
                            }else{
                                addPictureSelectorUpload(llUploadView,needPhotoBean,attrId);
                            }
                        }

                    }
                });





            }

        }

        clModel.addView(itemView);

    }

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

            }
        });
        return textView;
    }


    private String getTagKey(String key){
       return  "recyclerview".concat(key);
    }

    public void addPictureSelectorUpload(LinearLayout linearLayout,NeedPhotoBean needPhotoBean,String attrId){
        String tagKey = getTagKey(needPhotoBean.getFieldKey());
        View itemPictureSelector = View.inflate(mContext, R.layout.item_picture_selector, null);
        TextView tvPicturesTitle = itemPictureSelector.findViewById(R.id.tv_pictures_title);
        tvPicturesTitle.setText(needPhotoBean.getFieldKey());
        RecyclerView rvLabelShowImg = (RecyclerView)itemPictureSelector.findViewById(R.id.recyclerview);
        itemPictureSelector.setTag(tagKey);
        linearLayout.addView(itemPictureSelector);
        PictureSelectorUpload tmpPictureSelector  = setItemPicture(needPhotoBean.getFieldKey(),rvLabelShowImg,needPhotoBean.getLimit(),PictureConfig.TYPE_IMAGE);
        mapPictureSelector.put(needPhotoBean.getFieldKey(),tmpPictureSelector);
        mapUploadAttrId.put(needPhotoBean.getFieldKey(),attrId);
    }

    /**
     * 设置多个上传文件
     * @param actionType String
     * @param showImg RecyclerView
     */
    private PictureSelectorUpload setItemPicture(String actionType,RecyclerView showImg,int maxNum,int pictureType){
        PictureSelectorUpload pictureUpload = new PictureSelectorUpload(DetectionWorkMainActivity.this,showImg,"detection",maxNum,pictureType);
        pictureUpload.setActionType(actionType);
        pictureUpload.setCompress(true,100,500);
        pictureUpload.setOnlyCamera(true);
        pictureUpload.setProgressType(2);
        //showImg.onTouchEvent()

        pictureUpload.setOnChangeListener(new PictureSelectorUpload.UploadChangeListener() {
            @Override
            public void uploadResult(boolean State,String actionType) {
                if (State) {

                }
            }

            @Override
            public void uploadActionType(String actionType) {
                System.out.println("actionType："+actionType);
                currentPicture = actionType;
            }
        });
        return  pictureUpload;
    }

    @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 void doCompleted() {
        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) {
                                if (confirmDialog!=null){
                                    confirmDialog.dismiss();
                                }
                                showSuccessToast(bean.msg);
                                JSONObject jsonObject = new JSONObject(bean.data);
                                if (!jsonObject.has("next_step") || jsonObject.getString("next_step").isEmpty()){
                                    finish();
                                }else{
                                    nodeCode = jsonObject.getString("next_step");
                                    confirmGoodsBean.setNodeCode(nodeCode);
                                    stepInitData();
                                }


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

    /**
     * @param type int 1、库位，2、箱号
     * @return
     */
    private String formatParam(int type) {
        JSONObject jsonObject = new JSONObject();
        try {

        } catch (Exception e) {
            e.printStackTrace();
            XLog.e("组装数据失败");
        }
        return jsonObject.toString();
    }

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

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

            if (!confirmGoodsBean.getIsConfirm().isEmpty()){
                submitData.put("is_confirm",confirmGoodsBean.getIsConfirm());
            }

            if (!interruptCause.isEmpty()){
                submitData.put("zhong_duan",interruptCause);
                return true;
            }


            JSONArray steps = new JSONArray();

            //检查拍照上传
            for (Map.Entry<String, String> entry : mapUploadAttrId.entrySet()) {
                String fieldKey = entry.getKey();
                ArrayList<String> urlList = mapPictureSelector.get(fieldKey).getPhotoList();
                if (urlList.size()==0){
                    showErrorToast(fieldKey+"需要拍照");
                    return  false;
                }
                JSONObject item = new JSONObject();
                item.put("node_code",nodeCode);
                item.put("attr_id",entry.getValue());
                item.put("field_key",fieldKey);
                item.put("url",(new Gson()).toJson(urlList));
                steps.put(item);
            }


            for (int j=0;j<optionsBeanList.size();j++){
                OptionsBean itemOptions = optionsBeanList.get(j);
                //拍照 不会设置选中跟设置返回值
                if (itemOptions.getChecked() && !itemOptions.getResult().isEmpty()){
                    JSONObject item = new JSONObject();
                    item.put("node_code",nodeCode);
                    item.put("attr_id",itemOptions.getAttrId());
                    item.put("field_key",itemOptions.getResult());
                    steps.put(item);
                }


            }

            //输入框的值
            for (Map.Entry<String, Object> entry : mapInput.entrySet()) {
                submitData.put(entry.getKey(),entry.getValue());
            }




            submitData.put("steps",steps);


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


        return true;
    }



    private static class RecyclerAdapter extends BaseQuickAdapter<OptionsBean, BaseViewHolder>{
        private Context mContext;
        private BaseBean mBaseBean;
        public RecyclerAdapter(BaseBean baseBean,Context context) {
            super(R.layout.item_card, baseBean.getOptions());
            mContext = context;
            mBaseBean = baseBean;
        }


        @Override
        protected void convert(BaseViewHolder helper, OptionsBean item) {

            switch (mBaseBean.getNodeCode()){
                case "step_1":
                case "step_2":
                case "step_3":
                    if (mBaseBean.getOptionsType().equals("camera")){
                        addCamera(helper,item);
                    }else{
                        addTab(helper,item);
                    }

                    break;
                default:
                    break;
            }

        }

        private void addCamera(BaseViewHolder helper, OptionsBean item){
            LinearLayout clModel = helper.getView(R.id.cl_model);

        }


        //添加
        private void addTab(BaseViewHolder helper, OptionsBean item){


            View itemView =  View.inflate(mContext, R.layout.item_card_tab, null);
            TextView tvTitle = itemView.findViewById(R.id.tv_title);
            TextView tvDescribe = itemView.findViewById(R.id.tv_describe);

            LinearLayout clModel = helper.getView(R.id.cl_model);

            if (item.getTitle().isEmpty()){
                tvTitle.setVisibility(View.GONE);
            }else{
                tvTitle.setVisibility(View.VISIBLE);
                tvTitle.setText(item.getTitle());
            }
            tvDescribe.setText(item.getContent());
            clModel.addView(itemView);

            if (item.getChecked()){
                clModel.setBackgroundResource(R.drawable.bg_blue_item);
            }else{
                clModel.setBackgroundResource(R.drawable.bg_white_et);
            }
        }


    }

    private static class RepairAdapter extends BaseQuickAdapter<OptionsBean, BaseViewHolder>{
        private Context mContext;
        private TextView tvStatus;
        private TextView tvTitle;
        private LinearLayout llItemCenter;
        public RepairAdapter(List<OptionsBean> listOptionsBean,Context context) {
            super(R.layout.item_repair, listOptionsBean);
            mContext = context;
        }

        @SuppressLint("ResourceAsColor")
        @Override
        protected void convert(BaseViewHolder helper, OptionsBean item) {
            tvTitle = helper.getView(R.id.tv_title);
            tvStatus = helper.getView(R.id.tv_status);
            llItemCenter = helper.getView(R.id.ll_item_center);
            // 检查LinearLayout是否不为null且包含子视图
            if (llItemCenter.getChildCount() > 0) {
                llItemCenter.removeAllViews();
            }

            tvTitle.setText(item.getTitle());
            tvStatus.setText(item.getResult());
            tvStatus.setVisibility(View.VISIBLE);
            if (item.getResult().equals("未解决")){
                tvStatus.setTextColor(R.color.md_deep_orange_A700); // 设置文本颜色
            }

            for (int i=0;i<item.getConfirm().size();i++){
                RepairConfirmBean repairConfirmBean = item.getConfirm().get(i);
                String content = repairConfirmBean.getName().concat(repairConfirmBean.getTxt());
                // 创建一个新的TextView实例
                TextView textView = new TextView(mContext); // 这里的this指的是当前的Context，比如Activity或Fragment
                textView.setText(content);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40); // 设置文本大小，使用SP单位以支持不同屏幕密度
                textView.setTextColor(R.color.black_3d3d3d); // 设置文本颜色
                textView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, // 宽度
                        LinearLayout.LayoutParams.WRAP_CONTENT)// 高度
                );
                llItemCenter.addView(textView);
            }


        }
    }




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

    }

    @OnClick({R.id.btn_finish,R.id.btn_suspend,R.id.btn_result})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_finish:
            case R.id.btn_result:
                doCompleted();
                break;
            case R.id.btn_suspend:

                List<BtnInfoBean> listBtn = baseBean.getZhongDuan().getBtns();
                confirmDialog = new ConfirmDialog(mContext,listBtn);
                confirmDialog.setOnCallbackListener(new ConfirmDialog.OnCallbackListener() {
                    @Override
                    public void OnCallback(String v,int position) {
                        interruptCause = v;



                         doCompleted();
                    }
                });
                confirmDialog.showDialog(baseBean.getZhongDuan().getContent());

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


}
