package com.ycgis.macall.personalcenter.p.service;

import android.annotation.SuppressLint;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.ycgis.macall.personalcenter.m.adapterbean.MessageBean;
import com.ycgis.macall.personalcenter.m.event.MessageEvent;
import com.ycgis.macall.personalcenter.m.requestbean.BaseRequestModel;
import com.ycgis.macall.personalcenter.m.requestbean.PagingModel;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * created by:   Macall
 * create time:  2023/1/3 11:29
 * copyright:    @ruansee.com
 * Describe:
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class GetMessageService extends JobService {
    private static String TAG = "GetMessageService";
    private JobParameters jobParameters;

    @Override
    public boolean onStartJob(JobParameters params) {
        jobParameters = params;
        getMsg();
        doService();
        return true;
    }

    @SuppressLint("MissingPermission")
    private void doService() {
//        if (!MPush.I.hasStarted()) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(this, GetMessageService.class));
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(RuanseeApplication.REFRESH_MESSAGE_TIME); //执行的最小延迟时间
            builder.setOverrideDeadline(RuanseeApplication.REFRESH_MESSAGE_TIME);  //执行的最长延时时间
            builder.setBackoffCriteria(RuanseeApplication.REFRESH_MESSAGE_TIME, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        } else {
            builder.setPeriodic(RuanseeApplication.REFRESH_MESSAGE_TIME);
        }
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setRequiresCharging(false);//设置是否在只有插入充电器的时候执行
        builder.setRequiresDeviceIdle(false);//设置手机系统处于空闲状态下执行
        JobInfo info = builder.build();
        jobScheduler.schedule(info); //开始定时执行该系统任务

//        }
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    private void getMsg() {
        ApiModel.requestIO(RetrofitService.getBaseInstance().getMessage(0, 1, 3),
                new BaseRequestCallback<BaseRequestModel<PagingModel<MessageBean>>>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(TAG, msg);
                        jobFinished(jobParameters, false);
                    }

                    @Override
                    public void onRequestSuccess(BaseRequestModel<PagingModel<MessageBean>> result) {
//                LogUtils.w(TAG, result.toString());
                        if (result.getCode() == 20041) {
                            PagingModel<MessageBean> data = result.getData();
                            int counts = data.getCounts();
                            if (counts <= 0) {
                                jobFinished(jobParameters, false);
                                return;
                            }
                            List<MessageBean> items = data.getItems();
                            MessageEvent event = new MessageEvent();
                            event.setCount(counts);
                            String title = "<font color=\"#808080\">全部消息(</font><font color=\"#FF9124\">" + counts + "</font><font color=\"#808080\">）</font>";
                            event.setMsg(title);
                            //                            updateWidget(String.format("未读消息%s条", counts));
                            int lengthNum = Math.min(items.size(), 3);
                            List<MessageBean> messageBeans = items.subList(0, lengthNum);
                            for (int i = 0; i < messageBeans.size(); i++) {
                                MessageBean bean = messageBeans.get(i);
                                bean.setBaseType(1);
                            }
                            if (!messageBeans.isEmpty()) {
                                event.setMessageBeanList(messageBeans);
                                EventBus.getDefault().post(event);
                            }
                        }
                        jobFinished(jobParameters, false);

//                        List<MessageBean> messageBeanList = new ArrayList<>();
//                        try {
//                            JSONObject object = new JSONObject(result.toString());
//                            String code = TypConversion.getJsonStr(object, "code");
//                            if (code.equals("20041")) {
//                                JSONObject data = object.getJSONObject("data");
//                                int counts = TypConversion.getJsonInt(data, "counts", 0);
//                                if (counts <= 0) {
////                            updateWidget("暂无新消息");
//                                    jobFinished(jobParameters, false);
//                                    return;
//                                }
//                        MessageEvent event = new MessageEvent();
//                        event.setCount(counts);
//                        updateWidget(String.format("未读消息%s条", counts));
//                        String title = "<font color=\"#808080\">全部消息(</font><font color=\"#FF9124\">" + counts + "</font><font color=\"#808080\">）</font>";
//                        event.setMsg(title);
//                        JSONArray items = data.getJSONArray("items");
//                        int lengthNum = Math.min(items.length(), 2);
//                        for (int i = 0; i < lengthNum; i++) {
//                            JSONObject jsonObject = TypConversion.getJSONObject(items, i);
//                            if (jsonObject == null) continue;
//                            MessageBean bean = new MessageBean();
//                            bean.setBaseType(1);
//                            bean.setAppName(TypConversion.getJsonStr(jsonObject, "appName"));
//                            bean.setId(TypConversion.getJsonStr(jsonObject, "id"));
//                            bean.setMsgId(TypConversion.getJsonStr(jsonObject, "msgId"));
//                            bean.setTitle(TypConversion.getJsonStr(jsonObject, "msgTitle"));
//                            bean.setContent(TypConversion.getJsonStr(jsonObject, "msgContent"));
//                            bean.setClientId(TypConversion.getJsonStr(jsonObject, "appId"));
//                            bean.setClientSecret(TypConversion.getJsonStr(jsonObject, "appSecret"));
//                            bean.setAppLinkUrl(TypConversion.getJsonStr(jsonObject, "appUrl"));
//                            bean.setMsgType(TypConversion.getJsonStr(jsonObject, "msgType"));
//                            bean.setTime(TypConversion.getJsonStr(jsonObject, "sendingTime"));
//                            int state = TypConversion.getJsonInt(jsonObject, "state", 0);
//                            bean.setRead(state != 0);
//                            messageBeanList.add(bean);
//                        }
//                        if (!messageBeanList.isEmpty()) {
//                            event.setMessageBeanList(messageBeanList);
//                            EventBus.getDefault().post(event);
//                        }
//                        jobFinished(jobParameters, false);
//                    }
//                } catch(JSONException e){
//            e.printStackTrace();
//            jobFinished(jobParameters, false);
//        }
                    }
                });
    }

    private void updateWidget(String msg) {
//        RemoteViews rv = new RemoteViews(this.getPackageName(), R.layout.layout_widget);
//        rv.setTextViewText(R.id.tv_msg_count, msg);
//        ComponentName cn = new ComponentName(this, ListWidgetProvider.class);
//        AppWidgetManager am = AppWidgetManager.getInstance(this);
//        am.updateAppWidget(cn, rv);
    }


}
