package com.sheep.gamegroup.util;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.Html;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTarget;
import com.arialyy.aria.core.inf.IEntity;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.HomeListEntity;
import com.sheep.gamegroup.model.entity.RequestParameEty;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.TaskListen;
import com.sheep.gamegroup.model.entity.WebviewEntity;
import com.sheep.gamegroup.model.entity.WithdrawalEty;
import com.sheep.gamegroup.presenter.TryMakeMoneyPresenter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 一些公用的class
 * Created by ljy on 2018/3/21.
 */

public class CommonUtil {
    public static String START_TASK = "开始任务";
    public static String GET_TASK = "领取任务";
    public static String START_PLAY = "开始试玩";
    public static String CONTINUE_DOWNLOAD = "继续下载";
    public static String START_DOWNLOAD = "开始下载";
    public static String FAIL_DOWNLOAD = "下载失败";
    public static String START_INSTALL = "开始安装";
    public static String OPEN_APPLY = "打开应用";
    private static CommonUtil commonUtil;

    public static CommonUtil getInstance(){
        if(commonUtil == null){
            commonUtil = new CommonUtil();
        }
        return commonUtil;
    }

    /**
     * 返回提现审核结果
     * 审核状态 1系统审核不通过等待人工审核 2系统审核通过 3人工审核不通过 4人工审核通过
     */
    public String returnAuditResult(WithdrawalEty ety){
        String result = "未审核";
        switch (ety.getStatus()){
            case 0:
                result = "未审核";
                break;
            case 1:
                result = "等待人工审核";
                break;
            case 2:
                result = returnPayState(ety);
                break;
            case 3:
                result = "人工审核不通过";
                break;
            case 4:
                result = returnPayState(ety);
                break;
        }
        return result;
    }

    public String returnPayState(WithdrawalEty ety){

        String result = "未付款";
        switch (ety.getPay_status()){
            case 0:
            case 1:
            case 3:
                result = "付款中";
                break;
            case 2:
                result = "已付款";
                break;
        }
        return result;
    }

    /**
     * 昵称限制
     * @param str
     * @param maxLen
     * @return
     */
    public boolean handleText(String str, int maxLen) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        int count = 0;
        int endIndex=0;
        for (int i = 0; i < str.length(); i++) {
            char item = str.charAt(i);
            if (item < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
            if(maxLen==count || (item>=128 && maxLen+1==count)){
                endIndex=i;
            }
        }
//        if (count <= maxLen) {
//            return str;
//        } else {
//            G.showToast("昵称超过限制长度");
//            return str.substring(0, endIndex) + "...";
//        }
        if(count <= maxLen){
            return true;
        }else {
            return false;
        }

    }

    /**
     * 添加下载
     */
    public DownLoadInfo addNewDownloadTask(String gameName, String downloadUrl, String packageName,
                                           int versionCode, String iconUrl, String size, Integer gameId,int whereFrom) {

        DownLoadInfo task = new DownLoadInfo();
        task.setMIconUrl(iconUrl);
        task.setMGameName(gameName);
        task.setMDownloadUrl(downloadUrl);
        task.setMPackageName(packageName);
        task.setMVersionCode(versionCode);
        task.setMTotalSize(Double.valueOf(size));
        task.setMGameID(gameId);
        task.setWhereFrom(whereFrom);
        task.setMApkPath(ClassFileHelper.DIR + File.separator + packageName + ClassFileHelper.FILE_SUFFIX);
        return task;
    }

    /**
     * 暂停下载
     */
    public void stopDownloadTask(Context context, String downloadUrl){
        if(TextUtils.isEmpty(downloadUrl)){
            return;
        }
        try {
            DownloadTarget task = Aria.download(context).load(downloadUrl);
            if(task != null && task.getTaskState() == IEntity.STATE_RUNNING){
                task.stop();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 倒计时
     */
    public void countDownTimer(final TextView tv, long full_second, SelfCountDownTimer countDownUtil){
        countDownUtil = new SelfCountDownTimer(full_second * 1000, 1000,(int)full_second) {
            @Override
            public void onTimerRest() {
                tv.setText("");
            }

            @Override
            public void onTimerTick(long millisUntilFinished, int counTime) {
                String textStr = counTime + " s";
                tv.setText("");
            }

            @Override
            public void onTimerFinish() {
                tv.setText("");
            }
        };
    }

    /**
     * 任务倒计时
     * 组装String
     * 若00:00:00后任务未完成，视为自动放弃，您可重新接受
     */
    public String assemblyString(String date){
        String str = "若<font color='#ff2d4b'><small>" + date + "</small></font>后任务未完成，视为自动放弃，您可重新接受";
        return str;
    }
    /**
     * 任务传送数据组装
     * is_succession:0:不是连续  1:联系任务 3 全部显示
     */
    public HashMap<String, String> setHashMap(int page, int per_page,
                                              int platform, int is_hot,
                                              int is_recommend, int about_to_begin,
                                              int task_type, int is_succession){

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", page+"");
        hashMap.put("per_page", per_page+"");
        hashMap.put("platform", platform+"");
        hashMap.put("is_hot", is_hot+"");
        hashMap.put("is_recommend", is_recommend+"");
        hashMap.put("about_to_begin", about_to_begin+"");
        hashMap.put("task_type", task_type+"");
        hashMap.put("is_succession", is_succession+"");
        return hashMap;
    }
    /**
     * json 获取key
     */
    public String getValue(String json){
        try{
            JSONObject jsonObject = JSONObject.parseObject(json);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
                return (String)  entry.getValue();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 格式化图片 html
     */
    public CharSequence getCharSequence(final Context context, String value, String imgName){

        String html = value + "<img src='" + imgName + "' />";
        CharSequence c = Html.fromHtml(html, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                Drawable mipmap = context.getResources().getDrawable(
                        getResourceId(source)
                );
                mipmap.setBounds(0, 0, mipmap.getIntrinsicWidth() / 1,
                        mipmap.getIntrinsicHeight() / 1);
                return mipmap;
            }
        }, null);
        return c;
    }

    /**
     * 获取行数和一行的字数，来设置字符
     */
    public void getViewCharLines(final Context context, final TextView textView, String value){
        final ViewTreeObserver vto = textView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
//                vto.removeGlobalOnLayoutListener(this);
                if(textView.getLineCount() > 2){
                    int lineEndIndexOne = textView.getLayout().getLineEnd(1);
                    int lineEndIndexTwo = textView.getLayout().getLineEnd(2);
                    String text = textView.getText().subSequence(0, lineEndIndexTwo -3) + "...";
                    textView.setText(text);
                }
            }
        });

    }

