package cn.quantgroup.xyqb.service.user.impl;

import cn.quantgroup.user.enums.OccupationEnum;
import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.repository.IUserExtInfoRepository;
import cn.quantgroup.xyqb.service.user.CleanDataService;
import cn.quantgroup.xyqb.service.user.IUserExtInfoService;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：dongjianhua
 * @date ：Created in 2020/7/17 11:32
 * @description：清洗数据
 * @modified By：
 * @version: 1.0
 */
@Slf4j
@Service
public class CleanDataServiceImp implements CleanDataService {
    @Resource
    private IUserExtInfoService iUserExtInfoService;

    @Autowired
    private IUserExtInfoRepository userExtInfoRepository;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate<String, String> stringRedisTemplate;

    public final String LOCKKEY = "681F0307-C7F9-11EA-A303-0A58AC100553";

    @Async
    @Override
    public Map<String, Object> cleanData() {

        Map<String, Object> re = Maps.newHashMap();


        try {
            Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(LOCKKEY, "lock");


            if (!lock) {
                return re;
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Stopwatch s = Stopwatch.createStarted();

            Date parse = null;
            try {
                parse = sf.parse("2015-08-14 00:00:00");
//            parse = sf.parse("2020-01-01 00:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            long all = 0L;
            while (true) {

                Timestamp start = new Timestamp(calendar.getTime().getTime());
                calendar.add(Calendar.MONTH, 1);
                Timestamp end = new Timestamp(calendar.getTime().getTime());

                String starDate = (start.getYear() + 1900) + "年" + (start.getMonth() + 1) + "月" + start.getDate() + "日";
                String endDate = (end.getYear() + 1900) + "年" + (end.getMonth() + 1) + "月" + end.getDate() + "日";

                try {
                    List<UserExtInfo> list = iUserExtInfoService.findByCreatedAtAfterAndCreatedAtBeforeAndOccupationEnum(start, end);

                    if (!CollectionUtils.isEmpty(list)) {
                        for (UserExtInfo userExtInfo : list) {
                            try {
                                userExtInfo.setOccupationEnum(OccupationEnum.OTHER);
                                iUserExtInfoService.save(userExtInfo);
                                all++;
                            } catch (Exception e) {
                                log.error("保存异常o：{} ", userExtInfo);
                            }
                        }
                    }
                    log.info("开始时间start：{},结束时间end： {} ,条数:{}", starDate, endDate, list.size());

                    re.put(starDate + "-" + endDate, list.size());
                    if (end.after(new Date())) {
                        break;
                    }
                } catch (Exception e) {
                    log.error("时间段：{}--{}执行异常，e", starDate, endDate, e);
                }
                log.info("清洗结束总共清洗了all:{}条,耗时：{}秒", all, s.elapsed(TimeUnit.SECONDS));
            }
            log.info("清洗明细：{} ", re);
        } catch (Exception e) {
            log.error("清洗的时候出现了异常e:{}", e);
        } finally {
            stringRedisTemplate.delete(LOCKKEY);
        }
        return null;
    }
}
