package com.ycgis.macall.personalcenter.v.viewmodel;

import android.graphics.Bitmap;
import android.text.Html;
import android.util.Log;
import android.widget.ImageView;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.Observer;

import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.base.BaseViewModel;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.m.adapterbean.AppBean;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.HomeMessageBean;
import com.ycgis.macall.personalcenter.m.adapterbean.MessageBean;
import com.ycgis.macall.personalcenter.m.requestbean.BaseRequestModel;
import com.ycgis.macall.personalcenter.m.requestbean.HomeBannerBean;
import com.ycgis.macall.personalcenter.m.requestbean.PagingModel;
import com.ycgis.macall.personalcenter.p.app.AppCache;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.ImageCallBack;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.LoadPhotoImage;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * created by:   Macall
 * create time:  2023/11/9 14:14
 * copyright:    @ruansee.com
 * Describe:
 */
public class HomeViewModel extends BaseViewModel {

    private final MediatorLiveData<List<Object>> bannerList = new MediatorLiveData<>();
    private final MediatorLiveData<List<AppBean>> appList = new MediatorLiveData<>();
    private final MediatorLiveData<HomeMessageBean> msgList = new MediatorLiveData<>();

    public void addBannerData(LifecycleOwner owner, Observer<List<Object>> observer) {
        addLiveDataObserve(owner, bannerList, observer);
    }

    public void addAppList(LifecycleOwner owner, Observer<List<AppBean>> observer) {
        addLiveDataObserve(owner, appList, observer);
    }

    public void addMsgList(LifecycleOwner owner, Observer<HomeMessageBean> observer) {
        addLiveDataObserve(owner, msgList, observer);
    }

    public void getBanner() {
        ApiModel.request(RetrofitService.getBaseInstance().getBannerList(), new BaseRequestCallback<BaseRequestModel<List<HomeBannerBean>>>() {
            @Override
            public void onRequestFailure(String msg) {
                bannerList.postValue(getErrorBanner());
            }

            @Override
            public void onRequestSuccess(BaseRequestModel<List<HomeBannerBean>> result) {
                List<Object> imageViewList = new ArrayList<>();
                if (result.getCode() == 20041) {
                    List<HomeBannerBean> data = result.getData();
                    if (data != null && !data.isEmpty()) {
                        Collections.sort(data);
                        for (HomeBannerBean b : data) {
                            imageViewList.add(AppCache.BASE_IMAGE_URL + b.getUrl());
                        }
                    } else {
                        imageViewList.addAll(getErrorBanner());
                    }
                } else {
                    imageViewList.addAll(getErrorBanner());
                }
                bannerList.postValue(imageViewList);
            }
        });
    }

    private List<Object> getErrorBanner() {
        List<Object> imageViewList = new ArrayList<>();
        imageViewList.add(R.drawable.icon_banner1);
        imageViewList.add(R.drawable.icon_banner2);
        imageViewList.add(R.drawable.icon_banner3);
        imageViewList.add(R.drawable.icon_banner4);
        imageViewList.add(R.drawable.icon_banner5);
        return imageViewList;
    }