    /**
     * 根据资源的ID的变量名活的Filed的对象，使用反射机制来实现
     * @param name
     * @return
     */
    public int getResourceId(String name) {
        try {
            //根据资源的ID的变量名活的Filed的对象，使用反射机制来实现
            Field f = R.mipmap.class.getField(name);
            //使用反射机制，取得并返回资源id字段
            return Integer.parseInt(f.get(null).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 设置view 背景颜色
     */
    public void setViewBackground( TextView textView ,String colorValue){
        try {
            GradientDrawable gradientDrawable = (GradientDrawable) textView.getBackground();
            gradientDrawable.setColor(Color.parseColor(colorValue));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 首页，homelist 跳转 逻辑
     */
    public void goWhere(Context context, HomeListEntity entity){
        if(entity == null){
            return;
        }
        try {
            goNative(context, entity);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     *
     */
    public void goNative(Context context, HomeListEntity entity){

        switch(Integer.valueOf(entity.getJump())){
            case 1://试玩赚钱

                Jump2View.getInstance().goTryplayView(context, null);
                break;
            case 2://2邀请赚钱，
                Jump2View.getInstance().goAskGetMoney(context, null);
                break;
            case 3://3躺着赚钱，
                Jump2View.getInstance().tryGoLyingView(context, null);

                break;
            case 4://4办卡赚钱
                Jump2View.getInstance().goCreditCardTaskList(context, null);
                break;
            case 5://5玩转游戏
                Jump2View.getInstance()
                        .goMainGame(context);
                break;
            case 6://6充值q币
//                G.showToast("敬请期待!");
                Jump2View.getInstance().goRechargeQAct(context,null);
                break;
            case 7://微信辅助
//                G.showToast("敬请期待!");

                Jump2View.getInstance().goWeb(context,
                        entity.getUrl(), "微信二维码辅助好友注册任务");
                break;
            case 8://连续任务
                Jump2View.getInstance().goTryplayView(context, 1);
                break;
            case 98://内部WebView加载H5
                Jump2View.getInstance().goWeb(context, entity.getUrl(), entity.getTitle());
                break;
            case 99://外部浏览器加载H5
                Jump2View.getInstance().goWeb(context, entity.getUrl());
                break;
            default:

                break;

        }
    }
    /**
     * 注销账户
     */
    public void loginOut(final BaseActivity activity){
        //登出

        UMConfigUtils.onProfileSignOff();
        UMConfigUtils.onEvent(UMConfigUtils.Event.USER_LOGOUT);
        UMShareAPI api=  UMShareAPI.get(activity);
        api.deleteOauth(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                activity.hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                activity.hideProgress();
            }
        });

        api.deleteOauth(activity, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                activity.hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                activity.hideProgress();
            }
        });
        SpUtils.login(activity, "");
        SpUtils.saveWeixin(activity, "");
        SpUtils.savePhone(activity, "");
        ActivityManager.getInstance().finishAllActivity();
        Jump2View.getInstance().goLoginView(activity,"");

        activity.finish();
    }

    /**
     * 设置时长
     SheepApp.getInstance().setTaskEty(taskEty);
     */
    public void setTAskEnty(TaskEty tAskEnty){
        try {
            if(tAskEnty.getInspect_type() == 3){

                MyDbManager.getInstance()
                        .saveOrUpdate(new TaskListen(tAskEnty.getId(), tAskEnty.getPackage_names(), tAskEnty.getRelease_task_id()));
            }else {
                MyDbManager.getInstance()
                        .removeTask();
                SheepApp.getInstance().setTaskEty(null);
            }
        }catch (Exception e){
            MyDbManager.getInstance()
                    .removeTask();
            SheepApp.getInstance().setTaskEty(null);
        }
//        SheepApp.getInstance().setTaskEty(tAskEnty);
    }

    /**
     * 获取正在进行中的任务
     */
    public void getRunTask(TryMakeMoneyPresenter presenter,
                           int is_succession){

        RequestParameEty parameEty = new RequestParameEty();
        parameEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(1,
                                100,
                                1,
                                1,
                                0,
                                0,
                                -1,
                                is_succession));
        presenter.returnTask(parameEty);
    }

    /**
     * 设置 drawLeft drawRight
     */
    public void setDraw2View(Context context, TextView view, int res, int color){
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        view.setCompoundDrawables(drawable, null, null, null);
        view.setTextColor(context.getResources().getColor(color));
    }
}
