Newer
Older
huludao / src / main / java / com / newfiber / api / pc / service / impl / PlanNewServiceImpl.java
package com.newfiber.api.pc.service.impl;


import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.newfiber.api.core.base.domain.Accessory;
import com.newfiber.api.core.base.domain.BaseEntity;
import com.newfiber.api.core.commons.CustomException;
import com.newfiber.api.core.commons.PageResultObject;
import com.newfiber.api.core.commons.ResultCode;
import com.newfiber.api.pc.dao.PlanNewMapper;
import com.newfiber.api.pc.model.entity.PlanNew;
import com.newfiber.api.pc.model.entity.PlanTypeNew;
import com.newfiber.api.pc.model.request.planNew.PlanNewPageQueryRequest;
import com.newfiber.api.pc.model.request.planNew.PlanNewQueryRequest;
import com.newfiber.api.pc.model.request.planNew.PlanNewSaveRequest;
import com.newfiber.api.pc.model.request.planNew.PlanNewUpdateRequest;
import com.newfiber.api.pc.service.IPlanNewService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * 防汛应急指挥-应急预案Service业务层处理
 * 
 * @author newfiber
 * @date 2024-07-23
 */
@Service
public class PlanNewServiceImpl extends ServiceImpl<PlanNewMapper, PlanNew> implements IPlanNewService {

    @Resource
    private PlanNewMapper planNewMapper;

    /** 节点文件保存路径 */
    @Value("${xnFile.path}")
    private String xnFilePath;

    @Value("${nginx.file}")
    private String nginxfile;

    public String getXnFilePath() {
        return xnFilePath;
    }

    public void setXnFilePath(String xnFilePath) {
        this.xnFilePath = xnFilePath;
    }

    public String getNginxfile() {
        return nginxfile;
    }

    public void setNginxfile(String nginxfile) {
        this.nginxfile = nginxfile;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public long insert(PlanNewSaveRequest request) {
        PlanNew planNew = new PlanNew();
        BeanUtils.copyProperties(request, planNew);
        if (!CollectionUtils.isEmpty(planNew.getPlanFileList())){
            planNew.setPlanFile(JSONObject.toJSONString(request.getPlanFileList()));
        }
        planNew.setDelFlag("0");
        insert(planNew);
        return Optional.of(planNew).map(BaseEntity::getId).orElse(0L);
    }

    @Override
    public boolean update(PlanNewUpdateRequest request) {
        PlanNew planNew = new PlanNew();
        BeanUtils.copyProperties(request, planNew);
        if (!CollectionUtils.isEmpty(planNew.getPlanFileList())){
            planNew.setPlanFile(JSONObject.toJSONString(request.getPlanFileList()));
        }
        planNew.setDelFlag("0");
        return updateById(planNew);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        if (StringUtils.isNotEmpty(ids)){
            for (String s : ids.split(",")) {
                planNewMapper.deleteById(Long.valueOf(s));
            }

        }
	    return true;
    }

    @Override
    public PlanNew selectDetail(Long id) {
        PlanNew planNew = planNewMapper.selectById(id);
        if(null == planNew){
	        throw new CustomException(ResultCode.ERROR.getCode(),String.format("%s ID=%s 的记录不存在", this.getClass().getSimpleName(), id));
        }
        List<PlanTypeNew> planTypeNewList = planNewMapper.selectPlanType();
        Optional<PlanTypeNew> planTypeNewOptional = planTypeNewList.stream().filter(a -> a.getCode().equals(planNew.getPlanType())).findFirst();
        planTypeNewOptional.ifPresent(planTypeNew -> planNew.setPlanTypeName(planTypeNew.getName()));
        if (StringUtils.isNotEmpty(planNew.getPlanFile())){
            planNew.setPlanFileList(JSONArray.parseArray(planNew.getPlanFile(), Accessory.class));
        }
        return planNew;
    }

    @Override
    public PageResultObject<PlanNew> selectPage(PlanNewPageQueryRequest request) {
        Page<PlanNew> page = new Page<>(request.getCurrent(), request.getSize());
        EntityWrapper<PlanNew> wrapper = new EntityWrapper<>();
        if(!org.springframework.util.StringUtils.isEmpty(request) && !org.springframework.util.StringUtils.isEmpty(request.getPlanName())){
            wrapper.like("plan_name",request.getPlanName());
        }
        Page<PlanNew> meetPlanPage = this.selectPage(page, wrapper);
        if (!ObjectUtils.isEmpty(meetPlanPage) && !CollectionUtils.isEmpty(meetPlanPage.getRecords())){
            List<PlanTypeNew> planTypeNewList = planNewMapper.selectPlanType();
            meetPlanPage.getRecords().forEach(a -> {
                Optional<PlanTypeNew> planTypeNewOptional = planTypeNewList.stream().filter(b -> b.getCode().equals(a.getPlanType())).findFirst();
                planTypeNewOptional.ifPresent(planTypeNew -> a.setPlanTypeName(planTypeNew.getName()));
                if (StringUtils.isNotEmpty(a.getPlanFile())){
                    a.setPlanFileList(JSONArray.parseArray(a.getPlanFile(), Accessory.class));
                }
            });

        }

        int count = this.selectCount(wrapper);
        return new PageResultObject<>(request.getCurrent(),request.getSize(),(long)count,meetPlanPage.getRecords());
    }

    @Override
    public List<PlanNew> selectList(PlanNewQueryRequest request) {
        List<PlanNew> planNewList = planNewMapper.selectByCondition(request);
        if (!CollectionUtils.isEmpty(planNewList)){
            planNewList.forEach(a -> a.setPlanFileList(JSONArray.parseArray(a.getPlanFile(), Accessory.class)));
        }
        return planNewList;
    }

    @Override
    public List<PlanTypeNew> selectPlanTypeNewList() {
        return planNewMapper.selectPlanType();
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        if(org.springframework.util.StringUtils.isEmpty(id)){
            throw new CustomException(ResultCode.PARAM_NULL);
        }
        PlanNew meetPlan = planNewMapper.selectById(id);
        List<Accessory> accessoryList = JSONArray.parseArray(meetPlan.getPlanFile(), Accessory.class);
        String value = accessoryList.get(0).getUrl();
        File file = new File(value);
        if(file.exists()){
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(accessoryList.get(0).getName(),"UTF-8") );
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {

            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}