package com.fxy.fms.putOut;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;

import com.elvishew.xlog.XLog;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureConfig;
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.util.JsonUtil;
import com.fxy.R;
import com.fxy.common.PictureSelectorUpload;
import com.fxy.bean.ActionBean;
import com.fxy.constant.EventCode;
import com.fxy.fms.logic.ViewLogic;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;

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;

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

    @BindView(R.id.rv_show_img)
    RecyclerView rvShowImg;

    @BindView(R.id.ll_storage_details)
    LinearLayout llStorageDetails;

    private PictureSelectorUpload pictureSelectorUpload;

    private ViewLogic viewLogic;

    protected String action;

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

    //装柜信息
    private JSONObject storageObject;


    private JSONObject postParam = new JSONObject();

    private Unbinder unbinder;

    private String isConfirm = "N";

    private ArrayList photoList =new ArrayList<>();



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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {
        try {
            outboundObject = new JSONObject(bundle.getString("outbound_object"));
            action = bundle.getString("action","storage");
        } catch (JSONException e) {
            XLog.e("接收数据解析："+e.getMessage());
            e.printStackTrace();
        }

    }
    //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) {// 图片选择结果回调
                pictureSelectorUpload.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("完成装柜");
        viewLogic = new ViewLogic(llStorageDetails);
        initData();
        initEdit();
        pictureSelectorUpload = new PictureSelectorUpload(StorageFinishMainActivity.this,rvShowImg,"load");
    }


    private void initData(){

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("outbound_number",outboundObject.getString("outbound_number"));

            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_GET_OUTBOUND_INFO).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){
                                    storageObject = new JSONObject(bean.data);
                                    viewLogic.setOutbound(storageObject,outboundObject);
                                }else{

                                    showWarningToast(bean.msg);
                                }
                            } catch (Exception e) {
                                showWarningToast("获取获取排舱解析错误:"+e.getMessage());
                                e.printStackTrace();
                                XLog.e("获取获取排舱解析错误",e.getMessage());
                            }
                        }
                    });
        }catch (Exception e){
            showWarningToast(e.getMessage());
            XLog.e("请求获取排舱信息错误:",e);
        }
    }






    @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()){
                finishStorage();
            }
        }
        return super.dispatchKeyEvent(event);
    }



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


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

    }


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

    }

    private void initEdit() {


    }



    private void finishStorage() {

        //校验数据
        if (!validate()){
            return;
        }
        try {
            Gson gson = new Gson();
            postParam.put("outbound_number",outboundObject.getString("outbound_number"));
            postParam.put("is_confirm",isConfirm);
            postParam.put("photo",gson.toJson(photoList));


            if (!checkRepeat(Urls.FMS_FINISH_STORAGE+(postParam.toString()))){return;}
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_FINISH_STORAGE).upJson(postParam)
                    .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();
                                    intent.putExtra("opt_status", "success");
                                    setResult(200, intent);//返回值，200 是改返回的标志，也会返回
                                    finish();

                                }else{

                                    JSONObject result = new JSONObject();
                                    if (bean.data!=null && !bean.data.isEmpty()){
                                        result = new JSONObject(bean.data);
                                    }
                                    //is_warning
                                    if (result.has("is_warning") && result.getInt("is_warning")==1) {
                                        new AlertDialog.Builder(mContext)
                                                .setTitle(R.string.dl_hint)
                                                .setMessage(bean.msg)
                                                .setNegativeButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                                                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        isConfirm = "Y";
                                                        finishStorage();
                                                    }
                                                }).setPositiveButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //取消不做操作

                                            }
                                        }).show();

                                    }else{
                                        showWarningToast(bean.msg);
                                        isConfirm = "N";
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("添加理货数据结果返回错误",e.getMessage());
                            }
                        }
                    });
        } catch (JSONException e) {
            showEmptyView("数据组装失败:"+e.getMessage());
            e.printStackTrace();
        }


    }

    /*
     * 校验必录
     */
    private boolean validate(){
        photoList = pictureSelectorUpload.getPhotoList();
        if (photoList.size()==0){
            showWarningToast("请拍照拍照");
            return false;
        }
        return true;
    }




    @OnClick({R.id.btn_empty_remake,R.id.btn_finish,R.id.tv_not_look,R.id.tv_has_look})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_empty_remake:
                pictureSelectorUpload.emptyRemake();

                break;
            case R.id.btn_finish:
                finishStorage();
                break;
            case R.id.tv_not_look:
                toChecklist(10);
                break;
            case R.id.tv_has_look:
                toChecklist(20);
                break;

            default:
                break;
        }
    }

    private void toChecklist(int status){
        Bundle bundle = new Bundle();
        try {
            //PC-2021032611414
            JSONObject paramObject = new JSONObject();
            paramObject.put("outbound_number",outboundObject.getString("outbound_number"));
            paramObject.put("status",status);
            bundle.putString("param_object",paramObject.toString());
            bundle.putString("action",action);
            intentPageResult(this, StorageChecklistMainActivity.class, bundle,200);
        } catch (JSONException e) {
            XLog.e("调整参数错误"+e.getMessage());
            e.printStackTrace();
        }
    }

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

        pictureSelectorUpload.removeHandler();
        super.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        initReceiver();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播

    }


}
