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.BasePumpGroup;
import com.tofly.water.entity.DevicePump;
import com.tofly.water.service.BasePumpGroupService;
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.BasePumpMapper;
import com.tofly.water.entity.BasePump;
import com.tofly.water.entity.dto.BasePumpDto;
import com.tofly.water.service.BasePumpService;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

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

/**
 * 泵站信息管理(BasePump)表服务实现类
 *
 * @author HaiQiu
 * @since 2022-11-22 11:34:20
 */
@Service("basePumpService")
public class BasePumpServiceImpl extends ServiceImpl<BasePumpMapper, BasePump> implements BasePumpService {


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

    @Autowired
    private DevicePumpService devicePumpService;

    @Autowired
    private BasePumpGroupService pumpGroupService;

    @Autowired
    private DeviceBusinessService deviceBusinessService;


    /**
     * 根据ID查询
     *
     * @param id id
     * @return 数据
     */
    @Override
    public BasePump get(Serializable id) {
        return getById(id);
    }


    /**
     * 新增
     *
     * @param basePumpDto 实体
     * @param files       上传文件附件
     */
    @Override
    public void insert(BasePumpDto basePumpDto, List<MultipartFile> files) {
        BasePump basePump = convert(basePumpDto);
        basePump.setAnnex(fileInfoService.uploadFiles(files, basePump.getAnnex()
                , basePump.getAnnex(), path, "TF_BASE_PUMP"));
        if (!save(basePump)) {
            throw new RuntimeException("新增失败");
        }
        saveDevicePump(basePump);
    }


    /**
     * 保存中间表数据
     * @param basePump 泵站
     */
    private void saveDevicePump(BasePump basePump) {
        int count = devicePumpService.count(Wrappers.<DevicePump>lambdaQuery()
                .eq(DevicePump::getPumpId, basePump.getId()));
        if (count == 0) {
            DevicePump devicePump = new DevicePump();
            devicePump.setPumpId(basePump.getId());
            devicePumpService.save(devicePump);
        }
        //保存中间关联表信息
        deviceBusinessService.saveBusiness(basePump.getId(),"TF_BASE_PUMP");
    }

    /**
     * 修改
     *
     * @param basePumpDto 实体
     * @param files       上传文件附件
     */
    @Override
    public void edit(BasePumpDto basePumpDto, List<MultipartFile> files) {
        BasePump basePump = convert(basePumpDto);
        basePump.setAnnex(fileInfoService.uploadFiles(files, basePump.getAnnex()
                , basePump.getAnnex(), path, "TF_BASE_PUMP"));
        if (!updateById(basePump)) {
            throw new RuntimeException("修改失败");
        }
        saveDevicePump(basePump);
    }

    /**
     * 实体转换
     *
     * @param basePumpDto dto实体
     */
    private BasePump convert(BasePumpDto basePumpDto) {
        BasePump basePump = new BasePump();
        BeanUtils.copyProperties(basePumpDto, basePump);
        return basePump;
    }

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

    /**
     * 生成模板下载
     */
    @Override
    public void template() {
        BasePump basePump = new BasePump();
        ExcelUtils.createTemplate("泵站信息管理", "泵站信息管理",
                "泵站信息管理", BasePump.class, Collections.singletonList(basePump));
    }

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

    /**
     * 分页查询
     *
     * @param page     分页
     * @param basePump 查询wrapper
     * @return 数据集合
     */
    @Override
    public Page<BasePump> pageList(Page page, BasePump basePump) {
        return page(page, new QueryWrapper<>(basePump)).addOrder(page.getOrders());
    }

    /**
     * 数据导出
     *
     * @param page     分页
     * @param basePump 查询模型
     * @param isAll    是否导出全部数据，true是，false否
     */
    @Override
    public void export(Page page, BasePump basePump, Boolean isAll) {
        Page<BasePump> pageData = new Page<>();
        if (isAll == null || !isAll) {
            pageData = page(page, new QueryWrapper<>(basePump)).addOrder(page.getOrders());
        } else {
            pageData.setRecords(list(new QueryWrapper<>(basePump)));
        }
        //导出数据
        ExcelUtils.getListToExcel(BasePump.class, pageData.getRecords(), "泵站信息管理");
    }

    /**
     * 查询所有数据
     *
     * @param basePump 查询条件
     * @return 查询所有数据
     */
    @Override
    public List<BasePump> allList(BasePump basePump) {
        List<BasePump> list = list(new QueryWrapper<>(basePump));
        if (!CollectionUtils.isEmpty(list)){
            for (BasePump pump : list) {
                List<BasePumpGroup> groupList = pumpGroupService.list(Wrappers.<BasePumpGroup>lambdaQuery()
                        .eq(BasePumpGroup::getPumpId, pump.getId()));
                if (!CollectionUtils.isEmpty(groupList)){
                    pump.setBasePumpGroups(groupList);
                }
            }
        }
        return list;
    }
}

