package com.tofly.water.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.common.service.IFileInfoService;
import com.tofly.water.entity.BasePumpDetail;
import com.tofly.water.entity.DeviceBusiness;
import com.tofly.water.entity.DevicePump;
import com.tofly.water.entity.dto.BasePumpDetailDto;
import com.tofly.water.service.BasePumpDetailService;
import com.tofly.water.service.DeviceBusinessService;
import com.tofly.water.service.DevicePumpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.water.mapper.BasePumpGroupMapper;
import com.tofly.water.entity.BasePumpGroup;
import com.tofly.water.entity.dto.BasePumpGroupDto;
import com.tofly.water.service.BasePumpGroupService;
import org.springframework.stereotype.Service;

import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.io.Serializable;
import java.util.stream.Collectors;

/**
 * 水泵机组管理(BasePumpGroup)表服务实现类
 *
 * @author HaiQiu
 * @since 2022-11-22 11:34:22
 */
@Service("basePumpGroupService")
public class BasePumpGroupServiceImpl extends ServiceImpl<BasePumpGroupMapper, BasePumpGroup> implements BasePumpGroupService {


    @Value("${basePumpGroup.ftp.uploads:/dcsw/project/basePumpGroup}")
    private String path;
    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private BasePumpDetailService pumpDetailService;

    @Autowired
    private BasePumpDetailService basePumpDetailService;

    @Autowired
    private DevicePumpService devicePumpService;


    @Autowired
    private DeviceBusinessService deviceBusinessService;

    /**
     * 根据ID查询
     *
     * @param id id
     * @return 数据
     */
    @Override
    public BasePumpGroup get(Serializable id) {
        BasePumpGroup basePumpGroup = getById(id);
        if (!ObjectUtils.isEmpty(basePumpGroup)){
            List<BasePumpDetail> details = basePumpDetailService.list(Wrappers.<BasePumpDetail>lambdaQuery()
                    .eq(basePumpGroup.getId() != null, BasePumpDetail::getPumpGroupId, basePumpGroup.getId()));
            basePumpGroup.setPumpDetails(details);
        }
        return basePumpGroup;
    }


    /**
     * 新增
     *
     * @param basePumpGroupDto 实体
     * @param files            上传文件附件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(BasePumpGroupDto basePumpGroupDto, List<MultipartFile> files) {
        BasePumpGroup basePumpGroup = convert(basePumpGroupDto);
        basePumpGroup.setAnnex(fileInfoService.uploadFiles(files, basePumpGroup.getAnnex()
                , basePumpGroup.getAnnex(), path, "TF_BASE_PUMP_GROUP"));
        if (!save(basePumpGroup)) {
            throw new RuntimeException("新增失败");
        }
        //保存水泵信息
        saveDetails(basePumpGroup);
    }


    /**
     * 修改
     *
     * @param basePumpGroupDto 实体
     * @param files            上传文件附件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(BasePumpGroupDto basePumpGroupDto, List<MultipartFile> files) {
        BasePumpGroup basePumpGroup = convert(basePumpGroupDto);
        basePumpGroup.setAnnex(fileInfoService.uploadFiles(files, basePumpGroup.getAnnex()
                , basePumpGroup.getAnnex(), path, "TF_BASE_PUMP_GROUP"));
        if (!updateById(basePumpGroup)) {
            throw new RuntimeException("修改失败");
        }
        //保存水泵信息
        saveDetails(basePumpGroup);
    }

    /**
     * 实体转换
     *
     * @param basePumpGroupDto dto实体
     */
    private BasePumpGroup convert(BasePumpGroupDto basePumpGroupDto) {
        BasePumpGroup basePumpGroup = new BasePumpGroup();
        BeanUtils.copyProperties(basePumpGroupDto, basePumpGroup);
        return basePumpGroup;
    }

