package com.liquidnet.service.platform.service.impl.kylin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.adam.entity.AdamUser;
import com.liquidnet.service.adam.mapper.AdamUserMapper;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.stone.constant.StoneConstant;
import com.liquidnet.service.stone.entity.StoneScoreLogs;
import com.liquidnet.service.stone.entity.StoneScoreUser;
import com.liquidnet.service.stone.mapper.StoneScoreLogsMapper;
import com.liquidnet.service.stone.mapper.StoneScoreUserMapper;
import com.liquidnet.service.stone.vo.StoneUserVo;
import com.liquidnet.service.sweet.constant.SweetConstant;
import com.liquidnet.service.sweet.vo.SweetAppletUsersVo;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class DataImpl {

    @Value("${liquidnet.service.stone.url}")
    private String stoneUrl;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;
    private static final List<String> defaultBackgroundList = Arrays.asList("https://img.zhengzai.tv/other/2021/07/27/150eeb0e20af4fc88e8a1ec57c46c362.png", "https://img.zhengzai.tv/files/2021/01/13/5ffeab3584b7d.png", "http://pic.zhengzai.tv/default/background.png", "http://img.zhengzai.tv/album/20171027/1509106243302.png");

    @Autowired
    AdamUserMapper userMapper;
    @Autowired
    KylinOrderTicketsMapper orderTicketsMapper;
    @Autowired
    StoneScoreUserMapper stoneScoreUserMapper;
    @Autowired
    StoneScoreLogsMapper stoneScoreLogsMapper;


    public boolean initScore(int page, int size) {
        try {
            //查询全部用户
            List<AdamUser> adamUserList = userMapper.selectList(Wrappers.lambdaQuery(AdamUser.class).eq(AdamUser::getState, 1)
                    .select(AdamUser::getUid).last("limit " + ((page - 1) * size) + "," + ((page) * size)));
            log.info("AdamUserSize = " + adamUserList.size());
            int finishCount = 0;
            for (AdamUser item : adamUserList) {
                //获取用户相关信息
                String uid = item.getUid();
                AdamUserInfoVo userInfoVo = (AdamUserInfoVo) redisDataSourceUtil.getRedisAdamUtil().get(AdamRedisConst.INFO_USER.concat(uid));
                if (userInfoVo == null) {
                    continue;
                }
                String mobile = userInfoVo.getMobile();
                if (mobile == null) {
                    continue;
                }
                int score = 0;
                //创建 用户积分数据
                int isExists = stoneScoreUserMapper.selectCount(Wrappers.lambdaQuery(StoneScoreUser.class).eq(StoneScoreUser::getUid, uid));
                if (isExists <= 0) {
                    StoneScoreUser data = new StoneScoreUser();
                    data.setStatus(1);
                    data.setScoreId(IDGenerator.nextTimeId2());
                    data.setUid(uid);
                    data.setCreatedAt(LocalDateTime.now());
                    stoneScoreUserMapper.insert(data);
                    StoneUserVo userTaskVo = StoneUserVo.getNew();
                    userTaskVo.getTask();
                    userTaskVo.setUid(uid);
                    userTaskVo.setStatus(1);
                    userCreate(userTaskVo);
                }
                //获取演出每日任务积分
                Integer performancePrice = orderTicketsMapper.getOrderScore(uid);
                score += (performancePrice.intValue() / 100);
                //获取商品每日任务积分
                String resultData = HttpUtil.get("http://devmall.zhengzai.tv/admin/sumUserCost?user_id=" + 1, null);
                int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
                try {
                    score += (goodsPrice / 100);
                }catch (Exception e){

                }

                //获取 关注摩登天空服务号
                if (getUnionIdByPhone(mobile) != null) {
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("uid", uid);
                    params.add("taskId", 4 + "");
                    HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
                }
                //获取用户相关信息
                if (null != userInfoVo.getSex()) {
                    //获取 完善个人信息
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("uid", uid);
                    params.add("taskId", 5 + "");
                    HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
                }
                if (StringUtils.isNotBlank(userInfoVo.getBackground()) && !defaultBackgroundList.contains(userInfoVo.getBackground())) {
                    //获取 完善个人照片
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("uid", uid);
                    params.add("taskId", 6 + "");
                    HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
                }
//                if (userInfoVo.getIsComplete() == 11) {
//                    //获取 首次体验在场
//                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
//                    params.add("uid", uid);
//                    params.add("taskId", 8 + "");
//                    HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
//                }
                //生成用户积分日志
                int isLog = stoneScoreLogsMapper.selectCount(Wrappers.lambdaQuery(StoneScoreLogs.class).eq(StoneScoreLogs::getUid, uid).eq(StoneScoreLogs::getContent, "历史积分"));
                if (isLog <= 0) {
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("uid", uid);
                    params.add("score", score + "");
                    params.add("content", "历史积分");
                    HttpUtil.post(stoneUrl + "/user/logs/in2111", params);
                }
                finishCount += 1;
            }
            log.info("完成次数 = " + finishCount);
        } catch (Exception e) {
            log.info("异常 : {} ", e);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean initScore(String uid) {
        try {
            //获取用户相关信息
            AdamUserInfoVo userInfoVo = (AdamUserInfoVo) redisDataSourceUtil.getRedisAdamUtil().get(AdamRedisConst.INFO_USER.concat(uid));
            int score = 0;
            String mobile = userInfoVo.getMobile();
            //创建 用户积分数据
            int isExists = stoneScoreUserMapper.selectCount(Wrappers.lambdaQuery(StoneScoreUser.class).eq(StoneScoreUser::getUid, uid));
            if (isExists <= 0) {
                StoneScoreUser data = new StoneScoreUser();
                data.setStatus(1);
                data.setScoreId(IDGenerator.nextTimeId2());
                data.setUid(uid);
                data.setCreatedAt(LocalDateTime.now());
                stoneScoreUserMapper.insert(data);

                StoneUserVo userTaskVo = StoneUserVo.getNew();
                userTaskVo.getTask();
                userTaskVo.setUid(uid);
                userTaskVo.setStatus(1);
                userCreate(userTaskVo);
            }
            //获取演出每日任务积分
            Integer performancePrice = orderTicketsMapper.getOrderScore(uid);
            score += performancePrice.intValue() / 100;
            //获取商品每日任务积分
            String resultData = HttpUtil.get("http://devmall.zhengzai.tv/admin/sumUserCost?user_id=" + 1, null);
            int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
            score += goodsPrice / 100;

            //获取 关注摩登天空服务号
            if (getUnionIdByPhone(mobile) != null) {
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("uid", uid);
                params.add("taskId", 4 + "");
                HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
            }
            //获取用户相关信息
            if (null != userInfoVo.getSex()) {
                //获取 完善个人信息
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("uid", uid);
                params.add("taskId", 5 + "");
                HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
            }
            if (StringUtils.isNotBlank(userInfoVo.getBackground()) && !defaultBackgroundList.contains(userInfoVo.getBackground())) {
                //获取 完善个人照片
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("uid", uid);
                params.add("taskId", 6 + "");
                HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
            }
//            if (userInfoVo.getIsComplete() == 11) {
//                //获取 首次体验在场
//                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
//                params.add("uid", uid);
//                params.add("taskId", 8 + "");
//                HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
//            }
            //生成用户积分日志
            int isLog = stoneScoreLogsMapper.selectCount(Wrappers.lambdaQuery(StoneScoreLogs.class).eq(StoneScoreLogs::getUid, uid).eq(StoneScoreLogs::getContent, "历史积分"));
            if (isLog <= 0) {
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("uid", uid);
                params.add("score", score + "");
                params.add("content", "历史积分");
                HttpUtil.post(stoneUrl + "/user/logs/in2111", params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean initLogs(String uid) {
        List<StoneScoreLogs> list = stoneScoreLogsMapper.selectList(Wrappers.lambdaQuery(StoneScoreLogs.class).eq(StoneScoreLogs::getUid, uid));
        mongoTemplate.remove(Query.query(Criteria.where("uid").is(uid)), StoneScoreLogs.class, StoneScoreLogs.class.getSimpleName());
        String redisKey = StoneConstant.LOGS_LIST.concat(uid);
        redisDataSourceUtil.getRedisStoneUtil().del(redisKey);
        int scoreAll = 0;
        int scoreUse = 0;
        for (StoneScoreLogs item : list) {
            //初始化 mongo
            StoneScoreLogs logs = new StoneScoreLogs();
            logs.setLogsId(item.getLogsId());
            logs.setContent(item.getContent());
            logs.setReason(item.getReason());
            logs.setUid(uid);
            logs.setScore(item.getScore());
            logs.setCreatedAt(item.getCreatedAt());
            if (item.getScore().intValue() < 0) {
                scoreUse += item.getScore().negate().intValue();
            } else {
                scoreAll += item.getScore().intValue();
            }
            logCreate(logs);
        }
        //初始化 redis
        List<StoneScoreLogs> getLogsList = (List<StoneScoreLogs>) logList(uid, 1, 40).get("data");
        redisDataSourceUtil.getRedisStoneUtil().set(redisKey, getLogsList);
        String restKey = StoneConstant.USER.concat(uid).concat(StoneConstant.SURPLUS_SCORE);
        String useKey = StoneConstant.USER.concat(uid).concat(StoneConstant.USE_SCORE);
        redisDataSourceUtil.getRedisStoneUtil().set(useKey, scoreUse);
        redisDataSourceUtil.getRedisStoneUtil().set(restKey, scoreAll - scoreUse);
        return true;
    }

    /**
     * 创建 用户积分
     *
     * @param data
     * @return
     */
    private Object userCreate(StoneUserVo data) {
        return mongoTemplate.insert(data, StoneUserVo.class.getSimpleName());
    }

    private String getUnionIdByPhone(String phone) {
        log.info("mobile = " + phone);
        String redisKey = SweetConstant.REDIS_KEY_SWEET_APPLET_USERS_PHONE.concat(phone);
        Object obj = redisDataSourceUtil.getRedisSweetUtil().get(redisKey);
        if (null == obj) {
            return null;
        }
        SweetAppletUsersVo sweetAppletUsers = (SweetAppletUsersVo) obj;

        String redisKey2 = SweetConstant.REDIS_KEY_SWEET_WECHAT_USERS_UNIONID.concat(sweetAppletUsers.getUnionId())
                .concat(SweetConstant.REDIS_KEY_SWEET_WECHAT_USERS_TYPE).concat(String.valueOf(2));
        Object obj2 = redisDataSourceUtil.getRedisSweetUtil().get(redisKey2);
        if (null == obj2) {
            return null;
        } else {
            return "true";
        }
    }

    public Object logCreate(StoneScoreLogs data) {
        return mongoTemplate.insert(data, StoneScoreLogs.class.getSimpleName());
    }

    public HashMap<String, Object> logList(String uid, int page, int size) {
        LocalDateTime now = LocalDateTime.now();
        HashMap<String, Object> info = CollectionUtil.mapStringObject();
        // 排序 分页
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        //条件
        Query query = Query.query(Criteria.where("uid").is(uid));
        // 查询总数
        long count = mongoTemplate.count(query, StoneScoreLogs.class, StoneScoreLogs.class.getSimpleName());
        query.with(pageable);
        List<StoneScoreLogs> voList = mongoTemplate.find(query, StoneScoreLogs.class, StoneScoreLogs.class.getSimpleName());
        info.put("total", count);
        info.put("data", voList);
        return info;
    }
}
