package com.bcxin.auth.web.controller.manage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.auth.common.constant.Constants;
import com.bcxin.auth.common.constant.ShiroConstants;
import com.bcxin.auth.common.core.domain.AjaxResult;
import com.bcxin.auth.common.utils.DES3;
import com.bcxin.auth.common.utils.IdWorker;
import com.bcxin.auth.common.utils.IdcardUtils;
import com.bcxin.auth.common.utils.StringUtils;
import com.bcxin.auth.system.domain.*;
import com.bcxin.auth.system.service.ComCerService;
import com.bcxin.auth.system.util.ConfigUtil;
import com.bcxin.obpm.domain.ObpmCompanyCertificate;
import com.bcxin.obpm.dto.PdfChangeDTO;
import com.bcxin.obpm.service.CreatePDFService;
import com.bcxin.auth.system.service.PerCerService;
import com.bcxin.obpm.util.Base64Img;
import com.bcxin.obpm.util.QRCodeUtil;
import com.google.common.collect.Maps;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author linqinglin
 * @date 2021/11/19 0019 9:57
 */

@Controller
@RequestMapping("/manage/cer")
public class CerPrintController {
    protected Logger logger = LoggerFactory.getLogger(CerPrintController.class);

    private String prefix = "manage/certificate";

    public static Function<Object,String> toJSONString = e -> {
        if (e != null) {
            return JSON.toJSONString(e);
        }
        return null;
    };

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    IdWorker idWorker;

    @Resource
    private ConfigUtil configUtil;

    private static String pathName = "";

    @Autowired
    CreatePDFService createPDFService;

    @Autowired
    private PerCerService perCerService;

    @Autowired
    private ComCerService comCerService;

    @Value("${bcxin.profile}")
    private String baseFolder;


    private Cache<String, String> dzzgzPrintCache;

    @PostConstruct
    public void init()
    {
        dzzgzPrintCache = cacheManager.getCache(ShiroConstants.DZZGZPRINTCACHE);
    }

    @RequestMapping("comPrint")
    public String postComPrint(String id, ModelMap modelMap) throws Exception {
        ComCerDto comCerDto = comCerService.findById(id);
        comCerDto.setPdfChangeDTOList(JSON.parseArray(comCerDto.getChange(), PdfChangeDTO.class));
        comCerDto.setXkzh(comCerDto.getXkzh().replace("京公保服",""));
        //DES3加密
        String CerId = URLEncoder.encode(DES3.encode(comCerDto.getBusinessid()), "UTF-8");
        if (comCerDto.getZf().equals("z")) {
            comCerDto.setQrcode(configUtil.getValueByKey(Constants.V5_OUT_API_URL) + "/manage/cer/showCer?id=" + CerId + "&type=1");
        } else {
            comCerDto.setQrcode(configUtil.getValueByKey(Constants.V5_OUT_API_URL) + "/manage/cer/showCer?id=" + CerId + "&type=0");
        }
        if ("61".equals(configUtil.getCurrentNative())) {
            String path = createPDFService.createPDF(comCerDto, "001");
            comCerDto.setPath(path);
        } else {
            //证书编号去掉最后的号字
            comCerDto.setXkzh(comCerDto.getXkzh() != null && comCerDto.getXkzh().endsWith("号") ?
                    comCerDto.getXkzh().substring(0, comCerDto.getXkzh().length() - 1) : comCerDto.getXkzh());
            if (comCerDto.getQrcode() != null) {
                String pathName = QRCodeUtil.generateBase64QRCode(comCerDto.getQrcode(), 100, 100, "jpg");
                comCerDto.setQrcode(pathName);
            }
            String compic1_1 = configUtil.getValueByKey(Constants.COMPANY_PIC_1_1);
            if (compic1_1 != null) {
                comCerDto.setCompanyPic_1_1(compic1_1);
            }
            String compic1_2 = configUtil.getValueByKey(Constants.COMPANY_PIC_1_2);
            if (compic1_2 != null) {
                comCerDto.setCompanyPic_1_2(compic1_2);
            }
            String compic2_1 = configUtil.getValueByKey(Constants.COMPANY_PIC_2_1);
            if (compic2_1 != null) {
                comCerDto.setCompanyPic_2_1(compic2_1);
            }
            String compic2_2 = configUtil.getValueByKey(Constants.COMPANY_PIC_2_2);
            if (compic2_2 != null) {
                comCerDto.setCompanyPic_2_2(compic2_2);
            }
        }
        modelMap.addAttribute("printData", comCerDto);
        return prefix + "/original/comPrint" + configUtil.getCurrentNative();
    }

