package com.liquidnet.service.adam.service.processor;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.ServletUtils;
import com.liquidnet.service.adam.dto.vo.AdamTagVo;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.adam.entity.AdamUser;
import com.liquidnet.service.adam.entity.AdamUserInfo;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.liquidnet.service.adam.service.IAdamUserInfoService;
import com.liquidnet.service.adam.service.IAdamUserService;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DMUserInformationProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamUserService adamUserService;
    @Autowired
    IAdamUserInfoService adamUserInfoService;

    public static final String DM_FAILED_USER = "dm:failed:uid";
    public static final String DM_EXISTS_USER = "dm:exists:uid";
    public static Map<String, AdamTagVo> sexMap = new HashMap<>();

    static {
        sexMap.put("SECRET", AdamTagVo.getNew().setVal("MS00").setDesc("保密"));
        sexMap.put("MALE", AdamTagVo.getNew().setVal("MS01").setDesc("男性"));
        sexMap.put("FEMALE", AdamTagVo.getNew().setVal("MS02").setDesc("女性"));
    }

    @SneakyThrows
    @Override
    protected void dataProcessing() {
        HttpServletRequest request = ServletUtils.getRequest();
        String lS = request.getParameter(DM_LS), incrDt = request.getParameter(DM_INCR_DT),
                flg = StringUtils.defaultIfBlank(request.getParameter(DM_FLG), "");
        if (StringUtils.isNotEmpty(request.getParameter(DM_FLUSH))) {
            log.info("DM.flush.user:{}", userMapper.executeForDM("adam_user"));
            log.info("DM.flush.user_info:{}", userMapper.executeForDM("adam_user_info"));

            log.info("DM.flush.AdamUserInfoVo:{}", mongoTemplate.remove(Query.query(Criteria.where("_id").exists(true)), AdamUserInfoVo.class.getSimpleName()).getDeletedCount());
        }

        String sqlCount = "select count(1) from users where delete_tag in (0,1) and length(mobile)=11 and created_at" + (StringUtils.isBlank(incrDt) ? "<" : ">=") + "curdate()";
        String field = "uid,mobile,username,sex,birthday,area,sign,face_url,back_url,created_at,updated_at,is_complete,rong_cloud_token,rong_cloud_tag";
//                     1-uid,2-mobile,3-username,4-sex,5-birthday,6-area,7-sign,8-face_url,9-back_url,10-created_at,11-updated_at,12-is_complete,13-rong_cloud_token,14-rong_cloud_tag
        String sql = sqlCount.replace("count(1)", field);
        if ("1".equals(flg)) {
            sqlCount += "and mobile in ('13753596360','17701223310','18518013286','18548596019','15901093014','17382319723','13631444097','13671737873')";
            sql += " and mobile in ('13753596360','17701223310','18518013286','18548596019','15901093014','17382319723','13631444097','13671737873')";
        }
        sql += " order by uid limit ?,?";

        statement = connection.prepareStatement(sqlCount);
        row = (ResultSetImpl) statement.executeQuery();
        row.first();
        int ct = row.getInt(1), pSize = 1000, num = 0, tl = 0, pl = ct;
        log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> start.sql:{}", pl, num, pSize, tl, sql);

        while (ct > 0) {
            statement = connection.prepareStatement(sql);
            int ls = (num == 0 && StringUtils.isNotEmpty(lS)) ? Integer.parseInt(lS) : pSize * num;
            statement.setInt(1, ls);
            statement.setInt(2, pSize);
            row = (ResultSetImpl) statement.executeQuery();
            log.info("DM.execute.limit {},{} - begin", ls, pSize);

            List<AdamUser> userList = new ArrayList<>();
            List<AdamUserInfo> userInfoList = new ArrayList<>();
            List<AdamUserInfoVo> vos = new ArrayList<>();
            while (row.next()) {
                try {
                    AdamTagVo sex = sexMap.get(row.getString(4));
                    String uid = row.getString(1);
                    if (!reUidList.contains(uid)) {
//                        if (userMapper.selectCount(Wrappers.lambdaQuery(AdamUser.class).eq(AdamUser::getUid, uid)) > 0) {
//                            redisUtil.lSet(DM_EXISTS_USER, uid);
//                        } else {
                        AdamUser user = new AdamUser();
                        user.setUid(uid);
                        user.setMobile(row.getString(2));
                        user.setCreatedAt(row.getLocalDateTime(10));
                        user.setUpdatedAt(row.getLocalDateTime(11));
                        user.setState(1);

                        AdamUserInfo userInfo = new AdamUserInfo();
                        userInfo.setUid(user.getUid());
                        userInfo.setNickname(row.getString(3));
                        userInfo.setSex(JsonUtils.toJson(sex));
                        userInfo.setBirthday(row.getLocalDate(5));
                        userInfo.setArea(row.getString(6));
                        userInfo.setSignature(row.getString(7));
                        userInfo.setAvatar(row.getString(8));
                        userInfo.setBackground(row.getString(9));
                        userInfo.setQrCode("lN".concat(userInfo.getUid()).concat(RandomStringUtils.randomAlphanumeric(5).toUpperCase()));
                        userInfo.setRongCloudToken(row.getString(13));
                        userInfo.setRongCloudTag(row.getInt(14));

                        AdamUserInfoVo vo = AdamUserInfoVo.getNew();
                        vo.setUid(user.getUid());
                        vo.setMobile(user.getMobile());
                        vo.setNickname(userInfo.getNickname());
                        vo.setState(user.getState());
                        vo.setSex(sex);
                        vo.setBirthday(DateUtil.Formatter.yyyy_MM_dd.format(userInfo.getBirthday()));
                        vo.setArea(userInfo.getArea());
                        vo.setSignature(userInfo.getSignature());
                        vo.setAvatar(userInfo.getAvatar());
                        vo.setBackground(userInfo.getBackground());
                        vo.setCreateAt(user.getCreatedAt());
                        vo.setUpdatedAt(user.getUpdatedAt());
                        vo.setIsComplete(row.getInt(12));
                        vo.setQrCode(userInfo.getQrCode());

                        userList.add(user);
                        userInfoList.add(userInfo);
                        vos.add(vo);
//                        }
                    }
                } catch (SQLException throwables) {
                    redisUtil.lSet(DM_FAILED_USER, row.getString(1));
                    log.error("DM数据处理异常[uid:{},mobile:{}],{} - {}", row.getString(1), row.getString(2),
                            throwables.getErrorCode(), throwables.getMessage());
                }
            }
            log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, userList.size());
            if (!CollectionUtils.isEmpty(userList)) {
                tl += userList.size();
                mongoTemplate.insert(vos, AdamUserInfoVo.class.getSimpleName());
                log.info("DM.execute.limit.result:{}", adamUserService.saveBatch(userList));
                log.info("DM.execute.limit.result:{}", adamUserInfoService.saveBatch(userInfoList));
            }

            num++;
            ct -= pSize;
        }
        log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> end", pl, num, pSize, tl);
    }
}
