package com.sheep.gamegroup.util;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.CreditCard;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.entity.LoginUser;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.usage.AppUsageManager;
import com.sheep.gamegroup.view.activity.ActInstallApkList;
import com.sheep.gamegroup.view.activity.ActMain;
import com.sheep.gamegroup.view.activity.ActSheepApkList;
import com.sheep.gamegroup.view.activity.ActSheepPngList;
import com.sheep.gamegroup.view.activity.ActWeb;
import com.sheep.gamegroup.view.dialog.DialogLoading;
import com.sheep.gamegroup.view.dialog.DialogNewbieTaskList;
import com.sheep.gamegroup.view.dialog.DialogProgress;
import com.sheep.gamegroup.view.dialog.DialogShare;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.DeviceUtils;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.util.List;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by realicing on 2018/5/3.
 * realicing@sina.com
 */
public class TestUtil {
    private static TestUtil textUtils;

    public static TestUtil getInstance(){
        if(textUtils == null)
            textUtils = new TestUtil();
        return textUtils;
    }

    public static void testChange(final Activity activity, TextView test_change) {
        if (isTest() && !ConfigUtil.getInstance().isFileExists()) {
            test_change.setVisibility(View.VISIBLE);
            test_change.setText(SheepApp.getInstance().getConnectAddress().getName());
            test_change.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final ConnectAddress[] connectAddresses = ConnectAddress.values();
                    AlertDialog dialog = new AlertDialog.Builder(activity).setTitle("请选择要切换的服务器")
                            .setSingleChoiceItems(new ArrayAdapter<>(activity, android.R.layout.simple_list_item_single_choice, connectAddresses), SheepApp.getInstance().getConnectAddress().ordinal(), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialogInterface, int which) {
                                    SheepApp.getInstance().setConnectAddress(connectAddresses[which]);
                                }
                            })
                            .create();
                    dialog.show();
                }
            });
        }
    }
    public static void testChangeUser(final Activity activity, TextView test_change) {
        if (isTest() && !ConfigUtil.getInstance().isFileExists()) {

            test_change.setVisibility(View.VISIBLE);
            test_change.setText("切换账号");
            test_change.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final List<LoginUser> loginUserList = MyDbManager.getInstance().getAllLoginUser();
                    if(ListUtil.isEmpty(loginUserList)){//无用户
                        return;
                    }
                    final List<Object> list = ListUtil.emptyList();
                    list.add("清理图片");
                    list.add("下载小绵羊");
                    ListUtil.addAll(list, loginUserList);
                    AlertDialog dialog = new AlertDialog.Builder(activity).setTitle("选择要登录的账号")
                            .setAdapter(new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1, list),  new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialogInterface, int which) {
                                    Object object = ListUtil.getItem(list, which);
                                    if(object instanceof LoginUser){
                                        SpUtils.saveToken(SheepApp.getInstance(), ((LoginUser) object).getToken());
                                        CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                                            @Override
                                            public void call(UserEntity userEntity) {
                                                if(userEntity != null)
                                                    DataUtil.getInstance().initUserEntity(userEntity);
                                            }
                                        });
                                        ActivityManager.getInstance().finishAllActivity();
                                        Intent intent = new Intent(SheepApp.getInstance(), ActMain.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        SheepApp.getInstance().startActivity(intent);
                                    } else if(object instanceof String){
                                        switch (object.toString()){
                                            case "清理图片":
                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Glide.get(SheepApp.getInstance()).clearDiskCache();//清理图片
                                                    }
                                                }).start();
                                                break;
                                            case "下载小绵羊":
                                                downloadApkFromJenkins();
                                                break;
                                        }
                                    }
                                }
                            }).create();
                    dialog.show();
                }
            });
        }
    }

    public static void saveUser(LoginEntity loginEty) {
        if (isTest()) {
            if (loginEty != null && loginEty.getUser() != null) {
                LoginUser loginUser = new LoginUser();
                loginUser.setServiceName(SheepApp.getInstance().getConnectAddress().getName());
                loginUser.setId(loginEty.getUser().getOpen_id()+loginUser.getServiceName());
                loginUser.setToken(loginEty.getToken());
                loginUser.setNickname(loginEty.getUser().getNickname());
                MyDbManager.getInstance().saveOrUpdate(loginUser);
            }
        }
    }

    public static void addUser(final String token) {
        if (isTest()) {
            SheepApp.getInstance().getNetComponent().getApiService().getInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            UserEntity userEntity = baseMessage.getData(UserEntity.class);
                            LoginEntity loginEntity = new LoginEntity();
                            loginEntity.setToken(token);
                            loginEntity.setUser(userEntity);
                            saveUser(loginEntity);
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            G.showToast(baseMessage);
                        }
                    });
        }
    }
    public static boolean isSheep(){
        return TextUtils.equals("sheep", BuildConfig.FLAVOR) && !BuildConfig.DEBUG;
    }
    public static boolean isTest(){
        return BuildConfig.DEBUG || !"sheep".equals(BuildConfig.FLAVOR);
    }
    public static void downloadApkFromJenkins(){
        Jump2View.getInstance().goWeb(ActivityManager.getInstance().currentActivity(), "http://10.8.210.20:8080/jenkins/job/android_small_sheep/", "从jenkins下载小绵羊安装包");
    }

    /**
     * 交通
     http://mobi.yixiaozhao.jiyuonline.com/bank/10
     http://10.8.210.172:8095/BCM_Insert.js

     浦发
     https://ecentre.spdbccc.com.cn/creditcard/indexActivity.htm?data=P754372&itemcode=2017000032
     http://10.8.210.172:8095/SPDB_Insert.js

     * @param activity
     */
    public static void test(final Activity activity) {
        final String[] items = {"复制token","复制打点数据","从jenkins下载小绵羊安装包","审核中心","检查正版","crc32","loading","progress","查看截图",
                "复制imsi","小米游戏","测试可用金额","测试定位信息","测试apk的渠道","幂动科技","游戏搜索",
                "游戏帐号","游戏代充","尝试开启第三方应用使用情况","测试代理页面","第三方应用使用情况",
                "开启第三方应用使用情况","h5跳转","新手对话框","md5","空间不足提示框",
                "显示已经安装应用列表","复制faq地址","复制代理地址","复制世界杯地址","任务游戏列表","世界杯活动","交通银行信用卡测试",
                "浦发银行信用卡测试", "测试游戏模块","打卡成功提示","定向货币详情","进入绑定身份认证界面时的提示","提交身份认证时的提示", "检查标签",
                "友盟分享", "了解小绵羊", "提现成功"};
        AlertDialog dialog = new AlertDialog.Builder(activity).setTitle("请选择测试项目")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (items[which]) {
                            case "从jenkins下载小绵羊安装包":
                                downloadApkFromJenkins();
                                break;
                            case "审核中心":
                                Jump2View.getInstance().goAuditTastList(activity, null);
                                break;
                            case "检查正版":
                                PngUtil.isKfzsSheepApp();
                                break;
                            case "crc32":
                                activity.startActivity(new Intent(activity, ActSheepPngList.class));
                                break;
                            case "loading":
                                DialogLoading.showDialog(activity);
                                break;
                            case "progress":
                                DialogProgress.showDialog(activity);
                                break;
                            case "查看截图":
                                File root = DataUtil.getScreenShotsDir();
                                if(!root.exists() || root.listFiles().length <= 0){
                                    G.showToast("暂无截图");
                                } else {
                                    File dir = DataUtil.getScreenShotsDir().listFiles()[0];
                                    if (dir.exists()) {
                                        G.showToast("截图个数为：" + dir.list().length);
                                    } else {
                                        G.showToast("截图目录不存在");
                                    }
                                    if (dir.list().length > 0) {
                                        Jump2View.getInstance().selectImgFiles(activity, 7, dir.listFiles());
                                    }
                                }
                                break;
                            case "小米游戏":
                                Jump2View.getInstance().goXiaomiGameList(activity, null);
                                break;
                            case "测试定位信息":
                                String jsonString = LocationUtils.getInstance().getLocationJSONObject().toJSONString();
                                G.showToast(jsonString);
                                StringUtils.CopyText(jsonString);
                                break;
                            case "测试apk的渠道":
                                Intent intent = new Intent(activity, ActSheepApkList.class);
                                activity.startActivity(intent);
                                break;
                            case "测试可用金额":
                                CommonUtil.getInstance()
                                        .getVoucherAndRatio(activity, 115+"", new Action1<BaseMessage>() {
                                            @Override
                                            public void call(BaseMessage baseMessage) {

                                            }
                                        });
                                break;
                            case "幂动科技":
                                Jump2View.getInstance().goMiDong(activity, "http://10.8.210.172:8081/#/?authorization=123123");
                                break;
                            case "游戏帐号":
                                Jump2View.getInstance().goGameAccount(activity, "http://10.8.210.172:8081/#/?authorization=123123");
                                break;
                            case "游戏代充":
                                Jump2View.getInstance().goGameRecharge(activity, "http://10.8.210.172:8081/#/?authorization=123123");
                                break;
                            case "复制打点数据":
                                UMConfigUtils.copyDaDianData();
                                break;
                            case "游戏搜索":
                                Jump2View.getInstance().goGameSearch(activity, null);
                                break;
                            case "测试代理页面":
                                CommonUtil.getInstance().initUrlConfigByNet("agenturl", new Action1<String>(){
                                    @Override
                                    public void call(String url) {
                                        Jump2View.getInstance().goWeb(activity, url, "代理服务");
                                    }
                                });
                                break;
                            case "尝试开启第三方应用使用情况":
                                AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermission(false);
                                break;
                            case "第三方应用使用情况":
                                AppUsageManager.getInstance().println();
                                break;
                            case "开启第三方应用使用情况":
                                AppUsageManager.getInstance().openLookAppUsageStatsPermission();
                                break;
                            case "h5跳转":
                                Jump2View.getInstance().goXianwanWeb(activity,null,null);
                                break;
                            case "新手对话框":
                                DialogNewbieTaskList.tryShowDialog(activity);
                                break;
                            case "md5":
                                String md5 = SysAppUtil.getConnectAdrressFileMD5();
                                StringUtils.CopyText(md5);
                                G.showToast(md5);
                                break;
                            case "空间不足提示框":
                                DialogStorageLow.showDialog(activity);
                                break;
                            case "显示已经安装应用列表":
                                showHasInstallApkList(activity);
                                break;
                            case "复制token":
                                StringUtils.CopyText(SpUtils.getToken(activity));
                                break;
                            case "复制imsi":
                                StringUtils.CopyText(new DeviceUtils(activity).getIMEI());
                                G.showToast(TimeUtil.newInstance().getDayBegin() + "|" + TimeUtil.newInstance().big2Today("2018-07-27",TimeUtil.FORMAT_DD_LINE));
                                break;
                            case "复制faq地址":
                                copyUrl("faqurl");
                                break;
                            case "复制代理地址":
                                copyUrl("agenturl");
                                break;
                            case "复制世界杯地址":
                                copyUrl("world_cup_url");
                                break;
                            case "任务游戏列表":
                                Jump2View.getInstance().goGameMakeMoney(activity, 0);
                                break;
                            case "世界杯活动":
                                Jump2View.getInstance().goWeb(activity, SheepApp.getInstance().getConnectAddress().getWorldCupUrl(), "测试世界杯活动");
                                break;
                            case "交通银行信用卡测试":
                                CreditCard creditCard = new CreditCard();
                                creditCard.setCardName(items[which]);
                                creditCard.setName("交通银行信用卡");
//                                creditCard.setLoadUrl("http://mobi.yixiaozhao.jiyuonline.com/bank/10");
                                creditCard.setLoadUrl("https://creditcardapp.bankcomm.com/applynew/front/apply/campus/index.html?trackCode=A021316596752");
                                creditCard.setScriptUrl("http://10.8.210.172:8095/BCM_Insert.js");
                                Jump2View.getInstance().goCreditCardWeb(activity, creditCard);
                                break;
                            case "测试游戏模块":
                                Jump2View.getInstance().goMainGame(activity);
                                break;
                            case "打卡成功提示":
                                ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("恭喜您").setMsg("打卡成功，活动结束后平分奖励会直接发放到个人账户中")
                                        .setBtnLeftText("好的").setBtnRightText("查看战绩")
                                        .setBtnRightOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                Jump2View.getInstance().goSignRecordAct(activity, null);
                                            }
                                        }));
                                break;
                            case "检查标签":
                                Jump2View.getInstance().checkLabel(activity, null);
                                break;
                            case "定向货币详情":
                                ViewUtil.showOrienteeringDetails(activity);
                                break;
                            case "进入绑定身份认证界面时的提示":
                                ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("温馨提示")
                                        .setMsg("根据国家相关法律规定，为保障线上交易活动的安全，参与互联网大额提现等资金活动时需要进行实名认证。\n完成实名认证后，再次提现将不需要进行验证。")
                                        .setMsgGravity(Gravity.START).setMsgIndent(2).setBtnLeftText("确定"));
                                break;
                            case "提交身份认证时的提示":
                                ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("重要提示").setMsgMore(String.format(Locale.CHINA,"你已执行%d次实名认证操作", 0))
                                        .setMsg("实名认证首次免费。请务必确认您所提交的认证信息真实有效。若因信息填写错误造成认证失败。再次申请认证时需扣除您0.5绵羊币/次作为认证费用，请务必谨慎填写认证信息。")
                                        .setMsgColor("0.5绵羊币/次", "#FF0000")
                                        .setMsgIndent(2)
                                        .setMsgGravity(Gravity.START)
                                        .setBtnLeftText("返回修改").setBtnRightText("确认提交")
                                        .setBtnRightOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                G.showToast("下一步提交");
                                            }
                                        }));
                                break;
                            case "浦发银行信用卡测试":
                                CreditCard creditCard1 = new CreditCard();
                                creditCard1.setCardName(items[which]);
                                creditCard1.setName("浦发银行信用卡");
                                creditCard1.setLoadUrl("https://ecentre.spdbccc.com.cn/creditcard/indexActivity.htm?data=P754372&itemcode=2017000032");
                                creditCard1.setScriptUrl("http://10.8.210.172:8095/SPDB_Insert.js");
                                Jump2View.getInstance().goCreditCardWeb(activity, creditCard1);
                                break;
                            case "友盟分享":
                                TestUtil.getInstance().testUmen(activity);
                            case "了解小绵羊":
                                Jump2View.getInstance().goUnderstandSheep(activity, null);
                                break;
                            case "提现成功":
                                Jump2View.getInstance().goWithdrawalResultview(activity, 1000);
                                break;

                        }
                    }
                }).create();
        dialog.show();
    }


    private static void copyUrl(final String name) {
        CommonUtil.getInstance().initUrlConfigByNet(name, new Action1<String>(){
            @Override
            public void call(String url) {
                StringUtils.CopyText(ActWeb.addUrlToken(url));
            }
        });
    }

    private static void showHasInstallApkList(Activity activity) {
        Intent intent = new Intent(activity, ActInstallApkList.class);
        activity.startActivity(intent);
    }

    /**
     * umen 分享
     */
    private void testUmen(Activity context){
        CommonUtil.getInstance().popShare(context, "http://www.baidu.com", DialogShare.ALL);
        UMImage umImage = new UMImage(context, R.mipmap.icon);
        new ShareAction(context)
                .withText("hehe")
                .withMedia(umImage)
                .setDisplayList(
                        SHARE_MEDIA.QQ,
                        SHARE_MEDIA.WEIXIN)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        Log.e("start---"+share_media.getName(), share_media.getName());
                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        Log.e("result---"+share_media.getName(), share_media.getName());
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        Log.e("error---"+share_media.getName(), share_media.getName()+
                                ",msg:"+ throwable.getMessage());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        Log.e("cancel---"+share_media.getName(), share_media.getName());
                    }
                })
                .open();
    }

    public static boolean isTestRecharge() {
//        return BuildConfig.DEBUG;//测试充值与绑定微信和身份信息逻辑
        return false;
    }
}