    @RequestMapping("addComPrint")
    @ResponseBody
    public AjaxResult addComPrint(@RequestBody ComCerDto comCerDto) throws Exception {
        if (comCerDto.getCall_back_url() != null) {
            comCerDto.setCall_back_url(configUtil.getV5IPURL() + comCerDto.getCall_back_url());
        }
        if (comCerDto.getManagement() != null) {
            comCerDto.setManagement(getManagement(comCerDto.getManagement()));
        }
        comCerService.insert(comCerDto);
        return AjaxResult.success(configUtil.getLocalHostURL() + "manage/cer/comPrint" + "?id=" + comCerDto.getId());
    }


    @ResponseBody
    @RequestMapping("addPerPrint")
    public AjaxResult addPerPrint(@RequestBody PerCerDto printData) throws Exception {
        if ("61".equals(configUtil.getCurrentNative())) {
            return AjaxResult.error("陕西请调用其他方法！");
        } else {
            String PerId = URLEncoder.encode(DES3.encode(printData.getBusiness_id()), "UTF-8");
            printData.setQrcode(configUtil.getValueByKey(Constants.V5_OUT_API_URL) + "/manage/cer/showPer?id=" + PerId);
            if (StringUtils.isNotEmpty(printData.getCall_back_url())) {
                printData.setCall_back_url(configUtil.getV5IPURL() + printData.getCall_back_url());
            }
            String securityPic = configUtil.getValueByKey(Constants.SECURITY_PIC);
            if (StringUtils.isNotEmpty(securityPic)) {
                printData.setSecurityPic(securityPic);
            }
            if (!printData.getPhoto().startsWith("http")&&StringUtils.isNotEmpty(printData.getPhoto())) {
                printData.setPhoto(configUtil.getV5URL() + printData.getPhoto());
            }
            perCerService.insert(printData);
            return AjaxResult.success(configUtil.getLocalHostURL() + "manage/cer/PerPrint" + "?id=" + printData.getId());
        }
    }

    @RequestMapping("PerPrint")
    public String postPerPrint(String id, ModelMap modelMap) throws Exception {
        PerCerDto printData = perCerService.findById(id);
        if (printData == null) {
            throw new Exception("没有找到需要打印的记录");
        }
        if (StringUtils.isNotEmpty(printData.getQrcode())){
            String pathName = QRCodeUtil.generateBase64QRCode(printData.getQrcode(), 100, 100, "jpg");
            printData.setQrcode(pathName);
        }
        if (StringUtils.isNotEmpty(printData.getPhoto())) {
            String Base64Photo = Base64Img.encodeImageToBase64(new URL(printData.getPhoto()));
            printData.setPhoto(Base64Photo);
        }
        modelMap.addAttribute("printData", printData);
        return prefix + "/original/perPrint" + configUtil.getCurrentNative();
    }