    public void getAppList() {
        ApiModel.request(RetrofitService.getBaseInstance().recommendApplication(), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                hintTuiJianApp(-1, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                try {
                    JSONObject object = new JSONObject(result.toString());
                    String code = TypConversion.getJsonStr(object, "code");
                    if (code.equals("20041")) {
                        List<AppBean> modelList1 = new ArrayList<>();
                        JSONObject data = TypConversion.getJSONObject(object, "data");
                        if (data == null) {
                            hintTuiJianApp(0, "暂无应用");
                            return;
                        }
                        JSONArray tjyy = TypConversion.getJSONArray(data, "推荐应用");
                        JSONArray zxyy = TypConversion.getJSONArray(data, "最新应用");

                        if (zxyy != null) {
                            modelList1.addAll(hanAppData(zxyy));
                        }
                        if (tjyy != null) {
                            modelList1.addAll(hanAppData(tjyy));
                        }
                        if (modelList1.isEmpty()) {
                            hintTuiJianApp(0, "暂无应用");
                        } else {
                            AppBean bean = null;
                            if (modelList1.size() >= 8) {
                                modelList1 = modelList1.subList(0, 8);
                                bean = modelList1.remove(7);
                            } else {
                                bean = new AppBean();
                            }
                            bean.setBaseType(1);
                            bean.setAppName("更多应用");
                            bean.setIcon(R.drawable.icon_gd2);
                            bean.setIconUrl("");
                            modelList1.add(bean);
                            appList.postValue(modelList1);
                        }
                    } else {
                        hintTuiJianApp(-1, TypConversion.getJsonStr(object, "msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hintTuiJianApp(-1, e.getMessage());
                }
            }
        });
    }

    private List<AppBean> hanAppData(JSONArray array) {
        List<AppBean> dataList = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject = TypConversion.getJSONObject(array, i);
            if (jsonObject == null) continue;
            AppBean bean = new AppBean();
            bean.setBaseType(1);
            bean.setAppName(TypConversion.getJsonStr(jsonObject, "name"));
            bean.setId(TypConversion.getJsonStr(jsonObject, "id"));
            bean.setAppType(TypConversion.getJsonStr(jsonObject, "level"));
            if ("3".equals(bean.getAppType())) {
                bean.setLinkUrl(TypConversion.getJsonStr(jsonObject, "packageName"));
            } else {
                bean.setLinkUrl(TypConversion.getJsonStr(jsonObject, "link"));
            }
            String type = TypConversion.getJsonStr(jsonObject, "type");
            if (type.equals("1")) {
                bean.setNetworkType("Ⅱ类应用");
            } else if (type.equals("2")) {
                bean.setNetworkType("Ⅲ类应用");
            }
            bean.setClientId(TypConversion.getJsonStr(jsonObject, "clientId"));
            bean.setClientSecret(TypConversion.getJsonStr(jsonObject, "clientSecret"));
            bean.setIconUrl(TypConversion.getJsonStr(jsonObject, "icon"));
            bean.setClassification(TypConversion.getJsonStr(jsonObject, "classification"));
            bean.setCompany(TypConversion.getJsonStr(jsonObject, "serviceProvider"));
            bean.setOperationName(TypConversion.getJsonStr(jsonObject, "operationPerson"));
            bean.setOperationPhone(TypConversion.getJsonStr(jsonObject, "phoneNumber"));
            bean.setTime(TypConversion.getJsonStr(jsonObject, "applicationTime"));
            dataList.add(bean);
        }
        return dataList;
    }

    private void hintTuiJianApp(int type, String msg) {
        List<AppBean> modelList1 = new ArrayList<>();
//        AppBean bean = new AppBean();
//        bean.setBaseType(type);
//        bean.setBaseMessage(msg);
//        modelList1.add(bean);

        if (type == 0) {
            AppBean bean = new AppBean();
            bean.setBaseType(1);
            bean.setAppName("应用指南");
            bean.setIcon(R.drawable.ic_zfjc);
            modelList1.add(bean);
            AppBean bean1 = new AppBean();
            bean1.setBaseType(1);
            bean1.setAppName("常见问题");
            bean1.setIcon(R.drawable.ic_zazh);
            modelList1.add(bean1);
            AppBean bean2 = new AppBean();
            bean2.setBaseType(1);
            bean2.setAppName("意见反馈");
            bean2.setIcon(R.drawable.ic_ybss);
            modelList1.add(bean2);
        } else {
            AppBean bean = new AppBean();
            bean.setBaseType(type);
            bean.setBaseMessage(msg);
            modelList1.add(bean);
        }
        appList.postValue(modelList1);
    }

    public void getMessage() {
        ApiModel.request(RetrofitService.getBaseInstance().getMessage(0, 1, 6),
                new BaseRequestCallback<BaseRequestModel<PagingModel<MessageBean>>>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(TAG, msg);
                        HomeMessageBean homeMessageBean = new HomeMessageBean();
                        List<MessageBean> messageBeanList = new ArrayList<>();
                        MessageBean bean = new MessageBean();
                        bean.setBaseType(-1);
                        bean.setBaseMessage(msg);
                        homeMessageBean.setTitle("全部消息");
                        homeMessageBean.setCount(0);
                        homeMessageBean.setMessageBeanList(messageBeanList);
                        messageBeanList.add(bean);
                        msgList.postValue(homeMessageBean);
                    }

                    @Override
                    public void onRequestSuccess(BaseRequestModel<PagingModel<MessageBean>> result) {
//                LogUtils.w(TAG, result.toString());
                        HomeMessageBean homeMessageBean = new HomeMessageBean();
                        List<MessageBean> messageBeanList = new ArrayList<>();
                        if (result.getCode() == 20041) {
                            PagingModel<MessageBean> data = result.getData();
                            if (data == null) {
                                homeMessageBean.setTitle("全部消息");
                                MessageBean bean = new MessageBean();
                                bean.setBaseType(0);
                                bean.setBaseMessage("暂无新消息");
                                messageBeanList.add(bean);
                                homeMessageBean.setMessageBeanList(messageBeanList);
                                msgList.postValue(homeMessageBean);
                                return;
                            }
                            int counts = data.getCounts();
                            List<MessageBean> items = data.getItems();
                            if (items.isEmpty()) {
                                homeMessageBean.setTitle("全部消息");
                                MessageBean bean = new MessageBean();
                                bean.setBaseType(0);
                                bean.setBaseMessage("暂无新消息");
                                messageBeanList.add(bean);
                                homeMessageBean.setMessageBeanList(messageBeanList);
                                msgList.postValue(homeMessageBean);
                                return;
                            }
                            String title = "<font color=\"#323232\">全部消息(</font><font color=\"#FF9124\">" + counts + "</font><font color=\"#323232\">）</font>";
                            homeMessageBean.setTitle(title);
                            homeMessageBean.setCount(counts);
                            for (MessageBean bean : items) {
                                bean.setBaseType(1);
                            }
                            homeMessageBean.setMessageBeanList(items);
                            msgList.postValue(homeMessageBean);
                        } else {
                            MessageBean bean = new MessageBean();
                            bean.setBaseType(0);
                            bean.setBaseMessage(result.getMsg());
                            messageBeanList.add(bean);
                            homeMessageBean.setTitle("全部消息");
                            homeMessageBean.setMessageBeanList(messageBeanList);
                            msgList.postValue(homeMessageBean);
                        }
//
//                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);
//                        homeMessageBean.setCount(counts);
//                        if (counts <= 0) {
//                            homeMessageBean.setTitle("全部消息");
//                            MessageBean bean = new MessageBean();
//                            bean.setBaseType(0);
//                            bean.setBaseMessage("暂无新消息");
//                            messageBeanList.add(bean);
//                            homeMessageBean.setMessageBeanList(messageBeanList);
//                            msgList.postValue(homeMessageBean);
//                            return;
//                        }
//                        String title = "<font color=\"#323232\">全部消息(</font><font color=\"#FF9124\">" + counts + "</font><font color=\"#323232\">）</font>";
//                        homeMessageBean.setTitle(title);
//                        JSONArray items = data.getJSONArray("items");
//                        int lengthNum = Math.min(items.length(), 3);
//                        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()) {
//                            MessageBean bean = new MessageBean();
//                            bean.setBaseType(0);
//                            bean.setBaseMessage("暂无新消息");
//                            homeMessageBean.setTitle("全部消息");
//                            messageBeanList.add(bean);
//                        }
//                        homeMessageBean.setMessageBeanList(messageBeanList);
//                        msgList.postValue(homeMessageBean);
//                        return;
//                    }
//                    MessageBean bean = new MessageBean();
//                    bean.setBaseType(0);
//                    bean.setBaseMessage(TypConversion.getJsonStr(object, "msg"));
//                    messageBeanList.add(bean);
//                    homeMessageBean.setTitle("全部消息");
//                    homeMessageBean.setMessageBeanList(messageBeanList);
//                    msgList.postValue(homeMessageBean);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                    MessageBean bean = new MessageBean();
//                    bean.setBaseType(-1);
//                    bean.setBaseMessage(e.getMessage());
//                    messageBeanList.add(bean);
//                    homeMessageBean.setTitle("全部消息");
//                    homeMessageBean.setMessageBeanList(messageBeanList);
//                    msgList.postValue(homeMessageBean);
//                }
                    }
                });
    }
}
