package com.lz.modules.app.controller;

import com.lz.common.utils.*;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.RecordFile;
import com.lz.modules.flow.service.RecordFileService;
import com.lz.modules.sys.controller.AbstractController;
import com.lz.modules.sys.entity.app.ResultRecord;
import com.lz.modules.sys.service.app.ResultRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 绩效记录表
 *
 * @author zgh
 * @email zgh@ldxinyong.com
 * @date 2020-08-10 17:19:22
 */
@RestController
public class UploadController extends AbstractController {

    @Autowired
    private RecordFileService recordFileService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;

    @Autowired
    private  ResultRecordService resultRecordService;

    /**
     * 信息
     */
    @RequestMapping("/file/uploadFile")
    public R uploadFile(HttpServletRequest request, Long recordId) {
        MultipartHttpServletRequest requestFile = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = requestFile.getFile("file");
        if (multipartFile == null) {
            R.error("文件不能为空");
        }

        String suffix = CommonUtil.getSuffix(multipartFile.getOriginalFilename());
        String preffix = CommonUtil.getPreffix(multipartFile.getOriginalFilename());
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.setWritable(true);
            filePath.mkdirs();
        }
        File tempFile = new File(path + "/" + System.currentTimeMillis() + suffix);
        SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        try {
            ResultRecord resultRecord = resultRecordService.selectResultRecordById(recordId);
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), tempFile);
            String url = OSSUtils.uploadImage(tempFile.getPath());
            RecordFile recordFile = new RecordFile();
            Long staffId = resultRecord.getStaffId();
            StaffEntity staffEntity = staffService.selectStaffById(staffId);
            DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(staffId);
            recordFile.setDepartmentId(departmentsStaffRelateEntity.getDepartmentId());
            recordFile.setFileName(preffix + "_" + myFmt2.format(new Date()) + suffix);
            recordFile.setFileUrl(url);
            recordFile.setRecordId(recordId);
            recordFile.setStaffId(staffId);
            recordFile.setStaffName(staffEntity.getName());
            recordFileService.insertRecordFile(recordFile);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            tempFile.delete();
        }
        return R.ok();
    }


    /**
     * 信息
     */
    @RequestMapping("/file/downZip")
    public void downZip(String ids, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtil.isBlank(ids)) {
            return ;
        }
        String is[] = ids.split(",");
        List<String> paths = new ArrayList<>();
        String path = request.getSession().getServletContext().getRealPath("/downloads") + "/" + System.currentTimeMillis() + "/";
        logger.info("========zippath ==========" + path);
        try {
            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.setWritable(true);
                filePath.mkdirs();
            }
            String zipFilePath = path + "file.zip";
            ZipCompressor zc = new ZipCompressor(zipFilePath);
            for (String i : is) {
                RecordFile recordFile = recordFileService.selectRecordFileById(NumberUtil.objToLongDefault(i, 0l));
                if (recordFile != null) {
                    String fileName = recordFile.getFileUrl().substring(recordFile.getFileUrl().lastIndexOf("/") + 1);
                    String pathFileName = path + fileName;
                    paths.add(pathFileName);
                    FileUtils.downloadFile(recordFile.getFileUrl(), pathFileName);
                    logger.info("path : " + path);
                }
            }
            String[] str = paths.toArray(new String[paths.size()]);
            zc.compress(str);



            File file = new File(zipFilePath); // 要下载的文件绝对路径
            InputStream ins = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[ins.available()];
            ins.read(buffer);
            ins.close();

            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream ous = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            ous.write(buffer);
            ous.flush();
            ous.close();
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            FileUtils.deleteFileAndFoder(path);
        }
    }

}
