package org.jeecg.modules.itdmgongdanshuju.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.itdmDataHistory.entity.ItdmWenxiang;
import org.jeecg.modules.itdmDataHistory.mapper.ItdmWenxiangMapper;
import org.jeecg.modules.itdmgongdanshuju.dto.ItdmGongdanDto;
import org.jeecg.modules.itdmgongdanshuju.dto.ItdmGongdanEditListDto;
import org.jeecg.modules.itdmgongdanshuju.dto.ItdmGongdanUploadDto;
import org.jeecg.modules.itdmgongdanshuju.entity.ItdmGongdanImage;
import org.jeecg.modules.itdmgongdanshuju.entity.ItdmGongdanShuju;
import org.jeecg.modules.itdmgongdanshuju.mapper.ItdmGongdanImageMapper;
import org.jeecg.modules.itdmgongdanshuju.mapper.ItdmGongdanShujuMapper;
import org.jeecg.modules.itdmgongdanshuju.service.ItdmGongdanShujuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 委托信息
 * @Author: jeecg-boot
 * @Date: 2023-05-17
 * @Version: V1.0
 */
@Service
@SuppressWarnings("all")
public class ItdmGongdanShujuServiceImpl extends ServiceImpl<ItdmGongdanShujuMapper, ItdmGongdanShuju> implements ItdmGongdanShujuService {

    @Autowired
    ItdmGongdanShujuMapper itdmGongdanShujuMapper;

    @Autowired
    ItdmWenxiangMapper itdmWenxiangMapper;

    @Autowired

    private ItdmGongdanImageMapper gongdanImageMapper;

    @Override
    @Transactional
    public Boolean generate(ItdmGongdanDto itdmGongdanDto) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<ItdmGongdanShuju> detail = itdmGongdanShujuMapper.selectList(new QueryWrapper<ItdmGongdanShuju>()
                .eq("wo_id", itdmGongdanDto.getWoId()).eq("shiyan_date_time", itdmGongdanDto.getRiqi())
                .between("shiyan_time", itdmGongdanDto.getShiyanKaishitime(), itdmGongdanDto.getShiyanJieshutime())

        );


        if (detail.size() > 0) {
            throw new JeecgBootException("当前工单当前已经有数据，不能重复生成数据（请检查时间是否重合）");
        }

        try {

            String startTime = itdmGongdanDto.getShiyanKaishitime();
            String endTime = itdmGongdanDto.getShiyanJieshutime();
            String shijiShebeiId = itdmGongdanDto.getShebeiId();
            String ShijiWorkDate = itdmGongdanDto.getRiqi();

            String startDateTime = ShijiWorkDate + " " + startTime + ":00";
            String endDateTime = ShijiWorkDate + " " + endTime + ":00";

            boolean b = itdmWenxiangMapper.exists(Wrappers.lambdaQuery(ItdmWenxiang.class).eq(ItdmWenxiang::getDeviceId, shijiShebeiId)
                    .between(ItdmWenxiang::getCreateTime, startDateTime, endDateTime));


            Date date1 = DateUtil.parse(startTime);
            Date date2 = DateUtil.parse(endTime);
            long betweenMinute = DateUtil.between(date1, date2, DateUnit.MINUTE);
            // 频次
            int l = (int) (betweenMinute / Integer.parseInt(itdmGongdanDto.getPinci()));
            for (int i = 0; i <= l; i++) {
                ItdmGongdanShuju itdmGongdanShuju = new ItdmGongdanShuju();
                itdmGongdanShuju.setShiyanType(itdmGongdanDto.getShiyanType());
                itdmGongdanShuju.setPinci(itdmGongdanDto.getPinci());
                itdmGongdanShuju.setShiyanDateTime(itdmGongdanDto.getRiqi());
                itdmGongdanShuju.setWoId(itdmGongdanDto.getWoId());


                String shiyanTime = DateUtil.offsetMinute(date1, i * Integer.parseInt(itdmGongdanDto.getPinci())).toString().split(" ")[1];
                shiyanTime = String.join(":", Arrays.asList(shiyanTime.split(":")).subList(0, 2));


                itdmGongdanShuju.setShiyanTime(shiyanTime);

                if (b) {
                    ItdmWenxiang itdmWenxiang = itdmWenxiangMapper.selectOne(Wrappers.lambdaQuery(ItdmWenxiang.class).eq(ItdmWenxiang::getDeviceId, shijiShebeiId)
                            .between(ItdmWenxiang::getCreateTime, ShijiWorkDate + " " + itdmGongdanShuju.getShiyanTime() + ":00", ShijiWorkDate + " " + itdmGongdanShuju.getShiyanTime() + ":59")
                            .last("limit 1"));
                    if (itdmWenxiang != null) {
                        itdmGongdanShuju.setShiyanWendu(itdmWenxiang.getTemperature().toEngineeringString());
                        if (StringUtils.isNotBlank(itdmGongdanDto.getShiyanType()) && itdmGongdanDto.getShiyanType().contains("2")) {
                            itdmGongdanShuju.setShiyanShidu(itdmWenxiang.getHumidity().toEngineeringString());
                        }
                    }


                }

                boolean save = this.save(itdmGongdanShuju);
                if (!save) {
                    throw new IllegalArgumentException();
                }
            }
        } catch (Exception e) {
            throw new JeecgBootException(e.getMessage(), e);

        }
        return true;
    }


    @Override
    public void upload(ItdmGongdanUploadDto upload) {

        ItdmGongdanImage itdmGong = gongdanImageMapper
                .selectOne(Wrappers.lambdaQuery(ItdmGongdanImage.class).eq(ItdmGongdanImage::getWeituoId, upload.getWeituoId()));


        if (itdmGong == null) {
            ItdmGongdanImage itdmGong1 = new ItdmGongdanImage();
            itdmGong1.setWeituoId(upload.getWeituoId());
            itdmGong1.setExtraPic(upload.getImages());
            gongdanImageMapper.insert(itdmGong1);
        } else {
            itdmGong.setExtraPic(upload.getImages());
            gongdanImageMapper.updateById(itdmGong);
        }


    }


    @Override
    public void editList(ItdmGongdanEditListDto itdmGongdanShuju) {

        itdmGongdanShujuMapper.delete(Wrappers.lambdaQuery(ItdmGongdanShuju.class)
                .eq(ItdmGongdanShuju::getWoId, itdmGongdanShuju.getWoId()));

        for (ItdmGongdanShuju i : itdmGongdanShuju.getList()) {

            if (StringUtils.isBlank(i.getWoId())) {

                i.setWoId(itdmGongdanShuju.getWoId());

            }


            if (StringUtils.isBlank(i.getShiyanDateTime())) {

                i.setShiyanDateTime(itdmGongdanShuju.getShiyanDateTime());

            }

            itdmGongdanShujuMapper.insert(i);

        }


    }


    @Override
    public String getUpdate(String weituoId) {
        ItdmGongdanImage itdmGong = gongdanImageMapper.selectOne(Wrappers.lambdaQuery(ItdmGongdanImage.class)
                .eq(ItdmGongdanImage::getWeituoId, weituoId).last("limit 1"));

        if (itdmGong == null) {
            return "";
        }

        return itdmGong.getExtraPic();
    }

    public static void main(String[] args) {
        String shiyanTime = "10:20:30";
        shiyanTime = String.join(":", Arrays.asList(shiyanTime.split(":")).subList(0, 2));
        System.out.println(shiyanTime);

    }
}
