package com.rongwei.bscommon.sys.service.impl;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.config.EquDieseloilUseManagementListener;
import com.rongwei.bscommon.sys.dao.EquDieseloilUseManagementDao;
import com.rongwei.bscommon.sys.excel.EquDieseloilUseManagementTemplate;
import com.rongwei.bscommon.sys.service.EquDieseloilUseManagementService;
import com.rongwei.bsentity.domain.EquDieseloilUseManagementDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.safecommon.utils.CXCommonUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN_YMD;

@Service
public class EquDieseloilUseManagementServiceImpl extends ServiceImpl<EquDieseloilUseManagementDao, EquDieseloilUseManagementDo> implements EquDieseloilUseManagementService {

    @Autowired
    private EquDieseloilUseManagementDao equDieseloilUseManagementDao;


    @Autowired
    private EquDieseloilUseManagementService equDieseloilUseManagementService;
    @Override
    public R uploadDieseloil(MultipartFile multipartFile) throws IOException {
        // 使用自定义的DataListener来读取数据
        EquDieseloilUseManagementListener listener = new EquDieseloilUseManagementListener();
        // 读取数据
        EasyExcel.read(multipartFile.getInputStream(), EquDieseloilUseManagementTemplate.class, listener).sheet().headRowNumber(2).doRead();
        // 解析有误信息
        List<String> errorData = listener.getErrorData();
        if (!errorData.isEmpty()) {
            return R.error(JSON.toJSONString(errorData));
        }
        // 解析数据
        List<EquDieseloilUseManagementDo> dieseloilUseManagementDoList = listener.getDieseloilUseManagementDoList();
        // 唯一性数据
        R r = checkOneDateAndTenantid(dieseloilUseManagementDoList);
        if (r.getCode().equals("500")){
            return r;
        }
        //保存数据
        if (!dieseloilUseManagementDoList.isEmpty()) {
            equDieseloilUseManagementService.saveBatch(dieseloilUseManagementDoList);
        }
        return R.ok("导入成功");
    }

    /**
     * 通过  Tenantid 和  dieseldate 确认唯一值 做新增编辑
     * @param dieseloilUseManagementDoList
     */
    public R checkOneDateAndTenantid(List<EquDieseloilUseManagementDo> dieseloilUseManagementDoList) {
        String tenantid = "";StringBuilder builder = new StringBuilder();
        String tokenTenantId = CXCommonUtils.getCurrentUser() != null ? CXCommonUtils.getCurrentUser().getTenantid() : "";
        if (StringUtils.isNotBlank(tokenTenantId)) {
            tenantid = tokenTenantId;
        } else {
            return R.error("token 失效，请联系管理员");
        };

        //设置查询条件
        LambdaQueryWrapper<EquDieseloilUseManagementDo> queryWrapper = setqueryWrapper(dieseloilUseManagementDoList,tenantid);
        List<EquDieseloilUseManagementDo> oldList = equDieseloilUseManagementDao.selectList(queryWrapper);

        List<String> dieseldates = oldList.stream().map(info ->DateUtil.format(info.getDieseldate(),DATE_PATTERN_YMD) ).distinct().collect(Collectors.toList());
        if (dieseldates.size()<oldList.size()){
            return R.error("上传文件内存在重复的日期，请检查");
        }

        //通过时间判断是否有相同的数据
        for (EquDieseloilUseManagementDo dieseloilUseManagementDo:dieseloilUseManagementDoList){
            String dieseldate = DateUtil.format(dieseloilUseManagementDo.getDieseldate(), DATE_PATTERN_YMD);
            if (dieseldates.contains(dieseldate)){
                builder.append("日期"+dieseldate+"、");
                continue;
            };
            Date date =new Date();
            dieseloilUseManagementDo.setId(SecurityUtil.getUUID());
            dieseloilUseManagementDo.setTenantid(tenantid);
            dieseloilUseManagementDo.setCreatedate(date);
            dieseloilUseManagementDo.setCreateuserid(CXCommonUtils.getCurrentUser().getId());
            dieseloilUseManagementDo.setCreateusername(CXCommonUtils.getCurrentUser().getName());
            dieseloilUseManagementDo.setModifydate(date);
            dieseloilUseManagementDo.setModifyuserid(CXCommonUtils.getCurrentUser().getId());
            dieseloilUseManagementDo.setModifyusername(CXCommonUtils.getCurrentUser().getName());
        };

        //数据拼接错误日志
        if (StringUtils.isBlank(builder.toString())){
            return R.ok();
        }else {
            builder.append("的使用记录已存在，不可重复导入");
            String errMsg =builder.toString().replace("、的", "的");
            return R.error(errMsg);
        }

    }

    /**
     * 设置查询条件，筛选出传入参数的最大，最小时间去数据库查询，避免全量查询
     * @param dieseloilUseManagementDoList
     * @param tenantid
     * @return
     */
    private LambdaQueryWrapper<EquDieseloilUseManagementDo> setqueryWrapper(List<EquDieseloilUseManagementDo> dieseloilUseManagementDoList, String tenantid) {
        //默认升序，那个最小最大时间
        Collections.sort(dieseloilUseManagementDoList, Comparator.comparing(EquDieseloilUseManagementDo::getDieseldate));
        Date minDate = dieseloilUseManagementDoList.get(0).getDieseldate();
        Date maxDate = dieseloilUseManagementDoList.get(dieseloilUseManagementDoList.size()-1).getDieseldate();
        //对时间的设置时分秒
        Calendar instanceMin = Calendar.getInstance();
        instanceMin.setTime(minDate);
        // 设置时、分、秒
        instanceMin.set(Calendar.HOUR_OF_DAY, 0); // 24小时制
        instanceMin.set(Calendar.MINUTE, 0);
        instanceMin.set(Calendar.SECOND, 0);
        Date timemin = instanceMin.getTime();

        //对时间的设置时分秒
        Calendar instanceMax = Calendar.getInstance();
        instanceMax.setTime(maxDate);
        // 设置时、分、秒
        instanceMax.set(Calendar.HOUR_OF_DAY, 23); // 24小时制
        instanceMax.set(Calendar.MINUTE, 59);
        instanceMax.set(Calendar.SECOND, 59);
        Date timemax = instanceMax.getTime();

        //系统中已存在的相同的 tenantid 数据
        LambdaQueryWrapper<EquDieseloilUseManagementDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquDieseloilUseManagementDo::getTenantid,tenantid)
                .eq(EquDieseloilUseManagementDo::getDeleted,"0")
                .ge(EquDieseloilUseManagementDo::getDieseldate,timemin)
                .le(EquDieseloilUseManagementDo::getDieseldate,timemax);
        return queryWrapper;
    }

}
