package com.bonus.boot.manager.physical.controller;

import com.bonus.boot.manager.manager.annotation.LogAnnotation;
import com.bonus.boot.manager.manager.entity.R;
import com.bonus.boot.manager.manager.utils.*;
import com.bonus.boot.manager.physical.dao.EmployeeHealthCheckDao;
import com.bonus.boot.manager.physical.entity.EmployeeHealthCheckBean;
import com.bonus.boot.manager.physical.service.EmployeeHealthCheckService;
import io.swagger.annotations.ApiOperation;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
 * 体检结果管理
 * @author tqzhang
 */
@RestController
@RequestMapping("employeeHealthCheck")
public class EmployeeHealthCheckController {
    private static final Logger log = LoggerFactory.getLogger("EmployeeHealthCheckController");
    /**
     * 服务对象
     */
    @Resource
    private EmployeeHealthCheckService service;
    @Resource
    private EmployeeHealthCheckDao dao;

    @LogAnnotation
    @PostMapping("getMsgContent")
    @ApiOperation(value = "体检结果管理-列表")
    public R getList(EmployeeHealthCheckBean o){
        System.err.println("EmployeeHealthCheckBean="+o);
        if ("1".equals(o.getType())){
            o.setHospitalId(UserUtil.getLoginUser().getHospitalId());
        }else {
            o.setHospitalId("");
        }
        List<EmployeeHealthCheckBean> list = service.getList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }

    /**------------------------------------------------------导入体检报告开始------------------------------------------------------------------*/
//    private String uploadUrl = "D://files/physicalResult/"+ DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/";
//    private String uploadUrl = "/data/yn/physicalResult/"+ DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/";
    static List<String> nameList = new ArrayList<>();
    @LogAnnotation
    @PostMapping("uploadZip")
    @ApiOperation(value = "体检结果管理-上传报告")
    public AjaxRes importReport(@RequestParam("file") MultipartFile file) throws Exception {
        String uploadUrl = "/data/yn/physicalResult/"+ DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/";
        AjaxRes ar = new AjaxRes();
        ar.setFailMsg(GlobalConst.IMP_FAIL);
        File f = new File(uploadUrl);
        if (f.exists() && f.isDirectory()) {
            System.out.println("文件夹存在");
        }else {
            f.mkdirs();
        }
        String packageName = file.getOriginalFilename();
        String folderName = packageName.substring(0, packageName.length() - 4);
        //检查是否已存在
        log.debug("检查压缩包是否存在");
        File oldFile = new File(uploadUrl + packageName);
        if (oldFile != null) {
            //实现幂等
            oldFile.delete();
            deleteAllFile(uploadUrl + folderName);
        }
        //复制压缩包
        log.debug("复制压缩包到指定路径");
        file.transferTo(new File(uploadUrl + packageName));
        log.debug("开始解压...");
        if (file.getOriginalFilename().indexOf(".zip") > 0) {
            unPackZip(packageName, uploadUrl);
        }
        for (int i = 0; i < nameList.size(); i++) {
            String imageFiles = "physicalResult/"+DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/"+nameList.get(i);
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                imageFiles = "physicalResult/"+DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/"+nameList.get(i);
            }
            System.out.println(imageFiles);
            dao.updatePDFAddress(nameList.get(i).split("-")[1],imageFiles);
//            String linkPath = "http://112.31.106.186:1616/yntj/";//正式环境
            String linkPath = "http://192.168.0.14:18077/yntj";//测试环境
            String phone = dao.getPersonPhoneNumber(nameList.get(i).split("-")[1]);
            String msg = nameList.get(i).split("-")[0]+"您的体检结果已生成，请点击查看"+linkPath;
            SendPhoneMessageUtil.SendPhoneMsg(phone,msg);
            System.out.println(phone+"体检结果短信发送完成");
        }
        System.out.println("体检结果短信发送完成");
        //解压
        log.info("上传并解压成功");
        ar.setSucceedMsg(GlobalConst.IMP_SUCCEED);
        return ar;
    }

    private static final String SECRET_KEY = "your-secret-key";

    public static String generateEncryptedLink(String originalUrl) {
        String encryptedUrl = encryptUrl(originalUrl);
        String link = "<a href=" + encryptedUrl + ">这里</a>";
        return link;
    }

    private static String encryptUrl(String url) {
        String encryptedUrl = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest((SECRET_KEY + url).getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) {
                sb.append(String.format("%02x", b));
            }
            encryptedUrl = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encryptedUrl;
    }


    /**
     * 递归实现 删除文件夹下所有目录及文件
     **/
    public boolean deleteAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                if (!f.delete()) {
                    return false;
                }
            } else {
                if (!this.deleteAllFile(f.getAbsolutePath())) {
                    return false;
                }
            }
        }
        return file.delete();
    }
    //解压zip包，解决文件夹乱码问题
    public void unPackZip(String fileName, String destPath) throws Exception {
        ZipFile zipFile = new ZipFile(destPath + fileName);
        //getEncoding()解决字符集乱码
        zipFile.setFileNameCharset(getEncoding(destPath + fileName));
        zipFile.extractAll(destPath);

    }
    //getEncoding()解决字符集乱码

    private static String getEncoding(String path) throws Exception {
        nameList = new ArrayList<>();;
        String encoding = "GBK";
        ZipFile zipFile = new ZipFile(path);
        zipFile.setFileNameCharset(encoding);
        List<FileHeader> list = zipFile.getFileHeaders();
        for (int i = 0; i < list.size(); i++) {
            FileHeader fileHeader = list.get(i);
            String fileName = fileHeader.getFileName();
            if (isMessyCode(fileName)) {
                encoding = "UTF-8";
                break;
            }
            if (fileName.indexOf(".pdf") != -1 || fileName.indexOf(".PDF") != -1){
                nameList.add(fileName);
            }
        }
        return encoding;
    }
    //判断字符集
    private static boolean isMessyCode(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
            // 从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
            if ((int) c == 0xfffd) {
                // 存在乱码
                return true;
            }
        }
        return false;
    }

    /**---------------------------------------------------导入体检报告结束-------------------------------------------------------------------*/


    public HashMap<String, Object> uploadFileSpring(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        List<MultipartFile> tmps = new ArrayList<MultipartFile>();
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                tmps.add(file);
            }
            map.put("filePath", tmps);
        }
        return map;
    }
    /**---------------------------------------------------导入Excel数据开始-------------------------------------------------------------------*/
    @LogAnnotation
    @PostMapping("/importExcel")
    @ApiOperation(value = "体检结果管理数据导入")
    public AjaxRes workerInfoImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxRes ar = new AjaxRes();
        try {
            String code = service.saveExcelInfo(request,file);
            if ("导入成功".equals(code)){
                ar.setSucceedMsg("导入成功");
            }else{
                ar.setFailMsg(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ar;
    }
}

