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.mapper.*;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
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)));
            for (AdamUser item : adamUserList) {
                //获取用户相关信息
                String uid = item.getUid();
                String mobile = item.getMobile();
                AdamUserInfoVo userInfoVo = (AdamUserInfoVo) redisDataSourceUtil.getRedisAdamUtil().get(AdamRedisConst.INFO_USER.concat(uid));
                if (userInfoVo == 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");
                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 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;
    }

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

    public String getUnionIdByPhone(String 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.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";
        }
    }
}
