package com.casic.missiles.service.Impl.system;

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.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.system.DownloadFileRequest;
import com.casic.missiles.dto.system.DownloadListRequest;
import com.casic.missiles.dto.system.DownloadListResponse;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.mapper.system.SystemFileConfigMapper;
import com.casic.missiles.model.system.SystemFileConfig;
import com.casic.missiles.service.system.IDownloadCenterService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.MinioUtil;
import com.casic.missiles.utils.NumberGeneratorUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cz
 * @since 2023-04-03
 */
@Service
@AllArgsConstructor
public class DownloadCenterServiceImpl extends ServiceImpl<SystemFileConfigMapper, SystemFileConfig> implements IDownloadCenterService {

    private final MinioUtil minioUtil;
    private final IBaseExportService iBaseExportService;

    @Override
    public Page<DownloadListResponse> listPage(Page<SystemFileConfig> page, DownloadListRequest request) throws Exception {
        QueryWrapper<SystemFileConfig> queryWrapper = getWrapper(request);
        Page<DownloadListResponse> downloadListResponsePage = PageFactory.defaultPage();
        Page<SystemFileConfig> downloadCenterPage = this.baseMapper.selectPage(page, queryWrapper);
        downloadListResponsePage.setRecords(ConvertUtils.sourceToTarget(downloadCenterPage.getRecords(), DownloadListResponse.class));
        downloadListResponsePage.setTotal(downloadCenterPage.getTotal());
        for (DownloadListResponse customerInfo : downloadListResponsePage.getRecords()) {
            DictCodeUtils.convertDictCodeToName(customerInfo);
        }
        return downloadListResponsePage;
    }

    @Override
    public void downloadFileExport(DownloadListRequest request, HttpServletResponse response) throws Exception {
        Page<SystemFileConfig> page = PageFactory.defaultPage();
        Page<DownloadListResponse> downloadListResponsePage = PageFactory.defaultPage();
        if (!CollectionUtils.isEmpty(request.getIds())) {
            List<SystemFileConfig> downloadCenterPage = this.baseMapper.selectBatchIds(request.getIds());
            page.setRecords(downloadCenterPage);
            downloadListResponsePage.setRecords(ConvertUtils.sourceToTarget(page.getRecords(), DownloadListResponse.class));
            for (DownloadListResponse customerInfo : downloadListResponsePage.getRecords()) {
                DictCodeUtils.convertDictCodeToName(customerInfo);
            }
        } else {
            page.setCurrent(1);
            page.setSearchCount(false);
            page.setSize(Integer.MAX_VALUE);
            request.setIds(null);
            downloadListResponsePage = listPage(page, request);
        }
        iBaseExportService.exportExcel(response, DownloadListResponse.class, downloadListResponsePage.getRecords(), ExportEnum.DOWNLOAD_TEMPLATE.getSheetName());
    }

    @Override
    public ReturnDTO addDownloadFile(SystemFileConfig downloadCenter) {
        initDownloadFile(downloadCenter);
        int addFlag = this.baseMapper.insert(downloadCenter);
        if (addFlag > 0) {
            return ReturnUtil.success();
        }
        return null;
    }

    /**
     * 查询，删除之前的文件
     * 上传新的文件
     */
    @Override
    public ReturnDTO updateDownloadFile(SystemFileConfig downloadCenter) {
        AuthUser authUser = ShiroKit.getUser();
        downloadCenter.setUpdateUser(authUser.getId());
        int updateFlag = this.baseMapper.updateById(downloadCenter);
        if (updateFlag > 0) {
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("更新失败");
    }

    @Override
    public SystemFileConfig downloadFileDetail(Long id) {
        SystemFileConfig downloadCenter = this.baseMapper.selectById(id);
        return downloadCenter;
    }

    @Override
    public ReturnDTO deleteDownloadFile(Long id) {
        int deleteFlag = this.baseMapper.deleteById(id);
        if (deleteFlag > 0) {
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("删除失败");
    }

    @Override
    public ReturnDTO downloadFile(DownloadFileRequest downloadFileRequest) {
        if (StringUtils.isEmpty(downloadFileRequest.getFileName())) {
            downloadFileRequest.setFileName(this.baseMapper.getFileNameByBusiness(downloadFileRequest));
        }
        ResponseEntity<byte[]> download = minioUtil.download(downloadFileRequest.getFileName());
        return ReturnUtil.success(download);
    }

    private QueryWrapper<SystemFileConfig> getWrapper(DownloadListRequest request) {
        QueryWrapper<SystemFileConfig> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(request.getDownloadNo()), "download_no", request.getDownloadNo());
        wrapper.like(StringUtils.isNotBlank(request.getModuleName()), "module_name", request.getModuleName());
        wrapper.like(StringUtils.isNotBlank(request.getFileName()), "file_name", request.getFileName());
        wrapper.like(StringUtils.isNotBlank(request.getFileType()), "file_type", request.getFileType());
        wrapper.apply(StringUtils.isNotBlank(request.getStartTime()),
                "{0} <= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getStartTime());
        wrapper.apply(StringUtils.isNotBlank(request.getEndTime()),
                "{0} >= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getEndTime());
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("update_time");
        return wrapper;
    }

    private void initDownloadFile(SystemFileConfig downloadCenter) {
        Long maxNo = this.baseMapper.selectMaxFileNo();
        //版本号不为空，设置累加次数
        if (StringUtils.isNotEmpty(downloadCenter.getVersionName())) {
            Long maxVersionCode = this.baseMapper.selectMaxVersionNo();
            downloadCenter.setVersionCode(++maxVersionCode);
        }
        String downloadNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.DOWNLOAD_NO, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        downloadCenter.setCreateUser(authUser.getId());
        downloadCenter.setUpdateUser(authUser.getId());
        downloadCenter.setDownloadNo(downloadNo);
    }

}