    /**
     * 保存水泵信息
     *
     * @param basePumpGroup 水泵信息
     */
    private void saveDetails(BasePumpGroup basePumpGroup) {
        //保存中间关联表信息
        deviceBusinessService.saveBusiness(basePumpGroup.getId(),"TF_BASE_PUMP_GROUP");
        //保存水泵
        if (!CollectionUtils.isEmpty(basePumpGroup.getPumpDetails())) {
            //先删除数据，再添加数据
            pumpDetailService.remove(Wrappers.<BasePumpDetail>lambdaQuery()
                    .eq(basePumpGroup.getId() != null, BasePumpDetail::getPumpGroupId, basePumpGroup.getId()));
            List<BasePumpDetail> basePumpDetails = basePumpGroup.getPumpDetails().stream().map(pumpDetailDto -> {
                pumpDetailDto.setPumpGroupId(basePumpGroup.getId());
                pumpDetailDto.setPumpId(basePumpGroup.getPumpId());
                pumpDetailDto.setId(null);
                return pumpDetailDto;
            }).collect(Collectors.toList());
            pumpDetailService.saveBatch(basePumpDetails);
        }
        //检查中间表，进行数据添加
        DevicePump devicePump2 = new DevicePump();
        devicePump2.setPumpId(basePumpGroup.getPumpId());
        devicePump2.setPumpGroupId(basePumpGroup.getId());
        devicePump2.setPumpGroupForPid(basePumpGroup.getPumpId());
        int count = devicePumpService.count(Wrappers.query(devicePump2));
        if (count == 0) {
            DevicePump devicePump = new DevicePump();
            devicePump.setPumpGroupId(basePumpGroup.getId());
            devicePump.setPumpGroupForPid(basePumpGroup.getPumpId());
            //先进行旧数据删除
            devicePumpService.remove(Wrappers.lambdaQuery(devicePump));
            List<DevicePump> pumpList = new ArrayList<>();
            if (devicePump.getPumpId() != null) {
                pumpList = devicePumpService.list(Wrappers.<DevicePump>lambdaQuery()
                        .eq(DevicePump::getPumpId, devicePump.getPumpId())
                        .isNull(DevicePump::getPumpGroupId)
                        .isNull(DevicePump::getPumpGroupForPid));
            }
            //存在缺省数据就基础上修改
            if (!CollectionUtils.isEmpty(pumpList)) {
                pumpList.get(0).setPumpGroupId(basePumpGroup.getPumpId());
                pumpList.get(0).setPumpGroupForPid(basePumpGroup.getPumpId());
                devicePumpService.updateById(pumpList.get(0));
            } else {
                //否则就新增数据
                DevicePump devicePump1 = new DevicePump();
                devicePump1.setPumpId(basePumpGroup.getPumpId());
                devicePump1.setPumpGroupId(basePumpGroup.getId());
                devicePump1.setPumpGroupForPid(basePumpGroup.getPumpId());
                devicePumpService.save(devicePump1);
            }
        }
    }


    /**
     * 批量删除
     *
     * @param idList 数据ID集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        if (!removeByIds(idList)) {
            throw new RuntimeException("删除失败");
        }
        //删除水泵基础信息
        basePumpDetailService.remove(Wrappers.<BasePumpDetail>lambdaQuery()
                .in(!CollectionUtils.isEmpty(idList), BasePumpDetail::getPumpGroupId, idList));
        //删除中间关联表信息
        deviceBusinessService.removeBusiness(idList,"TF_BASE_PUMP_GROUP");
    }

    /**
     * 生成模板下载
     */
    @Override
    public void template() {
        BasePumpGroup basePumpGroup = new BasePumpGroup();
        ExcelUtils.createTemplate("水泵机组管理", "水泵机组管理",
                "水泵机组管理", BasePumpGroup.class, Collections.singletonList(basePumpGroup));
    }

    /**
     * 数据导入
     *
     * @param file 文件
     */
    @Override
    public void importData(MultipartFile file) {
        List<BasePumpGroup> excelToList = ExcelUtils.getExcelToList("水泵机组管理", file, BasePumpGroup.class);
        if (CollectionUtils.isEmpty(excelToList)) {
            throw new RuntimeException("数据解析为空");
        }
        saveBatch(excelToList);
    }

    /**
     * 分页查询
     *
     * @param page          分页
     * @param basePumpGroup 查询wrapper
     * @return 数据集合
     */
    @Override
    public Page<BasePumpGroup> pageList(Page page, BasePumpGroup basePumpGroup) {
        Page<BasePumpGroup> data = page(page, Wrappers.<BasePumpGroup>lambdaQuery(basePumpGroup));
        if (!CollectionUtils.isEmpty(data.getRecords())){
            for (BasePumpGroup record : data.getRecords()) {
                if (!ObjectUtils.isEmpty(record)){
                    List<BasePumpDetail> details = basePumpDetailService.list(Wrappers.<BasePumpDetail>lambdaQuery()
                            .eq(basePumpGroup.getId() != null, BasePumpDetail::getPumpGroupId, basePumpGroup.getId()));
                    record.setPumpDetails(details);
                }
            }
        }
        return data;
    }

    /**
     * 数据导出
     *
     * @param page          分页
     * @param basePumpGroup 查询模型
     * @param isAll         是否导出全部数据，true是，false否
     */
    @Override
    public void export(Page page, BasePumpGroup basePumpGroup, boolean isAll) {
        Page<BasePumpGroup> pageData = new Page<>();
        if (!isAll) {
            pageData = page(page,Wrappers.<BasePumpGroup>lambdaQuery(basePumpGroup));
        } else {
            pageData.setRecords(list(new QueryWrapper<>(basePumpGroup)));
        }
        //导出数据
        ExcelUtils.getListToExcel(BasePumpGroup.class, pageData.getRecords(), "水泵机组管理");
    }

    /**
     * 查询所有数据
     *
     * @param basePumpGroup 查询条件
     * @return 查询所有数据
     */
    @Override
    public List<BasePumpGroup> allList(BasePumpGroup basePumpGroup) {
        return list(new QueryWrapper<>(basePumpGroup));
    }
}

