package com.fxy.helper;

import android.content.Context;
import android.os.Handler;

import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.language.other.CommSharedUtil;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.bean.ActionBean;
import com.fxy.common.OssService;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.SPCache;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.realm.CutRuleRealm;
import com.fxy.realm.HkTransDetailRealm;
import com.fxy.realm.HkTransRealm;
import com.lzy.okgo.OkGo;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

import io.realm.Realm;
import io.realm.RealmResults;

public class HkDataHelper {
    protected Context mContext;
    public HkDataHelper(Context context) {
       this.mContext = context;
    }

    /**
     * 获取用户详细信息
     */
    public  void getBaseInfo(){


        String serviceAddress = CommSharedUtil.getInstance(mContext).getString(BaseConfig.SERVICE_ADDRESS);
        OkGo.<String>post(serviceAddress + Urls.GET_USER_BASE_INFO)
                .execute(new MyDialogCallback(mContext, true, false) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        super.onSuccess(response);
                        try {
                            ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                            if (bean.code == 1 && StringUtils.isNotEmpty(bean.data)) {
                                JSONObject jsonObject = new JSONObject(bean.data);
                                String cutRule  = jsonObject.getString("cut_rule");
                                JSONObject transFile = jsonObject.getJSONObject("trans_file");


                                List<HkTransRealm> hkTransRealmList = new ArrayList<>();

                                Iterator<String> keys = transFile.keys();
                                while (keys.hasNext()) {
                                    String key = keys.next();
                                    HkTransRealm hkTransRealm = JsonUtil.getObject(transFile.getString(key),HkTransRealm.class);
                                    hkTransRealm.setBatch(key);
                                    hkTransRealmList.add(hkTransRealm);
                                }
                                List<CutRuleRealm> cutRuleRealmList = JsonUtil.jsonString2Beans(cutRule,CutRuleRealm.class);


                                DataThread thread = new DataThread(mContext,cutRuleRealmList,hkTransRealmList);
                                thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                                    public void uncaughtException(Thread t, Throwable e) {
                                        // 在这里处理线程抛出的异常，并使用传递的参数进行操作
                                        XLog.e("处理数据异常",e.getMessage());
                                    }
                                });
                                thread.start();




                            }else{
                                XLog.e("获取基础数据信息:" + bean.msg);
                            }
                        } catch (Exception e) {
                            XLog.e("获取基础数据信息失败:" + e.getMessage());
                        }
                    }
                });
    }

    class DataThread extends Thread {
        protected Context mContext;
        protected  List<CutRuleRealm> cutRuleRealmList;
        protected  List<HkTransRealm> hkTransRealmList;
        public DataThread(Context context,List<CutRuleRealm> cutRuleRealmList,List<HkTransRealm> hkTransRealmList) {
            this.mContext = context;
            this.cutRuleRealmList = cutRuleRealmList;
            this.hkTransRealmList = hkTransRealmList;
        }
        @Override
        public void run() {
            if (cutRuleRealmList!=null || hkTransRealmList!=null){
                // 线程逻辑
                addCutRule(cutRuleRealmList,hkTransRealmList);
            }

        }
    }

    private  void addCutRule(List<CutRuleRealm> cutRuleRealmList,List<HkTransRealm> hkTransRealmList){
        Realm mRealm = Realm.getDefaultInstance();

        //同步操作写法一：
        mRealm.beginTransaction();
        if (cutRuleRealmList!=null && cutRuleRealmList.size()>0){
            mRealm.insertOrUpdate(cutRuleRealmList); // 将列表中的对象批量插入到数据库中
        }

        if (hkTransRealmList!=null && hkTransRealmList.size()>0){
            mRealm.insertOrUpdate(hkTransRealmList); // 将列表中的对象批量插入到数据库中
        }



        //提交事务，操作就被执行
        mRealm.commitTransaction();



        if (hkTransRealmList!=null && hkTransRealmList.size()>0){
            SPCache spCache = SPCache.getInstance(mContext);
            String ossHost = spCache.getResourceHost();

            RealmResults<HkTransRealm> allList   =  mRealm.where(HkTransRealm.class).distinct("batch").findAll();
            //查询所有批次
            ArrayList<String> delBatchList = new ArrayList<>();
            for (int i = 0; i <allList.size() ; i++) {
                delBatchList.add(allList.get(i).getBatch());
            }

            for (int i=0;i<hkTransRealmList.size();i++){

                long count  = mRealm.where(HkTransDetailRealm.class)
                        .equalTo("version",hkTransRealmList.get(i).getVersion())
                        .equalTo("batch_number",hkTransRealmList.get(i).getBatch())
                        .count();

                if (count==0){
                    addHkTransDetail(ossHost,hkTransRealmList.get(i) );
                }

                delBatchList.remove(hkTransRealmList.get(i).getBatch());

            }




            String[] needDelList =   new String[delBatchList.size()];
            for (int i = 0; i < delBatchList.size(); i++) {
                needDelList[i] = delBatchList.get(i);
            }
            delBatchList(needDelList);
        }


        mRealm.close();
    }

    private void delBatchList(String[] delBatchList){


        Realm mRealm = Realm.getDefaultInstance();
        mRealm.beginTransaction();


        RealmResults<HkTransRealm>  oldList =  mRealm.where(HkTransRealm.class)
                .in("batch",  delBatchList)
                .findAll();
        if (oldList != null && oldList.size()>0) {
            oldList.deleteAllFromRealm();
        }


        RealmResults<HkTransDetailRealm>  oldDetailList =  mRealm.where(HkTransDetailRealm.class)
                .in("batch_number",  delBatchList)
                .findAll();
        if (oldDetailList != null && oldDetailList.size()>0) {
            oldDetailList.deleteAllFromRealm();
        }

        mRealm.commitTransaction();
        mRealm.close();
    }


    private void addHkTransDetail(String ossHost , final HkTransRealm hkTransRealm){

        OkGo.<String>get(ossHost + hkTransRealm.getPath() + "?v=" + UUID.randomUUID().toString())
                .execute(new MyDialogCallback(mContext, false, false) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {

                        try {
                            long timestampMillis = System.currentTimeMillis();

                            String dataStr = response.body().toString();
                            List<HkTransDetailRealm> hkTransDetailRealmList = JsonUtil.jsonString2Beans(dataStr,HkTransDetailRealm.class);
                            Random random = new Random();
                            int randomNumber = random.nextInt(100);  // 生成0-99之间的随机数

                            Realm mRealm = Realm.getDefaultInstance();

                            for (int i = 0; i <hkTransDetailRealmList.size() ; i++) {
                                String id = timestampMillis+"-"+randomNumber+i;
                                hkTransDetailRealmList.get(i).setId(id);
                                hkTransDetailRealmList.get(i).setBatchNumber(hkTransRealm.getBatch());
                                hkTransDetailRealmList.get(i).setVersion(hkTransRealm.getVersion());
                            }

                            mRealm.beginTransaction();
                            mRealm.insertOrUpdate(hkTransDetailRealmList);
                            RealmResults<HkTransDetailRealm>  oldList =  mRealm.where(HkTransDetailRealm.class)
                                    .lessThan("version",hkTransRealm.getVersion())
                                    .equalTo("batch_number",hkTransRealm.getBatch())
                                    .findAll();
                            if (oldList != null && oldList.size()>0) {
                                oldList.deleteAllFromRealm();
                            }

                            mRealm.commitTransaction();
                            mRealm.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("获取json错误");
                        }


                    }
                });

    }



}
