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.AdapterView;
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.ScanBean;
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 FumudaiScanResultActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.fumudai_lv_infos)
    ListView fumudai_lv_infos;
    private String scanStr = "";
    private boolean scanf = false;

    private List<ScanBean> scanBeanList;
    private ScanAdapter scanAdapter;

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

    @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() {
        fumudai_lv_infos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showToast(l+"");
            }
        });
    }

    @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() {
                System.out.println("aaa++++getactive++++"+rpcObj);
                dongtaiQuanxian();
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.ChickTransportLogRpc_getactive);
                rpcObj = result.getRpcObject(RpcUrl.ChickTransportLogRpc_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("离开孵化厂请扫描"); //底部的提示文字，设为""可以置空
        }else {
            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){
                    LeaveHatchery();
                }else {
                    ArriveBreedFactory();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void ArriveBreedFactory() {
    }

    private void LeaveHatchery() {
        ViewOnClickTask leaveTask = new ViewOnClickTask(this,"加载中...") {
            @Override
            protected void successUI() {
                System.out.println("aaa++++leave++++"+rpcObj);
                ScanBean scanBean = new ScanBean();
                scanBean.setId(rpcObj.getLong("ID"));
                scanBean.setInfos_carname(rpcObj.getString("Car_Name"));
                scanBean.setInfos_driver(rpcObj.getString("Employee_Name"));
                scanBean.setInfos_fuhuachang(rpcObj.getString("Hatchery_Name"));
                scanBean.setInfos_yangzhichang(rpcObj.getString("BreedFactory_Name"));
                scanBean.setInfos_leavetime(DateTimeUtil.getYMD4(rpcObj.getDate("LeaveHatcheryTime")));
                scanBean.setInfos_daodashijian(DateTimeUtil.getYMD4(rpcObj.getDate("ArriveBreedFactoryTime")));
                scanBean.setInfos_phone(rpcObj.getString("Employee_HandPhone"));
                scanBeanList.add(scanBean);

                scanAdapter = new ScanAdapter(FumudaiScanResultActivity.this,scanBeanList);
                fumudai_lv_infos.setAdapter(scanAdapter);
            }

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