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.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.JsonObject;
import com.liquidnet.common.cache.redis.util.RedisUtil;
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.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.param.CheckPerformanceRelationParam;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinCheckUserPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinCheckUserVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketPartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketTimesPartnerVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.platform.utils.DataUtils;
import com.liquidnet.service.platform.utils.PerformanceVoTask;
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 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.DigestUtils;
import org.springframework.util.MultiValueMap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DataImpl {

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

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisUtil redisUtil;
    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) redisUtil.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() * 5;
                //获取商品每日任务积分
                String resultData = HttpUtil.get("http://devmall.zhengzai.tv/admin/sumUserCost?user_id=" + 1, null);
                int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
                score += goodsPrice * 5;
                //获取 关注摩登天空服务号
                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) redisUtil.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() * 5;
            //获取商品每日任务积分
            String resultData = HttpUtil.get("http://devmall.zhengzai.tv/admin/sumUserCost?user_id=" + 1, null);
            int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
            score += goodsPrice * 5;

            //获取 关注摩登天空服务号
            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_WECHAT_USER_UNIONID_PHONE.concat(phone);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return null;
        } else {
            return (String) obj;
        }
    }
}
