package com.fxy.workOrder;

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.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


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.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.common.PictureSelectorUpload;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;

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.JSONException;
import org.json.JSONObject;


import java.util.ArrayList;

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 WorkOrderOptMainActivity extends  BaseActivity implements StoJNI.ScanCallBack{

    /**
     * 列表适配器
     */
    Context mContext = this;

    @BindView(R.id.ll_take_picture)
    LinearLayout llTakePicture;

    @BindView(R.id.ll_audio_area)
    LinearLayout llAudioArea;

    @BindView(R.id.ll_remark_info)
    LinearLayout llRemarkInfo;

    @BindView(R.id.btn_confirm)
    TextView btnConfirm;



    @BindView(R.id.et_remark)
    EditText etRemark;



    private ArrayList photoList =new ArrayList<>();
    private ArrayList speakList =new ArrayList<>();

    private PictureSelectorUpload currentUpload;
    private PictureSelectorUpload pictureSelectorUpload;
    private PictureSelectorUpload audioSelectorUpload;
    //
    //扫码扫码动作
    private ScanBean scanBean;



    protected String action;

    private boolean isOk = true;

    private Unbinder unbinder;

    private JSONObject postParam = new JSONObject();

    private String actionUrl = "";
    private String trackingNumber = "";

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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {
        XLog.e("接收数据解析：",bundle);
        action = bundle.getString("action","add");
        trackingNumber = bundle.getString("tracking_number","");
        actionUrl = action.equals("handle") ? Urls.FXY_WORK_FINISH : Urls.FXY_ADD_WORK;
    }



    //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) {// 图片选择结果回调
                currentUpload.getSelectImg(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(action.equals("handle") ? "处理工单":"添加工单");

        initEdit();
        iniData();


        RecyclerView rvShowImg = (RecyclerView)llTakePicture.findViewById(R.id.rv_show_img);
        RecyclerView rvShowAudio = (RecyclerView)llAudioArea.findViewById(R.id.rv_show_img);
        pictureSelectorUpload  = setItemPicture("photo",rvShowImg,9,PictureConfig.TYPE_IMAGE);
        audioSelectorUpload  = setItemPicture("audio",rvShowAudio,1,PictureConfig.TYPE_AUDIO);



        audioSelectorUpload.setPictureType(PictureConfig.TYPE_AUDIO);


        if(ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(WorkOrderOptMainActivity.this,new String[]{
                    android.Manifest.permission.RECORD_AUDIO},1254);
        }


    }



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

        pictureUpload.setOnChangeListener(new PictureSelectorUpload.UploadChangeListener() {
            @Override
            public void uploadResult(boolean State,String actionType) {
                if (State) {
                    System.out.println("文件上传回调成功");
                } else {
                    System.out.println("文件上传失败");
                }
            }

            @Override
            public void uploadActionType(String actionType) {

                System.out.println("actionType："+actionType);
                switch (actionType){
                    case "photo":
                        currentUpload = pictureSelectorUpload;
                        break;
                    case "audio":
                        currentUpload = audioSelectorUpload;
                        break;
                }

            }
        });

        //showImg.onTouchEvent()
        return  pictureUpload;
    }


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

    }


    private void iniData(){

    }



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

                default:
            }


        }
    }


    private void workFinish(){
        if (!validate()){
            return;
        }
        //数据检查不通过

        if (!checkRepeat(actionUrl+(postParam.toString()))){
            Toast.makeText(this, getString(R.string.error_data_processed), Toast.LENGTH_LONG).show();
            return;
        }


        if (!isOk){  Toast.makeText(this, getString(R.string.error_data_processed), Toast.LENGTH_LONG).show(); return;}
        isOk = false;
        OkGo.<String>post(Urls.getServiceAddress(this) + actionUrl).upJson(postParam)
                .execute(new MyDialogCallback(this, true, true) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        isOk = true;
                        super.onSuccess(response);
                        try {
                            ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                            if(bean.code == 1){
                                showSuccessToast(bean.msg);
                                Intent intent = new Intent();
                                intent.putExtra("opt_status", "success");
                                setResult(200, intent);//返回值，200 是改返回的标志，也会返回
                                finish();

                            }else{
                                showWarningToast(bean.msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("添加理货数据结果返回错误",e.getMessage());
                        }
                    }
                });
    }


    /*
     * 校验必录
     */
    private boolean validate(){
        photoList = pictureSelectorUpload.getPhotoList();
        speakList = audioSelectorUpload.getPhotoList();
        try {
            postParam = new JSONObject();
            if (action.equals("handle")){
                postParam.put("tracking_number",trackingNumber);
            }

            //检查是否拍照  工单处理时拍照拍照非必传
            if (!action.equals("handle") && photoList.size()==0){
                showWarningToast("请拍照上传");
                return false;
            }
            Gson gson = new Gson();
            postParam.put("photo",gson.toJson(photoList));
            postParam.put("speak_file",gson.toJson(speakList));

        } catch (JSONException e) {
            showWarningToast("系统异常"+e.getMessage());
            e.printStackTrace();
            return false;
        }



        return true;
    }

    //sIsGoodinfoMatch,sIsBattery,sIsMagnetic,sIsWood,sIsExtra,sIsOther
    @OnClick({R.id.btn_confirm})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_confirm:
                workFinish();
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        pictureSelectorUpload.removeHandler();
        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());
        }
    }

}
