package com.testor.ddd.safetyControl.infrastructure.uitls.SpaceExcelTemplate;

//import cn.hutool.poi.excel.ExcelWriter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceTypeManageService;
import com.testor.ddd.safetyControl.infrastructure.uitls.SpaceLevelEnum;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceTypeDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceTypeDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DownloadSpaceTemplateUtil {

    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;

    @Resource
    private SysOrgService orgService;

    @Resource
    private SpaceTypeManageService spaceTypeManageService;

    @Resource
    private SpaceManageService spaceManageService;

    @Resource
    private SysFileService sysFileService;

//    public SysFile findSysFileByName(String fileName){
//        if(StrUtil.isBlank(fileName)) {
//            return null;
//        }
//        LambdaQueryWrapper<SysFile> fileQueryWrapper = new LambdaQueryWrapper<>();
//        fileQueryWrapper.eq(SysFile::getFileName, fileName)
//                .eq(SysFile::getStatus, BizConstants.STATUS_ENABLE)
//                .isNotNull(SysFile::getFileDowName)
//                .orderByDesc(SysFile::getCreateDate);
//        List<SysFile> fileList = sysFileService.list(fileQueryWrapper);
//        if(fileList == null || fileList.size() == 0) {
//            return null;
//        }
//        return fileList.get(0);
//    }

    /**
     * 车间场所 模板下载
     * @param response
     * @param fileName
     * @param orgId
     */
    public void downloadWorkshopTemplate(HttpServletResponse response, String fileName, String orgId){
        try {
            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2);
            List<TemplateEntity> orgList = findOrgList(orgId);
            List<TemplateEntity> spaceTypeList = findSpaceTypeList(null);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/cjcsdrmb.xlsx");
            EasyExcel.write(out).withTemplate(templatePathName).build()
                    .write(spaceTypeList, EasyExcel.writerSheet(2).head(TemplateEntity.class).needHead(false).build())
                    .write(orgList, EasyExcel.writerSheet(3).head(TemplateEntity.class).needHead(false).build())
                    .finish();
            byte[] bytes = out.toByteArray();
            out.flush();
            out.close();
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 作业区域模板下载
     * @param response
     * @param fileName
     * @param orgId
     */
    public void downloadWorkareaTemplate(HttpServletResponse response, String fileName, String orgId){
        try{
            InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/zyqyxxmb.xlsx");

            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2);

            List<SpaceTemplateEntity> spaceList = findWorkshopList(orgId);
            List<TemplateEntity> orgList = findOrgList(orgId);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            EasyExcel.write(out).withTemplate(templatePathName).build()
                    .write(spaceList, EasyExcel.writerSheet(2).head(SpaceTemplateEntity.class).needHead(false).build())
                    .write(orgList, EasyExcel.writerSheet(3).head(TemplateEntity.class).needHead(false).build())
                    .finish();

            byte[] bytes = out.toByteArray();
            out.flush();
            out.close();

            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        }catch(Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 测试导出
     * @param response
     */
    public void exportModelExcel(HttpServletResponse response) {
        try {
            //导出的数据
            List<TemplateEntity> dataTalk = new ArrayList<>();
            TemplateEntity dataMap = new TemplateEntity();
            dataMap.setName("name1");
            dataMap.setCode("code1");

            TemplateEntity dataMap2 = new TemplateEntity();
            dataMap2.setName("name2");
            dataMap2.setCode("code2");
            dataTalk.add(dataMap);
            dataTalk.add(dataMap2);

            String fileName = URLEncoder.encode("Script_", "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "System").head(TemplateEntity.class).build();
            excelWriter.write(dataTalk, writeSheet1);
            excelWriter.finish();

        } catch (IOException e) {
            e.getStackTrace();
        }
    }

    /**
     * 获取企业信息
     * @return
     */
    public List<TemplateEntity> findOrgList(String orgId){
        List<SysOrg> orgList;
        if(!StrUtil.isBlank(orgId)) {
            SysOrg org = orgService.getById(orgId);
            orgList = new ArrayList<>();
            orgList.add(org);
        } else {
            orgList = orgService.list();
        }
//        List<SysOrg> orgList = orgService.list();
//        if(orgList == null || orgList.size() == 0) {
//            return null;
//        }
        List<TemplateEntity> templateEntityList = orgList.stream().map(p -> new TemplateEntity(p.getOrgName(), p.getOrgCode())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取车间场所类型 信息
     * @param orgId
     * @return
     */
    public List<TemplateEntity> findSpaceTypeList(String orgId){
//        if(StrUtil.isBlank(orgId)) {
//            return null;
//        }
        TSafeSpaceTypeDTOParam spaceTypeDTOParam = new TSafeSpaceTypeDTOParam();
        spaceTypeDTOParam.setStatus(BizConstants.STATUS_ENABLE);
        if(!StrUtil.isBlank(orgId)) {
            spaceTypeDTOParam.setOrgId(orgId);
        }
        List<TSafeSpaceTypeDTO> spaceTypeDTOList = spaceTypeManageService.listByPage(spaceTypeDTOParam).getData();
        if(spaceTypeDTOList == null || spaceTypeDTOList.size() == 0) {
            return null;
        }

        List<TemplateEntity> templateEntityList = spaceTypeDTOList.stream().map(p -> new TemplateEntity(p.getName(), p.getCode())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取 车间场所信息
     * @param orgId
     * @return
     */
    public List<SpaceTemplateEntity> findWorkshopList(String orgId){
        if(StrUtil.isBlank(orgId)) {
            return null;
        }
        TSafeSpaceDTOParam spaceDTOParam = new TSafeSpaceDTOParam();
        //查询作业区域信息
        spaceDTOParam.setStatus(BizConstants.STATUS_ENABLE);
        spaceDTOParam.setOrgId(orgId);
        spaceDTOParam.setLevel(SpaceLevelEnum.workshop.getCode());
        List<TSafeSpaceVO> spaceDTOList = spaceManageService.listByPage(spaceDTOParam).getData();

        if(spaceDTOList == null || spaceDTOList.size() == 0) {
            return null;
        }

        List<SpaceTemplateEntity> templateEntityList = spaceDTOList.stream().map(p -> new SpaceTemplateEntity(p.getSpaceTypeName(), p.getName(), p.getCode())).collect(Collectors.toList());
        return templateEntityList;
    }
}
