package com.sunzee.mvp.homeactivity;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.BasePresenter;
import com.sunzee.db.CleaningBeanDao;
import com.sunzee.model.Global;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.HttpResult;
import com.sunzee.model.HttpResult2;
import com.sunzee.model.domain.CleaningBean;
import com.sunzee.model.domain.Name;
import com.sunzee.model.domain.ParameterBean;
import com.sunzee.retrofit.ApiCallback;
import com.sunzee.thread.advanceparameter.ThreadPoolAdvanceParameter;
import com.sunzee.utils.AlarmManagerUtil;
import com.sunzee.utils.HexadecimalUtil;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * 厕所状态界面 presenter
 * 需求：
 */
public class HomePageAPresenter extends BasePresenter<HomePageAView> {


    private static final String TAG = "HomeactivityPresenter";
    private CleaningBeanDao cleaningBeanDao;

    public HomePageAPresenter(HomePageAView view) {
        attachView(view);
        cleaningBeanDao = BaseApplication.getInstances().getDaoSession().getCleaningBeanDao();
    }



    //-------------------------------------------------------------------------清洗规则 start--------------------------------------------------------------------------------------------
    public void requstCleanRule() {
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId);
        addSubscription(apiStores.cleanRule(params), new ApiCallback<HttpResult<String>>() {
            @Override
            public void onSuccess(HttpResult<String> model) {
                String times = model.getData().trim();
                Log.d(TAG, "onSuccess: " + times);
                if ("尚未设定清洗规则".equals(times)) {
                    return;
                }
                Log.d(TAG, "onSuccess: ");
                Log.d(TAG, "onSuccess2: " + times);
                if (!TextUtils.isEmpty(times)) {
                    String[] Alltime = times.split("\\,");
                    Global.alarmNumber = Alltime.length;
                    for (int i = 0; i < Alltime.length; i++) {
                        String[] data = Alltime[i].split(":");
                        for (String datum : data) {
                            Log.d(TAG, "onSuccess1: " + datum);
                        }
                        //设置定时闹钟
                        AlarmManagerUtil.setAlarm(BaseApplication.getContext(), 1, Integer.valueOf(data[0]), Integer.valueOf(data[1]), Integer.valueOf(data[2]), i, 0, "闹钟响了26");
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                Log.d(TAG, "onFailure: " + msg);
            }

            @Override
            public void onFinish() {
            }
        });
    }

    //-------------------------------------------------------------------------清洗规则 end--------------------------------------------------------------------------------------------

    //------------------------------------------------------------------请求是否已经付费了。或者说过期了。 start-----------------------------------------------
    public void requestCleanTimeAndRemaining() {
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId);
        addSubscription(apiStores.getCleanTimeAndRemaining(params), new ApiCallback<HttpResult2<String>>() {
            @Override
            public void onSuccess(HttpResult2<String> model) {
                Log.d(TAG, "onSuccess11: " + model);
                String overdueDate = model.getOverdueDate();
                String remaining = model.getRemaining();
                if (TextUtils.isEmpty(overdueDate)) {
                    //如果为空
                    Hawk.put(Name.OVERDUE_DATE, null);
                } else {
                    try {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overdueDate));
                        Hawk.put(Name.OVERDUE_DATE, calendar.getTimeInMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        Hawk.put(Name.OVERDUE_DATE, null);
                    }
                }
                if (TextUtils.isEmpty(remaining)) {
                    Hawk.put(Name.REMAINING, null);
                } else {
                    Hawk.put(Name.REMAINING, remaining);
                }

            }

            @Override
            public void onFailure(String msg) {
                Log.d(TAG, "onFailure: " + msg);
                //失败了。
            }

            @Override
            public void onFinish() {
            }
        });
    }

    //---------------------------------------------------------------------请求是否已经付费了。 end---------------------------------------------
    public void setAdvanced(String name, ArrayList<String> results, ThreadPoolAdvanceParameter threadGetParameter1) {
        if (name.equals("D418")) {
            if (!threadGetParameter1.isReceive2()) {
                threadGetParameter1.setReceive2(true);
                threadGetParameter1.stopReadD418();
                threadGetParameter1.getValues()[6] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(0))));
                threadGetParameter1.getValues()[7] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(1))));
                threadGetParameter1.getValues()[0] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(2))));
                threadGetParameter1.getValues()[1] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(3))));
                threadGetParameter1.getValues()[2] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(4))));
                threadGetParameter1.getValues()[3] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(5))));
                threadGetParameter1.getValues()[4] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(6))));
                threadGetParameter1.getValues()[5] = String.valueOf(get177Data(HexadecimalUtil.hex2dec(results.get(7))));

                Log.d(TAG, "D418setAdvanced: "+results.size());
            }
        } else if (name.equals("D426")) {
            if (!threadGetParameter1.isReceive1()) {
                threadGetParameter1.setReceive1(true);
                threadGetParameter1.stopReadD426();
                threadGetParameter1.getValues()[7] = String.valueOf(HexadecimalUtil.hex2dec(results.get(0)));
                threadGetParameter1.getValues()[8] = String.valueOf(HexadecimalUtil.hex2dec(results.get(1)));
                threadGetParameter1.getValues()[9] = String.valueOf(HexadecimalUtil.hex2dec(results.get(2)));
                threadGetParameter1.getValues()[10] = String.valueOf(HexadecimalUtil.hex2dec(results.get(3)));
                threadGetParameter1.getValues()[11] = String.valueOf(HexadecimalUtil.hex2dec(results.get(4)));
                threadGetParameter1.getValues()[12] = String.valueOf(HexadecimalUtil.hex2dec(results.get(5)));
                threadGetParameter1.getValues()[13] = String.valueOf(HexadecimalUtil.hex2dec(results.get(6)));
                threadGetParameter1.getValues()[14] = String.valueOf(HexadecimalUtil.hex2dec(results.get(7)));
                threadGetParameter1.getValues()[15] = String.valueOf(HexadecimalUtil.hex2dec(results.get(8)));
                Log.d(TAG, "D426setAdvanced: "+results.size());
            }
        }
        if (threadGetParameter1.isReceive1() &&
                threadGetParameter1.isReceive2()) {
            mvpView.getDataSuccess();
            threadGetParameter1.setReceive1(false);
            threadGetParameter1.setReceive2(false);
        }
    }

    private String get177Data(long l) {
        return String.valueOf(Math.round((l/ Global.num)*10));
    }

    public void updateAdvanced(ArrayList<ParameterBean> parameterBeans) {

        String url = "/api/app_equipment/index/updateParam/1/" + Heartbeat.deviceId + ".htm";
        Gson gson = new Gson();
        String json = gson.toJson(parameterBeans);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
        addSubscription(apiStores.updateParamApi(url, body), new ApiCallback<HttpResult<String>>() {
            @Override
            public void onSuccess(HttpResult<String> model) {
                Log.d(TAG, "onSuccess: " + model);
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onFinish() {
            }
        });
    }

    /**
     * 上次局部清洗的蹲位有多少个
     *
     * @param num 数量
     */
    public void sendPositionNum(int num) {
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId + "");
        params.put("num", num + "");
        Log.d(TAG, "sendPositionNum: " + num);
        addSubscription(apiStores.sendPositionNum(params), new ApiCallback<HttpResult<String>>() {

            @Override
            public void onSuccess(HttpResult<String> model) {
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 上传厕所的使用状态
     * @param sn  几号厕所
     * @param status 厕所使用状态
     */
    public void sendStatusOfToiletUse(String sn,String status){
        Log.d(TAG, "11onSuccess: "+Heartbeat.deviceId);
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId + "");
        params.put("sn", sn);
        params.put("status", status);
        addSubscription(apiStores.sendStatusOfToiletUse(params), new ApiCallback<HttpResult<String>>() {

            @Override
            public void onSuccess(HttpResult<String> model) {
                Log.d(TAG, "sendStatusOfToiletUse11onSuccess: "+model);
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onFinish() {

            }
        });
    }

    public void createBox(int number){
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId + "");
        params.put("number", number+"");
        addSubscription(apiStores.createBox(params), new ApiCallback<HttpResult<String>>() {

            @Override
            public void onSuccess(HttpResult<String> model) {
                Log.d(TAG, "createBox11onSuccess: "+model);
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onFinish() {

            }
        });
    }


    /**
     * 查询今天的使用次数
     */
    public CleaningBean queryTodayCleanCount(int number,int number2) {
        QueryBuilder<CleaningBean> qb = cleaningBeanDao.queryBuilder();
        //tomorrowDateStr(0), tomorrowDateStr(1))
        List<CleaningBean> list = qb.where(new WhereCondition.StringCondition("TIME >= ? and TIME <= ?",
                tomorrowDateStr(number), tomorrowDateStr(number2))).build().list();
        Log.d(TAG, "tomorrowDateStronStartCommand: "+list.size());
        if (list.size()<=0) {
            //添加今天的数据,如果一直不关机呢？那么我们就需要当前时间如何重新插入数据。
            CleaningBean cleaningBean = new CleaningBean();
            cleaningBean.setOutCount("0");
            cleaningBean.setInCount("0");
            cleaningBean.setCleanCount("0");
            cleaningBean.setTime(System.currentTimeMillis());
            cleaningBeanDao.insert(cleaningBean);
            return cleaningBean;
        }
        return  list.get(0);
    }

    /**
     * 获取明天的日期字符串
     * @return
     */
    public static long tomorrowDateStr(int number){
        Date date=new Date();//取时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //把日期往后增加一天.整数往后推,负数往前移动
        calendar.add(calendar.DATE,number);
        //这个时间就是日期往后推一天的结果
        date=calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String tomorrowStr = formatter.format(date);
        Date parse= null;
        try {
            parse = formatter.parse(tomorrowStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse.getTime();
    }
}
