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

import com.bonus.boot.manager.basic.dao.HospitalDao;
import com.bonus.boot.manager.basic.entity.HospitalBean;
import com.bonus.boot.manager.basic.service.HospitalService;
import com.bonus.boot.manager.career.dao.CareerDao;
import com.bonus.boot.manager.career.entity.CareerBean;
import com.bonus.boot.manager.career.service.CareerService;
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 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.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 医院管理表控制层
 * @author tqzhang
 * @Data 2023/5/31 9:30
 */
@RestController
@RequestMapping("career")
public class CareerController {
    /**
     * 服务对象
     */
    private static final Logger log = LoggerFactory.getLogger("CareerController");
    @Resource
    private CareerService service;

    @Resource
    private CareerDao dao;
    @Resource
    private EmployeeHealthCheckDao employeeHealthCheckDao;
    @LogAnnotation
    @PostMapping("getMsgContent")
    @ApiOperation(value = "职业体检健康结果管理-列表")
    public R getList(CareerBean o){
        List<CareerBean> list = service.getList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    @LogAnnotation
    @PostMapping("getPhysicalInfoForOne")
    @ApiOperation(value = "职业体检健康结果管理-体检详情")
    public R getPhysicalInfoForOne(CareerBean o){
        List<CareerBean> list = service.getPhysicalInfoForOne(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }

    /**---------------------------------------------------导入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;
    }

    @LogAnnotation
    @PostMapping("/StateExcel")
    @ApiOperation(value = "职业体检结果导入已体检人员名单")
    public AjaxRes stateInfoImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxRes ar = new AjaxRes();
        try {
            String code = service.saveExcelInfos(request,file);
            if ("导入成功".equals(code)){
                ar.setSucceedMsg("导入成功");
            }else{
                ar.setFailMsg(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ar;
    }

    @RequestMapping(value = "updateInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "职业体检健康结果管理调岗统计-修改")
    public AjaxRes updateInfo(@RequestBody CareerBean bean){
        AjaxRes ar = new AjaxRes();
        int cb = service.updateInfo(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }

    /**------------------------------------------------------导入体检报告开始------------------------------------------------------------------*/
//    private String uploadUrl = "D://files/careerPhysicalResult/"+ DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/";
//        private String uploadUrl = "/data/yn/careerPhysicalResult/"+ 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/careerPhysicalResult/"+ 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 = "careerPhysicalResult/"+DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/"+nameList.get(i);
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                imageFiles = "careerPhysicalResult/"+DateTimeHelper.getNowYear()+"/"+DateTimeHelper.getNowMonths()+"/"+DateTimeHelper.getNowDay()+"/"+nameList.get(i);
            }
            System.out.println(imageFiles+nameList.get(i));
            dao.updatePDFAddress(nameList.get(i).split("-")[1],imageFiles+nameList.get(i));
            String idNumber = nameList.get(i).split("-")[1];
            String phone = employeeHealthCheckDao.getPersonPhoneNumber(idNumber);
            String linkPath = "http://192.168.0.14:18077/yntj";//z环境
            String msg = nameList.get(i).split("-")[0]+"您的体检结果已生成，请点击查看 "+linkPath;
            SendPhoneMessageUtil.SendPhoneMsg(phone,msg);
            System.out.println(phone+"职业体检结果短信发送完成");
        }
        //解压
        log.info("上传并解压成功");
        ar.setSucceedMsg(GlobalConst.IMP_SUCCEED);
        return ar;
    }

    /**
     * 递归实现 删除文件夹下所有目录及文件
     **/
    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.split("/")[1]);
            }
        }
        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 static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);
        System.out.println("Yesterday's date: " + String.valueOf(yesterday));
    }

}