    @RequestMapping("PerPrints")
    public String postPerPrints(String request, ModelMap modelMap) throws Exception {
        //String request = "[{\"address\":\"北京市北京经济技术开发区西环南路\",\"fzrq\":\"2021-12-08\",\"idnum\":\"351111199801281111\",\"photo\":\"https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg\",\"qrcode\":\"https://www.baidu.com/\",\"xm\":\"老王\",\"zsbh\":\"2011111111\",\"callBackUrl\":\"http://localhost:7080//manage/cer/testRequest\"},{\"address\":\"北京市北京经济技术开发区西1\",\"fzrq\":\"2021-12-12\",\"idnum\":\"350525199801283510\",\"photo\":\"https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg\",\"qrcode\":\"https://www.baidu.com/\",\"xm\":\"老王1\",\"zsbh\":\"京2019300011\",\"callBackUrl\":\"http://localhost:7080//manage/cer/testRequest\"},{\"address\":\"北京市北京经济技术开发区西1\",\"fzrq\":\"2021-12-12\",\"idnum\":\"350525199801283510\",\"photo\":\"https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg\",\"qrcode\":\"https://www.baidu.com/\",\"xm\":\"老王2\",\"zsbh\":\"京2019300011\",\"callBackUrl\":\"http://localhost:7080//manage/cer/testRequest\"},{\"address\":\"北京市北京经济技术开发区西1\",\"fzrq\":\"2021-12-12\",\"idnum\":\"350525199801283510\",\"photo\":\"https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg\",\"qrcode\":\"https://www.baidu.com/\",\"xm\":\"老王3\",\"zsbh\":\"2019311111\",\"callBackUrl\":\"http://localhost:7080//manage/cer/testRequest\"}]";
        List<PerCerDto> perCerDtoList = JSONArray.parseArray(request, PerCerDto.class);

        String securityPic = configUtil.getValueByKey(Constants.SECURITY_PIC);
        List<PerCerDto> printDatas = new ArrayList<>();
        for (PerCerDto perCerDto : perCerDtoList) {
            perCerService.insert(perCerDto);
            perCerDto.setSecurityPic(securityPic);
            if (StringUtils.isNotEmpty(perCerDto.getQrcode())) {
                String pathName = QRCodeUtil.generateBase64QRCode(perCerDto.getQrcode(), 100, 100, "jpg");
                perCerDto.setQrcode(pathName);
            }
            if (StringUtils.isNotEmpty(perCerDto.getPhoto())) {
                String base64Photo = Base64Img.encodeImageToBase64(new URL(perCerDto.getPhoto()));
                perCerDto.setPhoto(base64Photo);
            }
            printDatas.add(perCerDto);
        }

        modelMap.addAttribute("printDatas", printDatas);
        return prefix + "/original/perPrint" + configUtil.getCurrentNative();
    }

    /**
     * 陕西资格证打印
     */
    @RequestMapping("/snPerPrints")
    public String postSnPerPrints(String certs, ModelMap modelMap) throws Exception {
        //陕西目前只支持最多打印2个人
        if(certs == null) return null;
        List<PerCerDto> perCerDtoList = JSONArray.parseArray(certs, PerCerDto.class);
        perCerDtoList = perCerDtoList.stream().limit(2).collect(Collectors.toList());
        String securityPic = configUtil.getValueByKey(Constants.SECURITY_PIC);
        List<PerCerDto> printDatas = new ArrayList<>();
        for (PerCerDto perCerDto : perCerDtoList) {
            if (StringUtils.isNotEmpty(securityPic)) {
                perCerDto.setSecurityPic(securityPic);
            }
            //二维码
            String PerId = URLEncoder.encode(DES3.encode(perCerDto.getBusiness_id()), "UTF-8");
            perCerDto.setQrcode(configUtil.getValueByKey(Constants.V5_OUT_API_URL) + "/manage/cer/showPer?id=" + PerId);

            if (StringUtils.isNotEmpty(perCerDto.getCall_back_url())) {
                perCerDto.setCall_back_url(configUtil.getV5IPURL() + perCerDto.getCall_back_url());
            }

            if (StringUtils.isNotEmpty(perCerDto.getPhoto()) && !perCerDto.getPhoto().startsWith("http")) {
                perCerDto.setPhoto(configUtil.getV5URL() + perCerDto.getPhoto());
            }
            perCerService.insert(perCerDto);

            if (StringUtils.isNotEmpty(perCerDto.getQrcode())){
                String pathName = QRCodeUtil.generateBase64QRCode(perCerDto.getQrcode(), 100, 100, "jpg");
                perCerDto.setQrcode(pathName);
            }
            if (StringUtils.isNotEmpty(perCerDto.getPhoto())) {
                String Base64Photo = Base64Img.encodeImageToBase64(new URL(perCerDto.getPhoto()));
                perCerDto.setPhoto(Base64Photo);
            }
            printDatas.add(perCerDto);
        }

        modelMap.addAttribute("printDatas", printDatas);
        return prefix + "/original/perPrint" + configUtil.getCurrentNative();
    }

