package com.qhclh.ytzh.work.scan;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qhclh.ytzh.R;
import com.qhclh.ytzh.base.BaseActivity;
import com.qhclh.ytzh.bean.MaojiScanBean;
import com.qhclh.ytzh.home.RpcUrl;
import com.qhclh.ytzh.tasks.ViewOnClickTask;
import com.qhclh.ytzh.utils.DateTimeUtil;

import org.forks.jsonrpc.JsonRpcResult;
import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;

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

import butterknife.BindView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by 青花瓷 on 2017/11/29.
 */
///< 扫一扫毛鸡
public class ScanResultActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.lv_infos)
    ListView lv_infos;
    private String scanStr = "";
    private boolean scanf = false;

    private List<MaojiScanBean> scanBeanList;
    private MaojiScanAdapter scanAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.act_scanresult;
    }

    @Override
    protected void initView() {
        initToolbar(mToolbar, "扫码结果", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        scanBeanList = new ArrayList<>();
    }

    @Override
    protected void initOper() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (scanf == false) {
            getactive();
        }
    }

    private RpcObject rpcObj;
    private void getactive() {
        ViewOnClickTask getactiveTask = new ViewOnClickTask(this,"加载中...") {

            @Override
            protected void successUI() {
                dongtaiQuanxian();
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_getactive);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        getactiveTask.execute();
    }


    private static final int REQUEST_PERMISSION_CAMERA_CODE = 102;

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA_CODE)
    private void dongtaiQuanxian() {
        String[] perms = {Manifest.permission.CAMERA};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera),
                    REQUEST_PERMISSION_CAMERA_CODE, perms);
        } else {
            // Already have permission, do the thing
            scan();
            scanf = true;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void scan() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setCaptureActivity(ScanActivity.class);
        if (rpcObj == null) {
//            integrator.setPrompt("进入养殖场请扫描"); //底部的提示文字，设为""可以置空
            integrator.setPrompt("离开养殖场请扫描");
        }else {
//            if ("入养殖场".equals(rpcObj.getNamedValue("State").getName())) {
//                integrator.setPrompt("离开养殖场请扫描");
//            }else
                if ("出养殖场".equals(rpcObj.getNamedValue("State").getName())) {
                integrator.setPrompt("到达食品厂请扫描");
            }else if ("到食品厂".equals(rpcObj.getNamedValue("State").getName())) {
                integrator.setPrompt("到达挂鸡台请扫描");
            }
        }
        integrator.setCameraId(0); //前置或者后置摄像头
        integrator.setBeepEnabled(false); //扫描成功的「哔哔」声，默认开启
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
    }

    ///< 回调获取扫描得到的条码值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                showToast("取消扫描");
                finish();
            } else {
                scanStr = result.getContents();

                if (rpcObj == null) {
//                    EnterBreedFactory();
                    LeaveBreedFactoryNoEnter();
                }else {
//                    if ("入养殖场".equals(rpcObj.getNamedValue("State").getName())) {
//                        LeaveBreedFactory();
//                    }else
                        if ("出养殖场".equals(rpcObj.getNamedValue("State").getName())) {
                        ArriveFoodFactory();
                    }else if ("到食品厂".equals(rpcObj.getNamedValue("State").getName())) {
                        ArriveUnloadingPoint();
                    }
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void LeaveBreedFactoryNoEnter() {
        ViewOnClickTask LeaveBreedFactoryNoEnterTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                MaojiScanBean scanBean = new MaojiScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setShipingchang(rpcObj.getString("FoodFactory_Name"));
                if (rpcObj.getDate("InBreedFactoryTime")!=null) {
                    scanBean.setDaodayangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("InBreedFactoryTime")));
                }else {
                    scanBean.setDaodayangzhichang("");
                }
                if (rpcObj.getDate("OutBreedFactoryTime")!=null) {
                    scanBean.setLikaiyangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("OutBreedFactoryTime")));
                }else {
                    scanBean.setLikaiyangzhichang("");
                }
                if (rpcObj.getDate("ArriveFoodFactoryTime")!=null) {
                    scanBean.setDaodashipingchang(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveFoodFactoryTime")));
                }else {
                    scanBean.setDaodashipingchang("");
                }
                if (rpcObj.getDate("ArriveUnloadingPointTime")!=null) {
                    scanBean.setDaodaguajipingtai(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveUnloadingPointTime")));
                }else {
                    scanBean.setDaodaguajipingtai("");
                }
                if (rpcObj.getString("Employee_HandPhone")!=null) {
                    scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                }else {
                    scanBean.setInfos_phone("");
                }
                scanBeanList.clear();
                scanBeanList.add(scanBean);

                scanAdapter = new MaojiScanAdapter(ScanResultActivity.this,scanBeanList);
                lv_infos.setAdapter(scanAdapter);
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_LeaveBreedFactoryNoEnter,scanStr);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        LeaveBreedFactoryNoEnterTask.execute();
    }

    private void EnterBreedFactory() {
        ViewOnClickTask enterbTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                MaojiScanBean scanBean = new MaojiScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setShipingchang(rpcObj.getString("FoodFactory_Name"));
                if (rpcObj.getDate("InBreedFactoryTime")!=null) {
                    scanBean.setDaodayangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("InBreedFactoryTime")));
                }else {
                    scanBean.setDaodayangzhichang("");
                }
                if (rpcObj.getDate("OutBreedFactoryTime")!=null) {
                    scanBean.setLikaiyangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("OutBreedFactoryTime")));
                }else {
                    scanBean.setLikaiyangzhichang("");
                }
                if (rpcObj.getDate("ArriveFoodFactoryTime")!=null) {
                    scanBean.setDaodashipingchang(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveFoodFactoryTime")));
                }else {
                    scanBean.setDaodashipingchang("");
                }
                if (rpcObj.getDate("ArriveUnloadingPointTime")!=null) {
                    scanBean.setDaodaguajipingtai(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveUnloadingPointTime")));
                }else {
                    scanBean.setDaodaguajipingtai("");
                }
                if (rpcObj.getString("Employee_HandPhone")!=null) {
                    scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                }else {
                    scanBean.setInfos_phone("");
                }
                scanBeanList.clear();
                scanBeanList.add(scanBean);

                scanAdapter = new MaojiScanAdapter(ScanResultActivity.this,scanBeanList);
                lv_infos.setAdapter(scanAdapter);
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_EnterBreedFactory,scanStr);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        enterbTask.execute();
    }

    private void LeaveBreedFactory() {
        ViewOnClickTask leavebTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                MaojiScanBean scanBean = new MaojiScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setShipingchang(rpcObj.getString("FoodFactory_Name"));
                if (rpcObj.getDate("InBreedFactoryTime")!=null) {
                    scanBean.setDaodayangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("InBreedFactoryTime")));
                }else {
                    scanBean.setDaodayangzhichang("");
                }
                if (rpcObj.getDate("OutBreedFactoryTime")!=null) {
                    scanBean.setLikaiyangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("OutBreedFactoryTime")));
                }else {
                    scanBean.setLikaiyangzhichang("");
                }
                if (rpcObj.getDate("ArriveFoodFactoryTime")!=null) {
                    scanBean.setDaodashipingchang(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveFoodFactoryTime")));
                }else {
                    scanBean.setDaodashipingchang("");
                }
                if (rpcObj.getDate("ArriveUnloadingPointTime")!=null) {
                    scanBean.setDaodaguajipingtai(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveUnloadingPointTime")));
                }else {
                    scanBean.setDaodaguajipingtai("");
                }
                if (rpcObj.getString("Employee_HandPhone")!=null) {
                    scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                }else {
                    scanBean.setInfos_phone("");
                }
                scanBeanList.clear();
                scanBeanList.add(scanBean);

                scanAdapter = new MaojiScanAdapter(ScanResultActivity.this,scanBeanList);
                lv_infos.setAdapter(scanAdapter);
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_LeaveBreedFactory,rpcObj.getLong("ID"),scanStr);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        leavebTask.execute();
    }

    private void ArriveFoodFactory() {
        ViewOnClickTask arrivefTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                MaojiScanBean scanBean = new MaojiScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setShipingchang(rpcObj.getString("FoodFactory_Name"));
                if (rpcObj.getDate("InBreedFactoryTime")!=null) {
                    scanBean.setDaodayangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("InBreedFactoryTime")));
                }else {
                    scanBean.setDaodayangzhichang("");
                }
                if (rpcObj.getDate("OutBreedFactoryTime")!=null) {
                    scanBean.setLikaiyangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("OutBreedFactoryTime")));
                }else {
                    scanBean.setLikaiyangzhichang("");
                }
                if (rpcObj.getDate("ArriveFoodFactoryTime")!=null) {
                    scanBean.setDaodashipingchang(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveFoodFactoryTime")));
                }else {
                    scanBean.setDaodashipingchang("");
                }
                if (rpcObj.getDate("ArriveUnloadingPointTime")!=null) {
                    scanBean.setDaodaguajipingtai(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveUnloadingPointTime")));
                }else {
                    scanBean.setDaodaguajipingtai("");
                }
                if (rpcObj.getString("Employee_HandPhone")!=null) {
                    scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                }else {
                    scanBean.setInfos_phone("");
                }
                scanBeanList.clear();
                scanBeanList.add(scanBean);

                scanAdapter = new MaojiScanAdapter(ScanResultActivity.this,scanBeanList);
                lv_infos.setAdapter(scanAdapter);
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_ArriveFoodFactory,rpcObj.getLong("ID"),scanStr);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        arrivefTask.execute();
    }

    private void ArriveUnloadingPoint() {
        ViewOnClickTask arriveuTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                MaojiScanBean scanBean = new MaojiScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setShipingchang(rpcObj.getString("FoodFactory_Name"));
                if (rpcObj.getDate("InBreedFactoryTime")!=null) {
                    scanBean.setDaodayangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("InBreedFactoryTime")));
                }else {
                    scanBean.setDaodayangzhichang("");
                }
                if (rpcObj.getDate("OutBreedFactoryTime")!=null) {
                    scanBean.setLikaiyangzhichang(DateTimeUtil.getYMD4(rpcObj.getDate("OutBreedFactoryTime")));
                }else {
                    scanBean.setLikaiyangzhichang("");
                }
                if (rpcObj.getDate("ArriveFoodFactoryTime")!=null) {
                    scanBean.setDaodashipingchang(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveFoodFactoryTime")));
                }else {
                    scanBean.setDaodashipingchang("");
                }
                if (rpcObj.getDate("ArriveUnloadingPointTime")!=null) {
                    scanBean.setDaodaguajipingtai(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveUnloadingPointTime")));
                }else {
                    scanBean.setDaodaguajipingtai("");
                }
                if (rpcObj.getString("Employee_HandPhone")!=null) {
                    scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                }else {
                    scanBean.setInfos_phone("");
                }
                scanBeanList.clear();
                scanBeanList.add(scanBean);

                scanAdapter = new MaojiScanAdapter(ScanResultActivity.this,scanBeanList);
                lv_infos.setAdapter(scanAdapter);
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ToFoodFactoryTransportLogRpc_ArriveUnloadingPoint,rpcObj.getLong("ID"),scanStr);
                rpcObj = result.getRpcObject(RpcUrl.ToFoodFactoryTransportLogRpc_fanhui);
                return null;
            }
        };
        arriveuTask.execute();
    }

}
