package com.nantian.cloud.dbcapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.dbcapp.entity.BelowGradeNotice;
import com.nantian.cloud.dbcapp.entity.EnterpriseInfo;
import com.nantian.cloud.dbcapp.mapper.jly.BelowGradeNoticeMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseInfoMapper;
import com.nantian.cloud.dbcapp.service.BelowGradeNoticeService;
import com.nantian.cloud.dbcapp.unit.MultipartFileUnit;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


@Service
public class BelowGradeNoticeServiceImpl extends ServiceImpl<BelowGradeNoticeMapper, BelowGradeNotice> implements BelowGradeNoticeService {

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;

    @Override
    public IPage<BelowGradeNotice> getManageInfo(Page page, BelowGradeNotice belowGradeNotice) {
        return baseMapper.getManageInfo(page,belowGradeNotice);
    }

    @Override
    public IPage<BelowGradeNotice> getDetailInfo(Page page, BelowGradeNotice belowGradeNotice) {
        return baseMapper.getDetailInfo(page,belowGradeNotice);
    }

    @Override
    public R batchUpload(MultipartFile multipartFile, Integer pid, String status, String content) throws Exception {
        if(multipartFile == null){
            return R.failed("文件不能为空！");
        }
        String fileName = multipartFile.getOriginalFilename(); //文件名
        String[] strings = fileName.split("\\.");
        String fileSuffix = strings[strings.length - 1];  //文件后缀
        if(!"doc".equals(fileSuffix) && !"docx".equals(fileSuffix)  && !"pdf".equals(fileSuffix) && !"zip".equals(fileSuffix)){
            return R.ok("文件格式错误，只支持word文件、pdf文件和zip文件");
        }

        BelowGradeNotice belowGradeNotice = new BelowGradeNotice();
        belowGradeNotice.setPid(pid);
        belowGradeNotice.setStatus(status);
        if("zip".equals(fileSuffix)){ //文件解压
            try{
                //将MultipartFile转化为File
                File  newFile = (File) MultipartFileUnit.ultipartFileToFile(multipartFile);
                //创建ZipFile对象，解析file文件
                ZipFile zip = new ZipFile(newFile, Charset.forName("GBK"));
                for(Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                    belowGradeNotice.setId(null); //多个文件上传，id置为空
                    ZipEntry entry = (ZipEntry)entries.nextElement();
                    String newFileName = entry.getName();
                    InputStream fileStream = zip.getInputStream(entry);
                    //保存不合格报告信息，并上传文件
                    saveNoticeByFile(belowGradeNotice, newFileName, fileStream, content);
                }
            }catch (Exception e){
                System.err.println(e.toString());
                return R.failed("导入失败："+e.toString());
            }
        }else{
            InputStream fileStream = multipartFile.getInputStream();
            //保存不合格报告信息，并上传文件
            saveNoticeByFile(belowGradeNotice, fileName, fileStream, content);
        }

        return R.ok();
    }

    @Override
    public R renewManage(BelowGradeNotice belowGradeNotice) {
        belowGradeNotice.setUpdateTime(new Date());
        if(belowGradeNotice.getId() != null && belowGradeNotice.getId() != 0){
            baseMapper.updateById(belowGradeNotice);
        }else{
            ScUser user = SecurityUtils.getUser();
            belowGradeNotice.setUserid(user.getId());
            belowGradeNotice.setDeptId(user.getDeptId());
            belowGradeNotice.setDelFlag("1");
            baseMapper.insert(belowGradeNotice);
        }
        return R.ok();
    }

    @Override
    public R renewDetail(MultipartFile multipartFile, BelowGradeNotice belowGradeNotice) throws Exception {
        if(multipartFile != null){
            String fileName = multipartFile.getOriginalFilename();
            InputStream fileStream = multipartFile.getInputStream();
            //保存不合格报告信息，并上传文件
            saveNoticeByFile(belowGradeNotice, fileName, fileStream, belowGradeNotice.getContent());
        }else{
            saveNoticeByFile(belowGradeNotice, "", null, belowGradeNotice.getContent());
        }
        return R.ok();
    }

    @Override
    public List<BelowGradeNotice> getBelowGradeNoticeList(String topic) {
        return baseMapper.getBelowGradeNoticeList(topic);
    }

    public void saveNoticeByFile(BelowGradeNotice belowGradeNotice, String fileName, InputStream fileStream, String content) throws Exception {
        String regionCode = "", enterpriseCode = "", cmpName = "";
        if(StringUtils.isNotBlank(fileName)){
            belowGradeNotice.setFile(fileName); //设置文件名称
            //获取企业信息
            EnterpriseInfo enterpriseInfo = enterpriseInfoMapper.getInfoByName(fileName);
            if(enterpriseInfo != null){
                regionCode = enterpriseInfo.getRegionCode();
                enterpriseCode = enterpriseInfo.getEnterpriseCode();
                cmpName = enterpriseInfo.getCmpName();
                belowGradeNotice.setEnterpriseCode(enterpriseCode);
                belowGradeNotice.setContent(cmpName+"：\n" +
                        "    "+content); //不合格通知内容
            }
            //文件上传
            minioTemplate.putObject("jljc", fileName, fileStream, fileStream.available(), "application/octet-stream");
        }

        ScUser user = SecurityUtils.getUser();
        belowGradeNotice.setUpdateTime(new Date());
        if(belowGradeNotice.getId() != null && belowGradeNotice.getId() != 0){
            baseMapper.updateById(belowGradeNotice);
        }else{

            belowGradeNotice.setUserid(user.getId());
            belowGradeNotice.setDeptId(user.getDeptId());
            belowGradeNotice.setDelFlag("1");
            baseMapper.insert(belowGradeNotice);
        }
        if("1".equals(belowGradeNotice.getStatus()) && StringUtils.isNotBlank(enterpriseCode)){ //同步发送通知
            //String userDept = user.getUserDept();
            String userDept = "0,1,2,3,4,5,6"; //节能主管部门
            String zfDeptStr = "530000," + StringUtils.substring(regionCode,0, 4) + "00," + regionCode; //区域
            baseMapper.insertSysNotice(belowGradeNotice, userDept, zfDeptStr);
        }
    }
}
