package com.zcxk.rmcp.web.service.impl;

import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.rmcp.core.dao.ImportFileMapper;
import com.zcxk.rmcp.core.entity.ImportFile;
import com.zcxk.rmcp.web.service.AsyncTaskImportService;
import com.zcxk.rmcp.web.service.CommonService;
import com.zcxk.rmcp.web.service.ImportFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;

/**
 * 
 * @author linqingwei
 * @date 2021-07-23 15:52
 */
@Service
public class ImportFileServiceImpl implements ImportFileService {

    @Resource
    private ImportFileMapper importFileMapper;

    @Autowired
    private CommonService commonService;
    @Autowired
    private AsyncTaskImportService asyncTaskImportService;

    @Override
    public int insertSelective(ImportFile record) {
        record.setStatus(1);
        record.setCreateDate(LocalDateTime.now());
        record.setUpdateDate(LocalDateTime.now());
        record.setCreateBy(UserUtil.getUsername());
        record.setUpdateBy(UserUtil.getUsername());
        return importFileMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(ImportFile record) {
        record.setUpdateDate(LocalDateTime.now());
        record.setUpdateBy(UserUtil.getUsername());
        return importFileMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void importExcel(Integer categoryId, Integer importType, MultipartFile file) {
        LoginUser loginUser = UserUtil.getCurrentUser();

        String filePath = commonService.getExcelFilePath("import");
        java.io.File uploadDir = new File(filePath);
        try {
            file.transferTo(uploadDir);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //生成导入记录
        ImportFile importFile = new ImportFile();
        importFile.setTenantId(loginUser.getTenantId());
        importFile.setUserId(loginUser.getId());
        importFile.setType(importType);
        importFile.setImportFilePath(filePath);
        importFile.setImportFileName(file.getOriginalFilename());
        importFile.setFailFilePath("");
        importFile.setImportStatus(0);
        importFile.setSuccessNum(0);
        importFile.setFailNum(0);
        this.insertSelective(importFile);

        //异步执行任务
        if(importType == 1){
            asyncTaskImportService.executeAsyncDeviceTask(importFile,categoryId);
        }
        if(importType == 2){
            asyncTaskImportService.executeAsyncInstallTask(importFile,categoryId);
        }

        if(importType == 3){
            asyncTaskImportService.executeAsyncInstallPanTask(importFile,categoryId);
        }

    }

    @Override
    public void downloadFailFile(Integer objId, HttpServletResponse response) {
        ImportFile result = importFileMapper.findById(objId);

        if (result != null) {
            if (result.getFailFilePath() != null && !StringUtils.equals("",result.getFailFilePath())) {
                try (FileInputStream fileInputStream = new FileInputStream(result.getFailFilePath())){

                    String filename = URLEncoder.encode(result.getImportFileName(), "UTF-8");

                    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
                    ServletOutputStream outputStream = response.getOutputStream();

                    //将文件写入浏览器
                    byte[] bys = new byte[fileInputStream.available()];
                    fileInputStream.read(bys);
                    outputStream.write(bys);
                    outputStream.flush();
                    outputStream.close();


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
