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.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
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.base.ResponseDto;
import com.liquidnet.service.feign.stone.api.FeignStoneIntegralClient;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.entity.KylinExpressModule;
import com.liquidnet.service.kylin.entity.KylinPerformanceRelations;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.merchant.constant.MerchantRedisConst;
import com.liquidnet.service.merchant.dto.vo.MerchantFieldsVo;
import com.liquidnet.service.merchant.entity.MerchantFields;
import com.liquidnet.service.merchant.mapper.MerchantFieldsMapper;
import com.liquidnet.service.platform.utils.ObjectUtil;
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.entity.SweetArtists;
import com.liquidnet.service.sweet.vo.SweetAppletUsersVo;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
import com.mongodb.BasicDBObject;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
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.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class DataImpl {

    @Value("${liquidnet.service.adam.url}")
    private String adamUrl;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;
    @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;
    @Autowired
    FeignStoneIntegralClient stoneIntegralClient;
    @Autowired
    MerchantFieldsMapper merchantFieldsMapper;
    @Autowired
    KylinPerformanceRelationsMapper kylinPerformanceRelationsMapper;


    public boolean initScore(int page, int size) {
        try {
            long adamUserListCount = userMapper.selectCount(Wrappers.lambdaQuery(AdamUser.class).eq(AdamUser::getState, 1)
                    .lt(AdamUser::getMid, 2753314)
                    .select(AdamUser::getUid).orderByAsc(AdamUser::getMid));
            int number = page;
            int fount = 5000;
            while (adamUserListCount > 0) {
                //查询全部用户
                List<AdamUser> adamUserList = userMapper.selectList(Wrappers.lambdaQuery(AdamUser.class).eq(AdamUser::getState, 1)
                        .lt(AdamUser::getMid, 2753314)
                        .select(AdamUser::getUid).orderByAsc(AdamUser::getMid).last("limit " + ((number - 1) * fount) + "," + ((number) * fount)));
                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 isLog = stoneScoreLogsMapper.selectCount(Wrappers.lambdaQuery(StoneScoreLogs.class).eq(StoneScoreLogs::getUid, uid).eq(StoneScoreLogs::getContent, "历史积分"));
                    if (isLog > 0) {
                        continue;
//                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
//                    params.add("uid", uid);
//                    params.add("score", (score >= 12000 ? 12000 : score) + "");
//                    params.add("content", "历史积分");
//                    HttpUtil.post(stoneUrl + "/user/logs/in2111", params);
                    }

                    //创建 用户积分数据
                    int isExists = stoneScoreUserMapper.selectCount(Wrappers.lambdaQuery(StoneScoreUser.class).eq(StoneScoreUser::getUid, uid));
                    if (isExists <= 0) {
                        StoneScoreUser data = StoneScoreUser.getNew();
                        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());
                    //获取商品每日任务积分
                    try {
                        String resultData = HttpUtil.get("http://mall.zhengzai.tv/admin/sumUserCost?user_id=" + uid, null);
                        int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
                        score += (goodsPrice);
                    } catch (Exception e) {

                    }

                    //获取 关注摩登天空服务号
                    if (getUnionIdByPhone(mobile) != null) {
                        stoneIntegralClient.doTask(4, uid);
//                    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()) {
                        //获取 完善个人信息
                        stoneIntegralClient.doTask(5, uid);
//                    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())) {
                        //获取 完善个人照片
                        stoneIntegralClient.doTask(6, uid);
//                    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);
//                }
                    stoneIntegralClient.in2111(uid, score, "历史积分");
                    log.error("[ TASK INIT UID ] uid = " + uid);
                }
                log.error("[ TASK INIT NUMBER ] number = " + number);
                adamUserListCount -= fount;
                number += 1;
            }
            log.error("[ TASK INIT SCORE ] FINISH ");
        } 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));
            String mobile = userInfoVo.getMobile();
            int score = 0;

            //生成用户积分日志
            int isLog = stoneScoreLogsMapper.selectCount(Wrappers.lambdaQuery(StoneScoreLogs.class).eq(StoneScoreLogs::getUid, uid).eq(StoneScoreLogs::getContent, "历史积分"));
            if (isLog > 0) {
                return true;
//                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
//                    params.add("uid", uid);
//                    params.add("score", (score >= 12000 ? 12000 : score) + "");
//                    params.add("content", "历史积分");
//                    HttpUtil.post(stoneUrl + "/user/logs/in2111", params);
            }

            //创建 用户积分数据
            int isExists = stoneScoreUserMapper.selectCount(Wrappers.lambdaQuery(StoneScoreUser.class).eq(StoneScoreUser::getUid, uid));
            if (isExists <= 0) {
                StoneScoreUser data = StoneScoreUser.getNew();
                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());
            //获取商品每日任务积分
            try {
                String resultData = HttpUtil.get("http://mall.zhengzai.tv/admin/sumUserCost?user_id=" + uid, null);
                int goodsPrice = (int) JSONObject.parseObject(resultData).get("cost");
                score += (goodsPrice);
            } catch (Exception e) {

            }

            //获取 关注摩登天空服务号
            if (getUnionIdByPhone(mobile) != null) {
                stoneIntegralClient.doTask(4, uid);
//                    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()) {
                //获取 完善个人信息
                stoneIntegralClient.doTask(5, uid);
//                    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())) {
                //获取 完善个人照片
                stoneIntegralClient.doTask(6, uid);
//                    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);
//                }
            stoneIntegralClient.in2111(uid, score, "历史积分");
            log.error("[ TASK INIT UID ] uid = " + uid);
            log.error("[ TASK INIT SCORE ] FINISH ");
        } catch (Exception e) {
            log.info("异常 : {} ", 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 = StoneScoreLogs.getNew();
            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;
    }


    private static final String SQL_URL = "jdbc:mysql://39.107.71.112:3308/dev_ln_scene";
    private static final String SQL_USER = "testmall";
    private static final String SQL_PWD = "zhengzai!mYT";

    //迁移场地和场地认领关系
    public void fieldData() {
        try {
            String sql = "select mf.id                                                   AS 'field_id',\n" +
                    "       1                                                       AS 'is_online',\n" +
                    "       0                                                       AS 'is_check',\n" +
                    "       mf.`name`                                               AS 'name',\n" +
                    "       ''                                                      AS 'logo',\n" +
                    "       IF(LEFT(mf.cover_img, 4) = 'http', mf.cover_img, '')    AS 'background',\n" +
                    "       IF(ISNULL(mf.description), '', mf.description)          AS 'description',\n" +
                    "       NULL                                                    AS 'built_date',\n" +
                    "       mf.province_id                                          AS 'province_id',\n" +
                    "       mf.province_name                                        AS 'province_name',\n" +
                    "       mf.city_id                                              AS 'city_id',\n" +
                    "       mf.city_name                                            AS 'city_name',\n" +
                    "       IF(mf.ad_code > 7000, mf.ad_code, '')                   AS 'district_id',\n" +
                    "       mf.district_name                                        AS 'district_name',\n" +
                    "       mf.address                                              AS 'address',\n" +
                    "       mf.longitude                                            AS 'longitude',\n" +
                    "       mf.latitude                                             AS 'latitude',\n" +
                    "       mm.`name`                                               AS 'contact_name',\n" +
                    "       mm.mobile                                               AS 'contact_mobile',\n" +
                    "       mm.email                                                AS 'contact_email',\n" +
                    "       ''                                                      AS 'company_id',\n" +
                    "       IF(ISNULL(mf.created_at), mf.updated_at, mf.created_at) AS 'created_at',\n" +
                    "       mf.updated_at                                           AS 'updated_at',\n" +
                    "       mf.admin_id\n" +
                    "from kylin_performances as kp\n" +
                    "         inner join kylin_performance_relations as kpr on kpr.performance_id = kp.performances_id\n" +
                    "         inner join testmall.fields as mf on mf.id = kpr.field_id\n" +
                    "         left join testmall.merchants as mm on mm.id = mf.admin_id\n" +
                    "group by field_id";
            Connection connection = DriverManager.getConnection(SQL_URL, SQL_USER, SQL_PWD);
            //查询数据
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSetImpl row = (ResultSetImpl) preparedStatement.executeQuery();
            //数据迁移
            while (row.next()) {
                MerchantFields fields = new MerchantFields();
                fields.setFieldId(row.getString("field_id"));
                fields.setIsOnline(row.getInt("is_online"));
                String contactMobile = row.getString("contact_mobile");
                //判断场地认领逻辑
                if (null != contactMobile && !contactMobile.isEmpty()) {
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("mobile", contactMobile);
                    MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
                    headers.add("Accept", "application/json;charset=UTF-8");
                    String returnData = HttpUtil.post(adamUrl.concat("/adam/rsc/reg/mobile"), params, headers);
                    AdamUserInfoVo adamUserInfoVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserInfoVo>>() {
                    }).getData();
                    String uid = adamUserInfoVo.getUid();
                    fields.setClaimStatus(1);
                    fields.setUid(uid);
                } else {
                    fields.setClaimStatus(0);
                    fields.setUid("");
                }
                //完成
                fields.setIsCheck(row.getInt("is_check"));
                fields.setName(row.getString("name"));
                fields.setLogo(row.getString("logo"));
                fields.setBackground(row.getString("background").contains(".") ? row.getString("background") : "");
                fields.setDescription("空".equals(row.getString("description")) ? "" : row.getString("description"));
                fields.setBuiltDate(null != row.getDate("built_date") ? row.getDate("built_date").toLocalDate() : null);
                fields.setProvinceId(row.getString("province_id"));
                fields.setProvinceName(row.getString("province_name"));
                fields.setCityId(row.getString("city_id"));
                fields.setCityName(row.getString("city_name"));
                fields.setDistrictId(row.getString("district_id"));
                fields.setDistrictName(row.getString("district_name"));
                fields.setAddress(null != row.getString("address") ? row.getString("address") : "");
                fields.setLongitude(row.getString("longitude").contains(".") ? row.getString("longitude") : "");
                fields.setLatitude(row.getString("latitude").contains(".") ? row.getString("longitude") : "");
                fields.setContactName(null != row.getString("contact_name") ? row.getString("contact_name") : "");
                fields.setContactEmail(null != row.getString("contact_email") ? row.getString("contact_email") : "");
                fields.setCompanyId(row.getString("company_id"));
                fields.setCreatedAt(row.getTimestamp("created_at").toLocalDateTime());
                fields.setUpdatedAt(row.getTimestamp("updated_at").toLocalDateTime());
                MerchantFieldsVo vo = MerchantFieldsVo.getNew().copy(fields);

                //MYSQL
                merchantFieldsMapper.insert(fields);
                //MONGO
                setFieldsVoByFieldId(fields.getFieldId(), vo);
                //REDIS
                setRdsFieldsVoByFieldId(fields.getFieldId(), vo);
            }
            row.close();
            preparedStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //演出所属账号修改
    public void account() {
        try {
            String sql = "select merchant_id, mm.mobile\n" +
                    "from kylin_performances kp\n" +
                    "         inner join kylin_performance_relations kpr on kpr.performance_id = kp.performances_id\n" +
                    "         left join testmall.merchants mm on mm.id = kpr.merchant_id\n" +
                    "group by mm.mobile";
            Connection connection = DriverManager.getConnection(SQL_URL, SQL_USER, SQL_PWD);
            //查询数据
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSetImpl row = (ResultSetImpl) preparedStatement.executeQuery();
            //数据迁移
            while (row.next()) {
                String mobile = row.getString("mobile");
                String merchantId =row.getString("merchant_id");
                if(mobile==null){
                    continue;
                }
                //获取java用户id
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("mobile", mobile);
                MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
                headers.add("Accept", "application/json;charset=UTF-8");
                String returnData = HttpUtil.post(adamUrl.concat("/adam/rsc/reg/mobile"), params, headers);
                AdamUserInfoVo adamUserInfoVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserInfoVo>>() {
                }).getData();
                String uid = adamUserInfoVo.getUid();
                KylinPerformanceRelations kylinPerformanceRelations = KylinPerformanceRelations.getNew();
                kylinPerformanceRelations.setMerchantId(uid);
                kylinPerformanceRelationsMapper.update(kylinPerformanceRelations,
                        Wrappers.lambdaUpdate(KylinPerformanceRelations.class).eq(KylinPerformanceRelations::getMerchantId, merchantId));

                HashMap<String,Object> map = CollectionUtil.mapStringObject();
                map.put("merchantId",merchantId);
                //修改vo
                Query voQuery = Query.query(Criteria.where("merchantId").is(merchantId));
                BasicDBObject objectVo = ObjectUtil.cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(KylinPerformanceVo.class.getSimpleName()).updateOne(
                        voQuery.getQueryObject(),
                        objectVo
                );
                //修改partnerVo
                Query partnerVoQuery = Query.query(Criteria.where("merchantId").is(merchantId));
                BasicDBObject objectPartnerVo = ObjectUtil.cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateOne(
                        partnerVoQuery.getQueryObject(),
                        objectPartnerVo
                );
            }
            row.close();
            preparedStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //演出主办
//    public void sponsor() {
//        try {
//            String sql = "select sponsor_id,sponsor_type from kylin_performances kp\n" +
//                    "inner join kylin_performance_status kps on kps.performance_id = kp.performances_id\n" +
//                    "where status >=3 and sponsor_id != ''\n" +
//                    "group by sponsor_id,sponsor_type;";
//            Connection connection = DriverManager.getConnection(SQL_URL, SQL_USER, SQL_PWD);
//            //查询数据
//            PreparedStatement preparedStatement = connection.prepareStatement(sql);
//            ResultSetImpl row = (ResultSetImpl) preparedStatement.executeQuery();
//            //数据迁移
//            while (row.next()) {
//                String sponsorId = row.getString("sponsor_id");
//                String sponsorType =row.getString("sponsor_type");
//                if(mobile==null){
//                    continue;
//                }
//                //获取java用户id
//                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
//                params.add("mobile", mobile);
//                MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
//                headers.add("Accept", "application/json;charset=UTF-8");
//                String returnData = HttpUtil.post(adamUrl.concat("/adam/rsc/reg/mobile"), params, headers);
//                AdamUserInfoVo adamUserInfoVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserInfoVo>>() {
//                }).getData();
//                String uid = adamUserInfoVo.getUid();
//                KylinPerformanceRelations kylinPerformanceRelations = KylinPerformanceRelations.getNew();
//                kylinPerformanceRelations.setMerchantId(uid);
//                kylinPerformanceRelationsMapper.update(kylinPerformanceRelations,
//                        Wrappers.lambdaUpdate(KylinPerformanceRelations.class).eq(KylinPerformanceRelations::getMerchantId, merchantId));
//
//                HashMap<String,Object> map = CollectionUtil.mapStringObject();
//                map.put("merchantId",merchantId);
//                //修改vo
//                Query voQuery = Query.query(Criteria.where("merchantId").is(merchantId));
//                BasicDBObject objectVo = ObjectUtil.cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(map));
//                mongoTemplate.getCollection(KylinPerformanceVo.class.getSimpleName()).updateOne(
//                        voQuery.getQueryObject(),
//                        objectVo
//                );
//                //修改partnerVo
//                Query partnerVoQuery = Query.query(Criteria.where("merchantId").is(merchantId));
//                BasicDBObject objectPartnerVo = ObjectUtil.cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(map));
//                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateOne(
//                        partnerVoQuery.getQueryObject(),
//                        objectPartnerVo
//                );
//            }
//            row.close();
//            preparedStatement.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    //相关权限迁移

    private void setFieldsVoByFieldId(String fieldId, MerchantFieldsVo vo) {
        Query query = Query.query(Criteria.where("fieldId").is(fieldId));
        Document document = (Document) mongoConverter.convertToMongoType(vo);
        Update update = Update.fromDocument(document);
        mongoTemplate.upsert(query, update, MerchantFieldsVo.class, MerchantFieldsVo.class.getSimpleName());
    }

    // 【场地】更新详情
    private void setRdsFieldsVoByFieldId(String fieldId, MerchantFieldsVo vo) {
        redisDataSourceUtil.getRedisKylinUtil().set(MerchantRedisConst.INFO_FIELD.concat(fieldId), vo);
    }
}
