package com.huatek.busi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import com.huatek.busi.common.DictEnum;
import com.huatek.busi.common.FileTypeEnum;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.GenerateUtil;
import com.huatek.busi.common.util.ImportExcel;
import com.huatek.busi.dao.SysModelDao;
import com.huatek.busi.dto.*;
import com.huatek.busi.entity.*;
import com.huatek.busi.init.SftpInit;
import com.huatek.busi.mapper.LabReportBasisDataMapper;
import com.huatek.busi.mapper.SftpConnectConfigMapper;
import com.huatek.busi.mapper.WiringDiagramMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.service.gis.BusiOfflineGisBrandService;
import com.huatek.busi.service.gis.GisMechanicalPropertiesService;
import com.huatek.busi.util.FTPUtil;
import com.huatek.busi.vo.*;
import com.huatek.busi.where.LabReportBasisDataSelectVo;
import com.huatek.busi.where.LabReportBasisDataStatisticsWhereVo;
import com.huatek.busi.where.LabReportParamDataSelectVo;
import com.huatek.busi.where.SysFileDiagramSelectVo;
import com.huatek.frame.base.entity.Dictionnaire;
import com.huatek.frame.base.service.DictionnaireDetailService;
import com.huatek.frame.base.service.DictionnaireService;
import com.huatek.frame.base.util.Constants;
import com.huatek.frame.base.vo.DictionnaireDetailVO;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.sql.dao.impl.BaseDao;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@Service(interfaceClass = IWiringDiagramService.class)
@Transactional(rollbackFor = Exception.class)
public class WiringDiagramImpl extends BaseDao<WiringDiagram, String> implements IWiringDiagramService {

    @Reference(check = false)
    DictionnaireDetailService dictionnaireDetailService;

    @Reference(check = false)
    ISysFileDiagramService sysFileService;

    @Resource
    private WiringDiagramMapper wiringDiagramMapper;

    @Resource
    private SftpConnectConfigMapper sftpConnectConfigService;


    @Resource
    private SysModelDao sysModelDao;



    @Resource
    private SftpInit sftpInit;

    @Override
    public PageInfo<WiringDiagram> list(SysFileDiagramSelectVo sysFileDiagramSelectVo) {
        return PageHelper.startPage(sysFileDiagramSelectVo.getPage() == null ? 1 :sysFileDiagramSelectVo.getPage() , sysFileDiagramSelectVo.getLimit() == null? 1 : sysFileDiagramSelectVo.getLimit())
                .doSelectPageInfo(() -> wiringDiagramMapper.selectLists(sysFileDiagramSelectVo.getFileName(),sysFileDiagramSelectVo.getStartDate(),sysFileDiagramSelectVo.getEndDate()));
    }


    @Override
    public Map<String, Object> importFile(byte[] bytes, String token, String type, String fileNameNew, String rootPath, String fileType,String fileName) {

        if (StrUtil.isEmpty(token)) {
            log.error("Token为空！");
            throw new OwlException("Token为空！");
        }

        if (StrUtil.isEmpty(fileType)) {
            log.error("fileType为空！");
            throw new OwlException("fileType为空！");
        }

        if (StringUtils.isEmpty(fileName)) {
            log.error("fileName为空！");
            throw new OwlException("fileName为空！");
        }

        if (ArrayUtil.isEmpty(bytes)) {
            log.error("文件二进制流为空！");
            throw new OwlException("文件二进制流为空！");
        }
        // 获取当前用户
        LocalUser user = UserUtil.getLocalUser(token);

        try {
            MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), new ByteArrayInputStream(bytes));

