package com.huatek.busi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.huatek.busi.common.FileTypeEnum;
import com.huatek.busi.common.util.FileUtils;
import com.huatek.busi.dto.SysFileDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.init.SftpInit;
import com.huatek.busi.mapper.SysFileMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.vo.RModelVo;
import com.huatek.busi.vo.SysFileVo;
import com.huatek.busi.where.SysFileSelectVo;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.dao.impl.BaseDao;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
@Service(interfaceClass = IRModelService.class)
@Transactional(rollbackFor = Exception.class)
public class RModelServiceImpl extends BaseDao<RModel, String> implements IRModelService {

    @Resource
    private SftpInit sftpInit;

    @Reference(check = false)
    IGlobalSettingItemService globalSettingItemService;

    @Resource
    private SysFileMapper sysFileMapper;

    @Override
    public void saveOrUpdate(RModelVo rModelVo){
        RModel rModel = new RModel();
        rModelVo.setId(Uuid.getUUID());
        rModelVo.setCreateDate(LocalDateTime.now());
        rModelVo.setDeleted(Constants.DEFAULT_NO);
        BeanUtils.copyProperties(rModelVo, rModel);
        this.add(rModel);
    }

    @Override
    public Map<String, Object> downloadModels(String id){
        try{
            GlobalSettingItem globalSettingItem = globalSettingItemService.findOne();
            if(globalSettingItem != null){
                String localTempPath = globalSettingItem.getLocalTempPath();

                // 查询文件信息
                SysFileDto sysFileDto = sysFileMapper.findModelById(id);
                String filePath = sysFileDto.getFilePath();
                String remoteFile = sysFileDto.getFileName();

                // 下载本地文件夹
                String returnCode = sftpInit.download(filePath, remoteFile, localTempPath, remoteFile);
                if(Objects.equals(returnCode, "0")){
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("filePath", localTempPath + File.separator + remoteFile);
                    map.put("fileName", remoteFile);
                    return map;
                }
                return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.NOT.FIND.FILEPATH", "");
            }
        }catch (Exception e){
            log.error("文件下载异常：{}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.DOWNLOAD.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.DOWNLOAD.FAIL", "");
    }

    @Override
    @Transactional(propagation= Propagation.SUPPORTS)
    public Map<String, Object> deleteModels(List<String> ids, String equType){
        //去除重复元素
        ids = ids.stream().distinct().collect(Collectors.toList());
        updateByIdsAndEquType(ids, equType);
        GlobalSettingItem globalSettingItem = globalSettingItemService.findOne();
        String localTempPath = globalSettingItem.getLocalTempPath();

        List<SysFileDto> sysFileDtoList = sysFileMapper.findModelByDeleted(ids, equType);
        if(CollectionUtil.isNotEmpty(sysFileDtoList)){
            for (SysFileDto item :sysFileDtoList){
                String id = item.getId();
                String filePath = item.getFilePath();
                String fileName = item.getFileName();
                String suffixFilePath = item.getSuffixFilePath();

                if(StrUtil.isNotEmpty(filePath) && StrUtil.isNotEmpty(fileName) && StrUtil.isNotEmpty(suffixFilePath)){
                    // 远程下载文件至本地
                    String returnCode = sftpInit.download(filePath, fileName, localTempPath, fileName);
                    if(Objects.equals(returnCode, "1")){
                        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.NOT.FIND.FILEPATH", "");
                    }
                    // 远程删除文件
                    sftpInit.delete("/" + filePath + "/", fileName);
                    // 本地文件上传远程服务器上
                    filePath = sftpInit.upload(suffixFilePath, localTempPath, File.separator + fileName, "delete");
                    sysFileMapper.updateModelPathById(id, filePath);
                    // 删除本地临时文件
                    FileUtils.deleteFile(localTempPath.replace("/", "\\") + "\\" + fileName);
                }
            }
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.DELETE.SUCCESS", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.DELETE.FAIL", "");
    }

    @Override
    public int updateByIdsAndEquType(List<String> ids, String eqType){
        return sysFileMapper.deleteModels(ids, eqType);
    }

    @Override
    public Map<String, Object> modelList(SysFileSelectVo sysFileSelectVo){
        PageHelper.startPage(sysFileSelectVo.getPage(), sysFileSelectVo.getLimit());
        sysFileSelectVo.setFileType(FileTypeEnum.R_TEMPLATE.getKey());
        sysFileSelectVo.setDeleted(Constants.DEFAULT_NO);
        Page<SysFileDto> page = sysFileMapper.modelList(sysFileSelectVo);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "BUSINESS.QUERY.SUCCESS", page.getResult());
    }
}
