package cn.net.caoyao.cpzshandset.service.thread.impl.common;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import cn.net.caoyao.cpzshandset.bean.ChangeDeviceID;
import cn.net.caoyao.cpzshandset.bean.ProductBeanList;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.Product;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20001ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20001ResBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20001Product;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CommonUpdateProductListThread implements Runnable {
    private long deviceId;
    private ProductBll bll;
    private Handler mHandler;

    public CommonUpdateProductListThread(Handler mHandler, long deviceId, ProductBll bll) {
        this.mHandler = mHandler;
        this.deviceId = deviceId;
        this.bll = bll;
    }

    @Override
    public void run() {
        SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
        try {
            LogUtil.d(TConfig.Echo, "登录");
            create.createLoginCpzsHandset(deviceId);
            if (create.isResult()) {
                requestProductList(create);
            } else {
                Message msg = new Message();
                msg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
                msg.arg1 = create.getiErrCode();
                msg.obj = create.getErrMsg();
                mHandler.sendMessage(msg);
            }

        } catch (BindException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
        } catch (ConnectException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
        } finally {
            new Prot02Logout().dealLogout(create);
        }
    }
      String cmpId;
    //http://218.245.0.110:8081/jymf.api/updateInfo/updateEquipment?equipmentId=358001781005 转换 设备号
    public void getData(final String companyId, final Prot20001Product product) {

        if (companyId.length() > 9) {
            String changeDeviceId="http://218.245.0.110:8081/jymf.api/updateInfo/updateEquipment?equipmentId="+companyId;
            OkHttpClient client = new OkHttpClient();
            final Request request = new Request.Builder().url(changeDeviceId).get() .addHeader("Content-Type", "application/json").build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Message msg = mHandler.obtainMessage();
                    msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
                    msg.obj = "设备ID不正确";
                    msg.arg1 = 0;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String string = response.body().string();
                    Log.e("responseJson", "responseJson==>" + string);
                    ChangeDeviceID changeDeviceID=new Gson().fromJson(string,ChangeDeviceID.class);
                    if (changeDeviceID.isFlag()){
                        cmpId=changeDeviceID.getData();
                        getDataList( cmpId,product);
                    }else {
                        Message msg = mHandler.obtainMessage();
                        msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
                        msg.obj = "设备ID不正确";
                        msg.arg1 = 0;
                        mHandler.sendMessage(msg);
                    }
                }
            });
        }else {
            getDataList( companyId,product);
        }


    }

    private void getDataList(String companyId,final  Prot20001Product product) {
        //http://218.245.0.110:7080/handset.api//fire/updateProduct?companyId=358001781
        String url = "http://218.245.0.110:7080/handset.api/fire/updateProduct?companyId=" + companyId;
        Log.e("responseJson", "responseJson==>" + url);
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(url).get()
                // .post(RequestBody.create(okhttp3.MediaType
                // .parse("application/json; charset=utf-8"), json))
                .addHeader("Content-Type", "application/json").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                String responseJson = response.body().string();

                Log.e("responseJson", "responseJson==>" + responseJson);
                final ProductBeanList resBean = new Gson().fromJson(
                        responseJson, ProductBeanList.class);
                if (resBean == null) {
                    Message msg = mHandler.obtainMessage();
                    msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
                    msg.obj = "未请求到数据";
                    msg.arg1 = 0;
                    mHandler.sendMessage(msg);
                    return;
                }
                if (!resBean.isFlag()) {
                    //请求产品列表失败
                    Message msg = mHandler.obtainMessage();
                    msg.what = RequestConstant.REQUEST_PRODUCT_LIST_FAIL;
                    msg.obj = resBean;
                    mHandler.sendMessage(msg);
                    return;
                }
                if (resBean.getData() == null) {
                    //产品列表为空
                    bll.deleteAllProduct();
                    Message msg = mHandler.obtainMessage();
                    msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
                    msg.obj = "产品列表为空";
                    msg.arg1 = 0;
                    mHandler.sendMessage(msg);
                    return;
                }
                Prot20001ResBean resBean1 = new Prot20001ResBean();
                List<Product> list = new ArrayList<>();

                for (int i = 0; i < resBean.getData().size(); i++) {
                    ProductBeanList.DataBean dataBean = resBean.getData().get(i);
                    Product product = new Product();
                    product.setId(dataBean.getId()+"");
                    product.setName(dataBean.getName()+"");
                    product.setNid(dataBean.getNumber_id()+"");
                    list.add(product);
                }
                resBean1.setList(list);
                resBean1.setErrcode(0);
                resBean1.setErrmsg("更新成功");
                product.setResBean(resBean1);
                bll.deleteAllProduct();
                bll.insertProductList(resBean1.getList());
                mHandler.sendEmptyMessage(RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS);
            }
        });
    }

    private void requestProductList(SocketCreate create) throws IOException {
        Prot20001Product product = new Prot20001Product();
        product.reqProductList(create, new Prot20001ReqBean(String.valueOf(deviceId)));
        //贵人鸟 单独接口
//        getData(String.valueOf(deviceId), product);
//        product.getResBean();
		Prot20001ResBean resBean = product.getResBean();


        if (resBean == null) {
            Message msg = mHandler.obtainMessage();
            msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
            msg.obj = "未请求到数据";
            msg.arg1 = 0;
            mHandler.sendMessage(msg);
            return;
        }
        if (resBean.getResult() == 1) {
            //请求产品列表失败
            Message msg = mHandler.obtainMessage();
            msg.what = RequestConstant.REQUEST_PRODUCT_LIST_FAIL;
            msg.obj = resBean;
            mHandler.sendMessage(msg);
            return;
        }
        if (resBean.getList() == null) {
            //产品列表为空
            bll.deleteAllProduct();
            Message msg = mHandler.obtainMessage();
            msg.what = RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY;
            msg.obj = "产品列表为空";
            msg.arg1 = 0;
            mHandler.sendMessage(msg);
            return;
        }

        bll.deleteAllProduct();
        bll.insertProductList(resBean.getList());
        mHandler.sendEmptyMessage(RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS);
//
		/*Prot17GetProducts getProducts = new Prot17GetProducts();
//		LogUtil.d(TConfig.Echo, "开始请求产品列表信息");
		getProducts.dealProductList_V2(create, new CallBack_V2() {

			@Override
			public void okData(List<Product> products, int iTotalCount, int iCurrentRecCount) {
				if (products != null) {
					bll.deleteAllProduct();
					bll.insertProductList(products);
//					LogUtil.d(TConfig.Echo, "请求产品列表成功：" + bll.queryAllProductInfo().toString());
					mHandler.sendEmptyMessage(RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS);
				} else {
					Message msg = mHandler.obtainMessage();
					msg.what = RequestConstant.REQUEST_PRODUCT_LIST_FAIL;
					msg.obj = "产品列表为空";
					msg.arg1 = 0;
					mHandler.sendMessage(msg);
				}
			}

			@Override
			public void errData(String err, int iRecErrCode) {
				Message msg = mHandler.obtainMessage();
				msg.what = RequestConstant.REQUEST_PRODUCT_LIST_FAIL;
				msg.obj = err;
				msg.arg1 = iRecErrCode;
				mHandler.sendMessage(msg);
				LogUtil.e(TConfig.Echo, "err：" + err + " iRecErrCode:" + iRecErrCode);

			}
		});		*/
    }


}