                long start = System.currentTimeMillis();
                String folder = "use";
                String folderPath;
                    String uUID = Uuid.getUUID();
                    // 服务器根路径/站名路径/变电设备路径/文件类型路径
                    String destDirectory = "filestore"+ File.separator  + "wiringdiagram"+ File.separator  +uUID;
                    folderPath = sftpInit.upload(rootPath, destDirectory, file.getInputStream(), fileNameNew, 1, folder);
                    SysFileDiagramVo sysFileVo = new SysFileDiagramVo();
                    sysFileVo.setBusinessId(uUID);
                    sysFileVo.setType(type);
                    sysFileVo.setCount(1);
                    sysFileVo.setDate(DateUtil.getYYMMDDTime());
                    sysFileVo.setFileName(fileNameNew);
                    String suffix = fileNameNew.substring(fileNameNew.lastIndexOf('.'));
                    sysFileVo.setSuffixName(suffix);
                    sysFileVo.setFileSize(file.getSize());
                    if(suffix.contains("pdf") || suffix.contains("PDF")){
                        sysFileVo.setFileType("0");
                    }else{
                        sysFileVo.setFileType("1");
                    }
                String path = rootPath + File.separator + destDirectory;
                SftpConnectConfig sftpConnectConfig = sftpConnectConfigService.findOne();
                String httpPath= "http://"+ sftpConnectConfig.getHost()+":"+sftpConnectConfig.getHttpPort()+"/"+folderPath.replace(File.separator, Constants.NO_DATA)+"/"+fileNameNew;
                WiringDiagram wiringDiagram=new WiringDiagram();
                wiringDiagram.setId(uUID);
                wiringDiagram.setFileName(fileName);
                wiringDiagram.setFileType(sysFileVo.getFileType());
                wiringDiagram.setFilePath(httpPath);
                wiringDiagram.setFileSize(file.getSize());
                 wiringDiagram.setDeleted("0");
                wiringDiagram.setCreateDate(LocalDateTime.now());
                this.add(wiringDiagram);
                // 服务器是linux 直接存储该路径
                sysFileVo.setFilePath(folderPath.replace(File.separator, Constants.NO_DATA));
                sysFileService.saveOrUpdate(sysFileVo);

        } catch (Exception e) {
            log.error("导入异常:{}", e);
            throw new OwlException(e.getMessage());
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.IMPORT.SUCCESS", "");
    }

    @Override
    public int deleteWiringDiagram(String token, List<String> idList) {
        return wiringDiagramMapper.deleteWiringDiagram(idList);
    }

    @Override
    public Map<String, Object> importModelFile(byte[] bytes, String token, String type, String fileNameNew,
                                               String rootPath, String modelType, String fileName,String siteId, String status) {
        if (StrUtil.isEmpty(token)) {
            log.error("Token为空！");
            throw new OwlException("Token为空！");
        }

        if (StrUtil.isEmpty(modelType)) {
            log.error("modelType为空！");
            throw new OwlException("modelType为空！");
        }

        if (StringUtils.isEmpty(fileName)) {
            log.error("fileName为空！");
            throw new OwlException("fileName为空！");
        }

        if (ArrayUtil.isEmpty(bytes)) {
            log.error("文件二进制流为空！");
            throw new OwlException("文件二进制流为空！");
        }

        // 获取当前用户
        LocalUser user = UserUtil.getLocalUser(token);

        try {
            MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), new ByteArrayInputStream(bytes));

            long start = System.currentTimeMillis();
            String folder = "use";
            String folderPath;
            String uUID = Uuid.getUUID();
            // 服务器根路径/站名路径/变电设备路径/文件类型路径
            String destDirectory = "filestore"+ File.separator  + "model"+ File.separator  +uUID;
            folderPath = sftpInit.upload(rootPath, destDirectory, file.getInputStream(), fileNameNew, 1, folder);
            SysFileDiagramVo sysFileVo = new SysFileDiagramVo();
            sysFileVo.setBusinessId(uUID);
            sysFileVo.setType(type);
            sysFileVo.setCount(1);
            sysFileVo.setDate(DateUtil.getYYMMDDTime());
            sysFileVo.setFileName(fileNameNew);
            String suffix = fileNameNew.substring(fileNameNew.lastIndexOf('.'));
            sysFileVo.setSuffixName(suffix);
            sysFileVo.setFileSize(file.getSize());
            if(suffix.contains("pdf") || suffix.contains("PDF")){
                sysFileVo.setFileType("0");
            }else{
                sysFileVo.setFileType("1");
            }
            String path = rootPath + File.separator + destDirectory;
            SftpConnectConfig sftpConnectConfig = sftpConnectConfigService.findOne();
                String httpPath= "http://"+ sftpConnectConfig.getHost()+":"+sftpConnectConfig.getHttpPort()+"/"+folderPath.replace(File.separator, Constants.NO_DATA)+"/"+fileNameNew;
            SysModel sysModel=new SysModel();

            sysModel.setModelId(uUID);
            sysModel.setOriginalName(fileNameNew);
            sysModel.setName(fileName);
            sysModel.setFilePath(httpPath);
            sysModel.setStatus(status);
            sysModel.setDeleted("0");
            sysModel.setModelType(modelType);
            sysModel.setTimeStamp(LocalDateTime.now());
            sysModel.setSiteId(siteId);
            sysModelDao.add(sysModel);
            // 服务器是linux 直接存储该路径
            sysFileVo.setFilePath(folderPath.replace(File.separator, Constants.NO_DATA));
            sysFileService.saveOrUpdate(sysFileVo);

        } catch (Exception e) {
            log.error("导入异常:{}", e);
            throw new OwlException(e.getMessage());
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.IMPORT.SUCCESS", "");
    }

    @Override
    public int deleteModel(String token, List<String> idList) {
        return wiringDiagramMapper.deleteModel(idList);
    }


}