    /**
     * 通用资格证打印，用于新增记录
     */
    @RequestMapping("/addcomPerCer")
    @ResponseBody
    public AjaxResult addcomPerCer(@RequestBody List<PerCerDto> perCerDtoList, ModelMap modelMap) throws Exception {
        if(perCerDtoList == null) return null;
        String securityPic = configUtil.getValueByKey(Constants.SECURITY_PIC);
        ArrayList<Integer> idList = new ArrayList<>();
        for (PerCerDto perCerDto : perCerDtoList) {
            perCerService.insert(perCerDto);
            idList.add(perCerDto.getId());
        }

        return AjaxResult.success(configUtil.getLocalHostURL() + "manage/cer/comPerPrints" + "?ids=" + idList.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    /**
     * 通用资格证打印
     */
    @RequestMapping("/comPerPrints")
    public String comPerPrints(String ids, ModelMap modelMap) throws Exception {
        if(ids == null) return null;
        List<String> idList = Arrays.asList(ids.split(","));
        List<PerCerDto> perCerDtoList = perCerService.findByIds(idList);
        String securityPic = configUtil.getValueByKey(Constants.SECURITY_PIC);
        List<PerCerDto> printDatas = new ArrayList<>();
        for (PerCerDto perCerDto : perCerDtoList) {
            if (StringUtils.isNotEmpty(securityPic)) {
                perCerDto.setSecurityPic(securityPic);
            }
            //二维码
            String PerId = URLEncoder.encode(DES3.encode(perCerDto.getBusiness_id()), "UTF-8");
            perCerDto.setQrcode(configUtil.getValueByKey(Constants.V5_OUT_API_URL) + "/manage/cer/showPer?id=" + PerId);

            if (StringUtils.isNotEmpty(perCerDto.getCall_back_url())) {
                perCerDto.setCall_back_url(configUtil.getV5IPURL() + perCerDto.getCall_back_url());
            }

            if (StringUtils.isNotEmpty(perCerDto.getPhoto()) && !perCerDto.getPhoto().startsWith("http")) {
                perCerDto.setPhoto(configUtil.getV5URL() + perCerDto.getPhoto());
            }

            if (StringUtils.isNotEmpty(perCerDto.getQrcode())){
                String pathName = QRCodeUtil.generateBase64QRCode(perCerDto.getQrcode(), 100, 100, "jpg");
                perCerDto.setQrcode(pathName);
            }
            if (StringUtils.isNotEmpty(perCerDto.getPhoto())) {
                String Base64Photo = Base64Img.encodeImageToBase64(new URL(perCerDto.getPhoto()));
                perCerDto.setPhoto(Base64Photo);
            }
            printDatas.add(perCerDto);
        }

        modelMap.addAttribute("printDatas", printDatas);
        return prefix + "/original/perPrint" + configUtil.getCurrentNative();
    }

    // 生成资格证打印记录
    @RequestMapping("recordsPerGenerated")
    @ResponseBody
    public String recordsPerGenerated(String id, boolean isPrint) {
        PerCerDto perCerDto = perCerService.findById(id);
        if (isPrint) {
            //打印成功
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String printDate = simpleDateFormat.format(new Date());
            //保存打印数据
            perCerDto.setPrintlnState(true);
            perCerDto.setPrintDate(printDate);
            perCerService.updatePrintState(perCerDto);
            String body = perCerService.generatePrintRecord(perCerDto);
            JSONObject object = JSONObject.parseObject(body);
            //string
            String s = object.getString("msg");
            if (s.equals("success")) {
                perCerDto.setCallBackResult(body);
                perCerDto.setCallBackState(true);
                perCerService.updateCallBackState(perCerDto);
            }
        } else {
            //取消打印
            perCerDto.setPrintlnState(false);
            perCerDto.setCallBackResult("取消打印");
            perCerDto.setCallBackState(false);
            perCerService.cancelPrint(perCerDto);
        }
        return "true";
    }

    // 生成许可证打印记录
    @RequestMapping("recordsComGenerated")
    @ResponseBody
    public String recordsComGenerated(String id, boolean isPrint) {
        ComCerDto comCerDto = comCerService.findById(id);
        //System.out.println("dddddddddddddddddd"+comCerDto);
        if (isPrint) {
            //打印成功
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String printDate = simpleDateFormat.format(new Date());
            //保存打印数据
            comCerDto.setPrintlnState(true);
            comCerDto.setPrintDate(printDate);
            comCerService.updatePrintState(comCerDto);
            String body = comCerService.generatePrintRecord(comCerDto);
            System.out.println(body);
            JSONObject object = JSONObject.parseObject(body);
            //string
            String s = object.getString("code");
            if (s.equals("1")) {
                comCerDto.setCallBackResult(body);
                comCerDto.setCallBackState(true);
                comCerService.updateCallBackState(comCerDto);
            } else {
                comCerDto.setCallBackResult(body);
                comCerDto.setCallBackState(false);
                comCerService.updateCallBackState(comCerDto);
            }
        } else {
            //取消打印
            comCerDto.setPrintlnState(false);
            comCerDto.setCallBackResult("取消打印");
            comCerDto.setCallBackState(false);
            comCerService.cancelPrint(comCerDto);
        }
        return "true";
    }

    @PostMapping("recordsGenerateds")
    @ResponseBody
    public String recordsGenerateds(String perList,String isPrint) {
        System.out.println(perList);
        List<PerCerDto> perCerDtos = JSONArray.parseArray(perList,PerCerDto.class);
        for (PerCerDto perCerDto:perCerDtos
        ) {
            if (isPrint.equals("true")) {
                //打印成功
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String printDate = simpleDateFormat.format(new Date());
                //保存打印数据
                perCerDto.setPrintlnState(true);
                perCerDto.setPrintDate(printDate);
                perCerService.updatePrintState(perCerDto);
                //String body = perCerService.upload(perCerDto.getCallBackUrl(), perCerDto.getZsbh(), printDate, perCerDto.getPrintPeople(), perCerDto.getPrintOrganization());
                String body = perCerService.generatePrintRecord(perCerDto);
                JSONObject object = JSONObject.parseObject(body);
                //string
                String s = object.getString("msg");
                if (s.equals("success")) {
                    perCerDto.setCallBackResult(body);
                    perCerDto.setCallBackState(true);
                    perCerService.updateCallBackState(perCerDto);
                }
            } else {
                //取消打印
                perCerDto.setPrintDate("-");
                perCerDto.setPrintlnState(false);
                perCerDto.setCallBackResult("取消打印");
                perCerDto.setCallBackState(false);
                perCerService.cancelPrint(perCerDto);
            }
        }
        return "true";
    }


    @RequestMapping("testRequest")
    @ResponseBody
    public JSONObject testRequest(String callBackUrl, String callBackId) throws Exception {
        Map map = new HashMap();
        map.put("msg", "success");
        map.put("code", "10000");
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject;
    }

    private String getManagement(ObpmCompanyCertificate obpmCompanyCertificate) {
        String management = "";
        String ss[] = obpmCompanyCertificate.getBusinessScope().split(";");
        for (int i = 0; i < ss.length; i++) {
            if (ss[i].equals("01")) {
                management += "门卫、";
            } else if (ss[i].equals("02")) {
                management += "巡逻、";
            } else if (ss[i].equals("03")) {
                management += "守护、";
            } else if (ss[i].equals("04")) {
                management += "押运、";
            } else if (ss[i].equals("05")) {
                management += "随身护卫、";
            } else if (ss[i].equals("06")) {
                management += "安全检查、";
            } else if (ss[i].equals("07")) {
                management += "区域秩序维护、";
            } else if (ss[i].equals("08")) {
                management += "安全风险评估、";
            } else if (ss[i].equals("09")) {
                management += "安全技术防范、";
            } else if (ss[i].equals("10")) {
                management += "其他、";
            }
        }
        if (management != null && management != "") {
            management = management.substring(0, management.length() - 1);
        }
        return management;
    }

    private String getManagement(String management) {
        String newManagement = "";
        String ss[] = management.split(";");
        for (int i = 0; i < ss.length; i++) {
            if (ss[i].equals("01")) {
                newManagement += "门卫、";
            } else if (ss[i].equals("02")) {
                newManagement += "巡逻、";
            } else if (ss[i].equals("03")) {
                newManagement += "守护、";
            } else if (ss[i].equals("04")) {
                logger.info("Current native: {}", configUtil.getCurrentNative()); // 添加日志
                if ("11".equals(configUtil.getCurrentNative())) {
                    newManagement += "武装押运、"; // 北京
                } else {
                    newManagement += "押运、"; // 陕西或其他地区
                }
            } else if (ss[i].equals("05")) {
                newManagement += "随身护卫、";
            } else if (ss[i].equals("06")) {
                newManagement += "安全检查、";
            } else if (ss[i].equals("07")) {
                if (!"11".equals(configUtil.getCurrentNative())) {
                    newManagement += "区域秩序维护、";
                }
                } else if (ss[i].equals("08")) {
                newManagement += "安全风险评估、";
            } else if (ss[i].equals("09")) {
                newManagement += "安全技术防范、";
            } else if (ss[i].equals("10")) {
                if (!"11".equals(configUtil.getCurrentNative())) {
                    newManagement += "其他、";
                }
            }
        }
        System.out.println("经营范围123:"+newManagement);
        if (newManagement != null && newManagement != "") {
            newManagement = newManagement.substring(0, newManagement.length() - 1);
        }

        return newManagement;
    }


    /**
     * 下载证书
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("download")
    public void exportApprovals(String templateName, HttpServletResponse response) throws Exception {
        File file = new File(templateName);
        if (file != null) {
            ServletOutputStream out = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            InputStream is = new FileInputStream(file);
            try {
                int read = 0;
                byte[] buffer = new byte[8192];
                while ((read = is.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                is.close();
                out.flush();
                out.close();
                file.delete();
            } catch (Exception e) {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
                file.delete();
            }
        }
    }

    public static void main(String[] args) {

        PerCerDto perCerDto = new PerCerDto();
        PerCerDto perCerDto1 = new PerCerDto();
        perCerDto.setXm("老王");
        perCerDto.setPhoto("https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg");
        perCerDto.setQrcode("https://www.baidu.com/");
        perCerDto.setAddress("北京市北京经济技术开发区西环南路26号院19号楼4层2-401");
        perCerDto.setIdnum("350525199801283510");
        perCerDto.setFzrq("2021-12-08");
        perCerDto.setZsbh("京2019300001");
        perCerDto1.setXm("老王");
        perCerDto1.setPhoto("https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-12-06%2F1638756956362941233.jpg");
        perCerDto1.setQrcode("https://www.baidu.com/");
        perCerDto1.setAddress("北京市北京经济技术开发区西环南路26号院19号楼4层2-401");
        perCerDto1.setIdnum("350525199801283510");
        perCerDto1.setFzrq("2021-12-08");
        perCerDto1.setZsbh("京2019300001");
        List<PerCerDto> perCerDtoList = new ArrayList<>();
        perCerDtoList.add(perCerDto);
        perCerDtoList.add(perCerDto1);
        System.out.println(perCerDtoList.size());

        //http://localhost:7080//manage/cer/PerPrint?callBackUrl=http://localhost:7080//manage/cer/testRequest&xm=%E8%80%81%E7%8E%8B&photo=http://bj.baibaodun.cn:8801/ars-web/getResource.do?path=upload/2019-07-05/1562315663331.jpg&qrcode=https://www.baidu.com/&address=%E5%8C%97%E4%BA%AC%E5%B8%82%E5%8C%97%E4%BA%AC%E7%BB%8F%E6%B5%8E%E6%8A%80%E6%9C%AF%E5%BC%80%E5%8F%91%E5%8C%BA%E8%A5%BF%E7%8E%AF%E5%8D%97%E8%B7%AF26%E5%8F%B7%E9%99%A219%E5%8F%B7%E6%A5%BC4%E5%B1%822-401&nation=%E6%B1%89%E6%97%8F&idnum=350525199801283510&fzrq=2021-12-08&zsbh=%E4%BA%AC2019300001
    }

    @RequestMapping("showCer")
    public String findCer(String id, String type, ModelMap modelMap) throws Exception {
        //DES3解密
        String cerId = DES3.decode(id);
        cerId = cerId.replace(Constants.OLD_FROMID, Constants.NEW_FROMID);

        System.out.println(cerId);
        ComCerDto comCerDto = getComCerDto(cerId);
        if (StringUtils.isNotEmpty(comCerDto.getManagement())) {
            comCerDto.setManagement(getManagement(comCerDto.getManagement()));
        }
        if (StringUtils.isNotEmpty(comCerDto.getFzrq())) {
            String year = comCerDto.getFzrq().substring(0, 4);
            System.out.println(year);
            String mon = comCerDto.getFzrq().substring(5, 7);
            String day = comCerDto.getFzrq().substring(8);
            comCerDto.setFzrq(year + "年" + mon + "月" + day + "日");
        }
        if (StringUtils.isNotEmpty(comCerDto.getXkzh())) {
            String shortName = configUtil.getCurrentNativeShort();
            String newxkzh = comCerDto.getXkzh().replace(shortName + "公保服", "");
            comCerDto.setXkzh(shortName + "公保服" + newxkzh + "号");
        }
        modelMap.addAttribute("comCerDto", comCerDto);
        if (type.equals("1")) {
            return prefix + "/original/company";
        }
        return prefix + "/original/companyCopy";
    }

    @RequestMapping("showPer")
    public String findPer(String id, ModelMap modelMap) throws Exception {
        //DES3解密
       String perId = DES3.decode(id);
        perId = perId.replace(configUtil.getValueByKey(Constants.OLD_ZZG_FROMID), configUtil.getValueByKey(Constants.NEW_ZZG_FROMID));
        System.out.println(perId);
        PerCerDto perCerDto=getPerCerDto(perId);
       if (StringUtils.isNotEmpty(perCerDto.getIdnum())){
           perCerDto.setBirthDate(IdcardUtils.getBirthDayByIdCard(perCerDto.getIdnum()));
       }
        String currentProvince=configUtil.getCurrentProvince();
        modelMap.addAttribute("currentProvince", currentProvince);
        modelMap.addAttribute("perCerDto", perCerDto);
        return prefix + "/original/person";
    }

    private PerCerDto getPerCerDto(String perId) {
        Map<String, Object> params = Maps.newHashMap();
        //生产记录的id
        params.put("id", perId);
        //链式构建请求
        String returnValue = StringUtils.EMPTY;
        PerCerDto perCerDto = new PerCerDto();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(configUtil.getV5IPURL() + "/Electronic_certificates");
            RequestConfig.Builder requestConfig = RequestConfig.custom();
            requestConfig.setConnectTimeout(Constants.TIMEOUT);
            requestConfig.setConnectionRequestTimeout(Constants.TIMEOUT);
            requestConfig.setSocketTimeout(Constants.TIMEOUT);
            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(params), "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            System.out.println(requestEntity);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader(Constants.ACCESS_TOKEN, configUtil.getValueByKey(Constants.ACCESS_TOKEN));
            //System.out.println(httpPost);
            httpPost.setConfig(requestConfig.build());
            httpPost.setEntity(requestEntity);
            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时，必须用此方法
            JSONObject object = JSONObject.parseObject(returnValue);
            perCerDto = JSON.toJavaObject(object, PerCerDto.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return perCerDto;
    }

    public ComCerDto getComCerDto(String businessid) {
        Map<String, Object> params = Maps.newHashMap();
        //生产记录的id
        params.put("id", businessid);
        //链式构建请求
        String returnValue = StringUtils.EMPTY;
        ComCerDto comCerDto = new ComCerDto();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(configUtil.getV5IPURL() + "/comPrint/findLicenseById");
            RequestConfig.Builder requestConfig = RequestConfig.custom();
            requestConfig.setConnectTimeout(Constants.TIMEOUT);
            requestConfig.setConnectionRequestTimeout(Constants.TIMEOUT);
            requestConfig.setSocketTimeout(Constants.TIMEOUT);
            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(params), "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            System.out.println(requestEntity);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader(Constants.ACCESS_TOKEN, configUtil.getValueByKey(Constants.ACCESS_TOKEN));
            //System.out.println(httpPost);
            httpPost.setConfig(requestConfig.build());
            httpPost.setEntity(requestEntity);
            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时，必须用此方法
            JSONObject object = JSONObject.parseObject(returnValue);
            comCerDto = JSON.toJavaObject(object, ComCerDto.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return comCerDto;
    }

    /**
     * 北京保安服务设立许可审批通过后生成证书的正副本
     *
     * @param securityService
     * @throws Exception
     */
    @RequestMapping("createSecurityService")
    @ResponseBody
    public Map<String,String> createSecurityService(@RequestBody SecurityService securityService) throws Exception {
        Map<String, String> urlPath = createPDFService.createSecurityServicePDF(securityService);
        return urlPath;
    }

    /**
     * 荣誉证书
     *
     * @param honorCertificates
     * @throws Exception
     */
    @RequestMapping("createHonorCertificate")
    @ResponseBody
    public List<HonorCertificate> createHonorCertificate(@RequestBody List<HonorCertificate> honorCertificates) throws Exception {
        List<HonorCertificate> pdfHonorCertificates = createPDFService.createHonorCertificatePDF(honorCertificates);
        return pdfHonorCertificates;
    }

    /**
     * 下载文件
     * @param path
     * @param response
     */
    @RequestMapping(value = "getResource")
    public void getResource(String path, HttpServletResponse response) throws Exception {
        InputStream is = null;
        ServletOutputStream out = null;
        File file = new File(path);
        if(file != null) {
            try {
                out = response.getOutputStream();
                String encodedFileName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20");
                response.addHeader("Content-Disposition", "attachment;filename=\"" + encodedFileName + "\"");
                is = new FileInputStream(file);
                int read = 0;
                byte[] buffer = new byte[8192];
                while ((read = is.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
            }catch (Exception e ){
                logger.error(e.getMessage(),e);
            }finally {
                if(is!=null){
                    is.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            }
        }
    }
    /**
     * 浏览器预览文件
     * @param path
     * @param response
     */
    @RequestMapping(value = "viewResource")
    public void viewResource(String path, HttpServletResponse response) throws Exception {
        InputStream is = null;
        ServletOutputStream out = null;
        File file = new File(path);
        if(file != null) {
            try {
                out = response.getOutputStream();
                String encodedFileName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20");
                response.addHeader("Content-Disposition", "inline;filename=\"" + encodedFileName + "\"");
                is = new FileInputStream(file);
                int read = 0;
                byte[] buffer = new byte[8192];
                while ((read = is.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
            }catch (Exception e ){
                logger.error(e.getMessage(),e);
            }finally {
                if(is!=null){
                    is.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            }
        }
    }

    /**
     * <b> 根据缓存key读取数据访问打印列表进行加载（结合接口/cerPdfPrints使用） </b>
     * @author ZXF
     * @create 2025/02/28 0028 16:53
     * @version
     * @注意事项 </b>
     */
    @RequestMapping("snpdfviewer/{cacheKey}")
    public String snpdfviewer(@PathVariable("cacheKey") String cacheKey, ModelMap modelMap) throws Exception {
        String datas = dzzgzPrintCache.get(cacheKey);
        List<String> result = JSON.parseObject(datas, List.class);
        modelMap.addAttribute("printDatas", result);
        return prefix + "/original/snpdfviewer";
    }

    /**
     * <b> 陕西保安员电子证书打印专用：批量处理要打印的电子证书（支持一张纸打2个证） </b>
     * 请求方式：body JSON格式 ：{"paths":["/uploads/pdf/dianziqianzhang/shanxi/2025-01-25/C610100queueId_600.pdf","/uploads/pdf/dianziqianzhang/shanxi/2025-01-25/C610100queueId_606.pdf","/uploads/pdf/dianziqianzhang/shanxi/2025-01-25/C610100queueId_641.pdf","/uploads/pdf/dianziqianzhang/shanxi/2025-01-25/C610100queueId_643.pdf","/uploads/pdf/dianziqianzhang/shanxi/2025-01-25/C610100queueId_644.pdf"]}
     * 请求地址：http://localhost:7080/manage/cer/cerPdfPrints
     * 返回：AjaxResult 其中msg值为访问打印列表的访问地址
     * @author ZXF
     * @create 2025/02/28 0028 16:53
     * @version
     * @注意事项 缓存时间 10秒</b>
     */
    @ResponseBody
    @RequestMapping("cerPdfPrints")
    public AjaxResult cerPdfPrints(@RequestBody CertificatePaths paths) throws Exception {
        String cacheKey = "print"+idWorker.nextId();
        List<String> result = createPDFService.mergePdfServer(paths);
        dzzgzPrintCache.put(cacheKey,JSON.toJSONString(result));
        return AjaxResult.success(configUtil.getLocalHostURL() + "manage/cer/snpdfviewer/" + cacheKey);
    }

    //调试用
    /*@RequestMapping("cerPdfPrints1")
    public String cerPdfPrints1(ModelMap modelMap) throws Exception {
        List<String> result = new ArrayList<>();
        result.add("/manage/cer/viewResource?path=D://data/auth/upload/temp/2025-03-03/1346143589232590848.pdf");
        result.add("/manage/cer/viewResource?path=D://data/auth/upload/temp/2025-03-03/1346143590146949120.pdf");
        result.add("/manage/cer/viewResource?path=D://data/auth/upload/temp/2025-03-03/1346143590839009280.pdf");
        modelMap.addAttribute("printDatas", result);
        return prefix + "/original/snpdfviewer";
    }*/

}
