package cn.com.victorysoft.business.calc.service;

import cn.com.victorysoft.business.calc.dao.FlushDataSyncDao;
import cn.com.victorysoft.business.calc.dao.WellToolDataSyncDao;
import cn.com.victorysoft.business.sys.entity.WellSectionDaily;
import cn.com.victorysoft.business.sys.param.UnitWellMonthPageParam;
import cn.com.victorysoft.business.technology.dao.WellToolDao;
import cn.com.victorysoft.business.technology.entity.WellTool;
import cn.com.victorysoft.business.util.BeanUtils;
import cn.com.victorysoft.business.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 井下工具数据同步服务
 */
@Slf4j
@Service
public class WellToolDataSyncService {

    @Resource
    private WellToolDataSyncDao wellToolDataSyncDao;
    @Resource
    private WellToolDao wellToolDao;

    /**
     * 同步数据
     */
    @Transactional
    public void sync(Date startDate, Date endDate) {
        String month = DateUtils.format(endDate, "yyyyMM");
        String prevMonth = DateUtils.format(DateUtils.addMonths(endDate, -1), "yyyyMM");
        // 查询源头
        List<WellTool> list = wellToolDataSyncDao.selectList(startDate, endDate);
        Map<String, WellTool> wellToolMap = list.stream().collect(Collectors.toMap(WellTool::getJh, v -> v));
        // 查询上月
        UnitWellMonthPageParam param = new UnitWellMonthPageParam();
        param.setMonth(prevMonth);
        List<WellTool> prevMonthList = wellToolDao.selectList(param);
        Map<String, WellTool> prevMonthMap = prevMonthList.stream().collect(Collectors.toMap(WellTool::getJh, v -> v));
        // 合并源头数据和上月数据
        for (WellTool wellTool : list) {
            WellTool prevWellTool = prevMonthMap.get(wellTool.getJh());
            if (prevWellTool != null) {
                BeanUtils.mergeBean(wellTool, prevWellTool);
            }
        }
        if (list.size() > 0) {
            // 先删除，后插入
            wellToolDao.deleteByMonth(month);
            // 每批commit的个数
            int batchCount = 500;
            int index = 0;
            do {
                int batchLastIndex = Math.min(index + batchCount, list.size());
                List<WellTool> tmp = list.subList(index, batchLastIndex);
                wellToolDao.insertBatch(tmp);
                index = index + batchCount;
            } while (index < list.size());
        }
    }

}
