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

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

import com.google.gson.Gson;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import cn.net.caoyao.cpzshandset.bean.ManagerDataBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.service.bll.SheepDealerBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.res.DealerBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20024ResBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20024ReqDealerInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SheepExReqDealerInfoRunable implements Runnable {
	private Handler mHandler;
	private long deveicedId; 
	private SheepDealerBll dealerBll;
	public SheepExReqDealerInfoRunable(Handler mHandler, long deveicedId,SheepDealerBll dealerBll) {
		this.mHandler = mHandler;
		this.deveicedId = deveicedId;
		this.dealerBll = dealerBll;
	}

	@Override
	public void run() {
	    if ("358001981".equals(deveicedId+"")||"358002005".equals(deveicedId+"")){
            getDeviceData(deveicedId+"");
        }else {
            SocketCreate create = new SocketCreate(Config.ip, Config.port, String.valueOf(deveicedId));
            try {
                create.createLoginCpzsHandset(deveicedId);
                if (create.isResult()) {
                    Prot20024ReqDealerInfo dealerReq = new Prot20024ReqDealerInfo();
                    dealerReq.dealDealerList(create);
                    Prot20024ResBean resBean = dealerReq.getResBean();
                    if (resBean.getResult() == 0) {
                        //0：请求成功     1：遇到错误信息，返回错误码
                        if (resBean.getList() != null && resBean.getList().size()>0) {
                            insertDealerInfo(resBean.getList());
                        }else {
                            mHandler.sendEmptyMessage(RequestConstant.PROT_REQ_DEALERINFO_20024_NO_DATA);
                        }
                    } else {
                        Message failMsg = mHandler.obtainMessage();
                        failMsg.what = RequestConstant.PROT_REQ_DEALERINFO_20024_FAIL;
                        failMsg.obj = resBean;
                        mHandler.sendMessage(failMsg);
                    }

                } else {
//				mHandler.sendEmptyMessage(ThreadConstant.)
                    Message loginFailMsg = mHandler.obtainMessage();
                    loginFailMsg.obj = create.getErrMsg();
                    loginFailMsg.arg1 = create.getiErrCode();
                    loginFailMsg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
                    mHandler.sendMessage(loginFailMsg);
                }
            }catch (SocketTimeoutException e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
            } catch (IOException e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
            } finally{
                new Prot02Logout().dealLogout(create);
            }
        }
	}

	private void insertDealerInfo(List<DealerBean> dealers) {
		dealerBll.deleteAllDealer();
		dealerBll.insertDealerList(dealers);
		mHandler.sendEmptyMessage(RequestConstant.PROT_REQ_DEALERINFO_20024_SUCCESS);
	}

    void getDeviceData(String deveicedId) {
        // 创建Get请求
        String url = "http://218.245.0.110:8081/jymf.api/updateInfo/updateDealerTy?companyId="+deveicedId;
        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("onResponse","onResponse==>"+responseJson);
                ManagerDataBean dataBean = new Gson().fromJson(responseJson, ManagerDataBean.class);
                if (responseJson.contains("Flag")) {
                    if (dataBean.isFlag()) {

                        if (dataBean.getData() != null) {
                            //0：请求成功     1：遇到错误信息，返回错误码
                            if (dataBean.getData().getList() != null && dataBean.getData().getList().size() > 0) {
                                List<DealerBean> list=new ArrayList<>();
                                for (int i=0;i<dataBean.getData().getList().size();i++){
                                    ManagerDataBean.DataBean.ListBean listBean = dataBean.getData().getList().get(i);
                                    DealerBean dealerBean=new DealerBean();
                                    dealerBean.setArea_code(listBean.getArea_code());
                                    dealerBean.setCode(listBean.getCode());
                                    dealerBean.setCreatetime(listBean.getCreatetime());
                                    dealerBean.setId(listBean.getId());
                                    dealerBean.setMarket(listBean.getMarket());
                                    dealerBean.setName(listBean.getName());
                                    dealerBean.setPhone(listBean.getPhone());
                                    dealerBean.setProvince(listBean.getProvince());
                                    dealerBean.setRemark(listBean.getRemark());
                                    dealerBean.setStatus(listBean.getStatus());
                                    list.add(dealerBean);
                                }
                                insertDealerInfo(list);
                            } else {
                                mHandler.sendEmptyMessage(RequestConstant.PROT_REQ_DEALERINFO_20024_NO_DATA);
                            }
                        } else {
                            Message failMsg = mHandler.obtainMessage();
                            failMsg.what = RequestConstant.PROT_REQ_DEALERINFO_20024_FAIL;
                            failMsg.obj = dataBean.getMessage();
                            mHandler.sendMessage(failMsg);
                        }

                    } else {
//				mHandler.sendEmptyMessage(ThreadConstant.)
                        Message loginFailMsg = mHandler.obtainMessage();
                        loginFailMsg.obj = dataBean.getMessage();
//                            loginFailMsg.arg1 = ;
                        loginFailMsg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
                        mHandler.sendMessage(loginFailMsg);
                    }

                }
            }
        });
    }


}

