package com.bcxin.ars.rest.manage;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bcxin.ars.dao.PersonBaseInfoDao;
import com.bcxin.ars.dao.SecurityPersonDao;
import com.bcxin.ars.dao.certificate.SecurityCertificateDao;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.GradeCertificateToSAASDto;
import com.bcxin.ars.dto.PersonInfoDto;
import com.bcxin.ars.dto.page.SecurityCertificateDto;
import com.bcxin.ars.dto.page.SecurityCertificatePageSearchDto;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.Config;
import com.bcxin.ars.model.PageResult;
import com.bcxin.ars.model.PersonBaseInfo;
import com.bcxin.ars.model.SecurityPerson;
import com.bcxin.ars.model.certificate.GradeCertificate;
import com.bcxin.ars.model.certificate.SecurityCertificate;
import com.bcxin.ars.model.sb.Personcertificate;
import com.bcxin.ars.rest.BaseController;
import com.bcxin.ars.rest.util.manage.ManageResultUtil;
import com.bcxin.ars.rest.util.manage.TableResult;
import com.bcxin.ars.service.PersonBaseInfoService;
import com.bcxin.ars.service.certificate.GradeCertificateService;
import com.bcxin.ars.service.certificate.SecurityCertificateService;
import com.bcxin.ars.service.sb.PersoncertificateService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.service.util.SAASInterfaceUtil;
import com.bcxin.ars.util.*;
import com.bcxin.ars.util.poi.ExcelUtil;
import com.bcxin.ars.util.redis.RedisUtil;
import com.com.bcxin.ars.com.abcxin.smart.core.web.validate.AjaxPageResponse;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 保安员证管理
 * @author linqinglin
 * @date 2019/01/11 0011 14:56
 */
@Controller
@RequestMapping("manage/security")
public class ManageSecurityController {

    Logger logger = LoggerFactory.getLogger(ManageSecurityController.class);

    @Value("${BBD_H5_URL}")
    private String bbdH5Url;

    @Autowired
    private ConfigUtils configUtils;

    @Autowired
    private SecurityCertificateService securityCertificateService;

    @Autowired
    private PersoncertificateService personcertificateService;

    @Autowired
    private PersonBaseInfoService personBaseInfoService;

    @Autowired
    private SecurityCertificateDao securityCertificateDao;

    @Autowired
    private SecurityPersonDao securityPersonDao;

    @Autowired
    private SAASInterfaceUtil saasInterfaceUtil;

    @Autowired
    private BaseController baseController;

    @Autowired
    private PersonBaseInfoDao personBaseInfoDao;

    @Autowired
    private GradeCertificateService gradeCertificateService;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 保安员证审批流程修复页面
     * @return
     */
    @RequestMapping("init")
    public ModelAndView init() {
        ModelAndView view = new ModelAndView("/manage/security/manageList");
        return view;
    }

    /**
     * 上传保安员证头像页面
     * @param idNumber
     * @return
     */
    @RequestMapping("upload/{idNumber}")
    public ModelAndView upload(@PathVariable String idNumber) {
        ModelAndView view = new ModelAndView("/manage/security/upload");
        view.addObject("idNumber",idNumber);
        return view;
    }

    /**
     * 上传证件照页面
     * @param idnum
     * @return
     */
    @RequestMapping("uploadHeadImg/{idnum}")
    public ModelAndView uploadHeadImg(@PathVariable String idnum) {
        ModelAndView view = new ModelAndView("/manage/security/uploadHeadImg");
        view.addObject("idnum",idnum);
        return view;
    }

    /**
     * 列表分页查询
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("searchList")
    @ResponseBody
    public TableResult searchList(@RequestParam Map<Object, Object> params, HttpServletRequest req) {
        //查询初始化
        Map<Object, Object> p = CTLUtil.init(req, params);
        Config nativeConfig = configUtils.getConfigByKey(Constants.CURRENT_NATIVE);
        p.put("areaCode", nativeConfig.getValue());
        PageResult page = personcertificateService.searchPrintList(p);
        TableResult result = new TableResult();
        result.setTotal(page.getTotal());
        result.setRows(page.getRows());
        return result;
    }

    /**
     * 保安员证书分页查询
     * @param dto
     * @param page
     * @return
     */
    @RequestMapping("searchForPage")
    @ResponseBody
    @Deprecated
    public AjaxPageResponse searchForPage(SecurityCertificatePageSearchDto dto, AjaxPageResponse<SecurityCertificateDto> page){
        securityCertificateService.searchForPage(dto,page);
        return page;
    }

    /**
     * 手动获取人口库头像
     * @param personId
     * @return
     * @throws Exception
     */
    @RequestMapping("getPersonImg/{personId}")
    public @ResponseBody
    JSONObject getPersonImg(@PathVariable Long personId) throws Exception{
        try {
            return ManageResultUtil.returnSuccessJson(securityCertificateService.getPersonImg(personId),"securityList","refreshCurrent", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","securityList", "closeCurrent", "");
        }
    }
    @RequestMapping("viewCount")
    public @ResponseBody
    JSONObject viewCount() throws Exception{
        try {
            Map<String,String> map = new HashedMap();
            String key = DateUtil.getCurrentDate(DateUtil.FORMAT11)+"_"+Constants.CZ_SERVICEID;
            map.put(Constants.CZ_SERVICEID, redisUtil.get(key));
            return ManageResultUtil.returnSuccessJson(JSON.toJSONString(map),"securityList","refreshCurrent", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","securityList", "closeCurrent", "");
        }
    }


    /**
     * 上传保安员证头像
     * @param personBaseInfo
     * @param file
     * @param idNumber
     * @return
     * @throws Exception
     */
    @RequestMapping("uploadPersonImg")
    @ResponseBody
    public AjaxResult uploadPersonImg(PersonBaseInfo personBaseInfo, MultipartFile file, String idNumber) throws Exception {
        AjaxResult result = new AjaxResult();
        result.setSuccessful(true);
        result.setMsg("后台运行中！");

        Date now = new Date();
        if(file == null ){
            return result;
        }
        String[] fileTypes = file.getOriginalFilename().split("\\.");
        String materialFileType = fileTypes[fileTypes.length-1];
        //文件类型
        /***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
        String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
        //判断是否为允许上传的文件类型
        if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
        {   result.setSuccessful(false);
            result.setMsg("文件格式不对，重新上传！！");
            return result;
        }
        String fileName = now.getTime() +"."+ materialFileType;
        String dirDate = DateUtil.systemDate.format(now);
        File dir = new File(configUtils.uploadFolder + dirDate);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        String key = "upload/" + dirDate + "/" + fileName;
        String url = "getResource.do?path=" + key;
        String targetPath = configUtils.uploadFolder + dirDate + "/" + fileName;
        File targetFile = new File(targetPath);
        file.transferTo(targetFile);
        personBaseInfo.setIdnum(idNumber);
        personBaseInfo.setCreateTime(new Date());
        personBaseInfo.setActive(true);
        personBaseInfo.setImgPath(url);
        personBaseInfo.setState(Constants.PHOTO_YES);
        personBaseInfoService.save(personBaseInfo);


        if(!Constants.BEIJING.equals(configUtils.getCurrentNative())) {
            SecurityCertificate securityCertificate = new SecurityCertificate();
            securityCertificate.setHavephoto(true);
            securityCertificate.setIdnum(personBaseInfo.getIdnum());
            securityCertificate.setHeadImg(url);
            securityCertificateDao.updateHavePhotodByIdnum(securityCertificate);
        }

        return result;
    }


    /**
     * 上传保安员证头像
     * @param securityCertificate
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("uploadHeadImg")
    @ResponseBody
    public AjaxResult uploadHeadImg(SecurityCertificate securityCertificate, MultipartFile file) throws Exception {
        AjaxResult result = new AjaxResult();
        try{
            result = baseController.uploadFile(file);
            if(result.isSuccessful()){
                result.setSuccessful(true);
                result.setMsg("上传成功");
                Map<String,String> map = (Map<String,String>)result.getData();
                securityCertificateDao.resetDraw(securityCertificate.getIdnum(),map.get("url"));
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            result.setSuccessful(false);
            result.setMsg("上传失败！");
        }

        return result;
    }

    /**
     * 北京保安员旧数据批量保存电子证地址
     * @return
     * @throws Exception
     */
    @RequestMapping("batchSaveElectronCerUrlForOldData")
    @ResponseBody
    public JSONObject batchSaveElectronCerUrlForOldData() throws Exception {
        try{
            if(Constants.BEIJING.equals(configUtils.getCurrentNative())){
                List<SecurityCertificate> certificateList = securityCertificateDao.findOldDataForPerson();
                List<SecurityCertificate> list = new Vector<>();
                if(certificateList.size() > 0) {

                    //使用线程池
                    CountDownLatch workCount = ThreadUtil.newCountDownLatch(certificateList.size());
                    ThreadPoolExecutor threadPoolExecutor = ThreadUtil.newExecutor(15, 15);

                    certificateList.forEach(detail -> {
                        threadPoolExecutor.execute(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    //电子证书
                                    String data = DES3.encode(JSON.toJSONString(detail.getSecuritypersonid(), SerializerFeature.WriteDateUseDateFormat));
                                    detail.setElectronCerUrl("http://www.bktang.cn/pxxtfront/bbdapp/#/certificate?certificateId=" + URLEncoder.encode(data, "utf-8") + "$http://bjapi.baibaodun.cn:8803/");
                                    list.add(detail);
                                } catch (Exception e) {
                                    logger.error(e.getMessage(),e);
                                    e.printStackTrace();
                                } finally {
                                    workCount.countDown();
                                }
                            }
                        });
                    });

                    try {
                        //线程等待全部数据文件生成完成
                        workCount.await();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(),e);
                        throw e;
                    }

                    //根据数据数量情况，切分不同的大小
                    int limit = configUtils.limitSize;
                    //计算拆分次数
                    int count = new Double(Math.ceil(list.size() * 1.0 / limit)).intValue();

                    //使用线程池
                    CountDownLatch workCount1 = ThreadUtil.newCountDownLatch(count);

                    //循环拆分次数 生成相应数据文件
                    for (int i = 0; i < count; i++) {
                        int finalI = i;
                        threadPoolExecutor.execute(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    List<SecurityCertificate> subList = list.stream().skip(finalI * limit).limit(limit).collect(Collectors.toList());
                                    securityCertificateDao.batchSaveElectronCerUrl2(subList);
                                } catch (Exception e) {
                                    logger.error(e.getMessage(),e);
                                    e.printStackTrace();
                                } finally {
                                    workCount1.countDown();
                                }
                            }
                        });
                    }

                    try {
                        //线程等待全部数据文件生成完成
                        workCount1.await();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(),e);
                        throw  e;
                    }
                    threadPoolExecutor.shutdown();
                }
            }

            return ManageResultUtil.returnSuccessJson("操作成功","securityList","", "");
        }catch (Exception e){
            logger.error(e.getMessage());
            return ManageResultUtil.returnFailedJson("操作失败","securityList", "closeCurrent", "");
        }

    }


    /**
     * 资格证书信息同步给saas
     * @param cerId
     * @return
     * @throws Exception
     */
    @RequestMapping("sendToSAAS/{cerId}")
    public @ResponseBody
    JSONObject sendToSAAS(@PathVariable Long cerId) throws Exception{
        try {
            SecurityCertificate securityCertificate = securityCertificateService.findById(cerId);
            this.updateSecurityPersonCertificateInfo(securityCertificate);
            return ManageResultUtil.returnSuccessJson("操作成功","securityList","refreshCurrent", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","securityList", "closeCurrent", "");
        }
    }

    @RequestMapping("viewPersonBaseImg/{idnum}")
    @ResponseBody
    public AjaxResult viewPersonBaseImg(@PathVariable String idnum) {
        AjaxResult result = new AjaxResult();
        PersonBaseInfo personBaseInfo = personBaseInfoDao.findByIdNum(idnum);
        if(personBaseInfo != null && StringUtil.isNotEmpty(personBaseInfo.getImgPath())) {
            result.setSuccessful(true);
            result.setData(personBaseInfo.getImgPath());
        }else{
            result.setMsg("没有人口库照片");
            result.setSuccessful(false);
        }
        return result;
    }


    /**
     * 修改为代推送
     * @param idnum
     * @return
     */
    @RequestMapping("authorization/{idnum}")
    @ResponseBody
    public AjaxResult authorization(@PathVariable String idnum) {
        AjaxResult result = new AjaxResult();
        int i = securityCertificateDao.updateIisDrawByIdNum(idnum, Constants.ISDRAW_WAITPASH);
        if(i>0){
            result.setSuccessful(true);
            result.setData(null);
        }else {
            result.setMsg("授权失败");
            result.setSuccessful(false);
        }
        return result;
    }

    /**
     * 批量授权页面
     * @return
     */
    @RequestMapping("batchupdatestate")
    public ModelAndView batchInit2(String isMakeCard) {

        ModelAndView view = new ModelAndView("/manage/security/batchupdatestate");

        view.addObject("isMakeCard",isMakeCard);
        return view;
    }




    /**
     *
     * @return
     */
    @RequestMapping("batchexportAppPhoto")
    public ModelAndView batchexportAppPhoto() {
        ModelAndView view = new ModelAndView("/manage/security/batchexportAppPhoto");
        return view;
    }



    /**
     * 批量修改
     * @param idNums
     * @return
     */
    @RequestMapping("batchUpdateisDraw")
    @ResponseBody
    public JSONObject batchOperation2(String idNums,String isState,String isMakeCard) {
        try {
            List<String> urlList = securityCertificateService.batchUpdateState(idNums, isState,isMakeCard);
            return ManageResultUtil.returnSuccessJson("操作成功","visaList","closeCurrent", "",urlList);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","visaList", "closeCurrent", "");
        }

    }




//    /**
//     * 批量导出app证件照
//     * @param idNums
//     * @return
//     */
//    @RequestMapping("exportAppPhoto")
//    @ResponseBody
//    public JSONObject exportAppPhoto(String idNums) {
//        try {
//            List<String> urlList = securityCertificateService.batchexportAppPhoto(idNums);
//            return ManageResultUtil.returnSuccessJson("操作成功","visaList","closeCurrent", "",urlList);
//
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return ManageResultUtil.returnFailedJson("操作失败","visaList", "closeCurrent", "");
//        }
//
//
//    }




    @Value("${temp-folder}")
    private String tempfolder;
    /**
     * 批量导出app证件照
     * @param
     * @return
     */
    @RequestMapping("exportAppPhoto")
    @ResponseBody
    public JSONObject exportAppPhoto(MultipartFile file) {

        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        ManageResultUtil result=new ManageResultUtil();
        if (!fileType.toUpperCase().equalsIgnoreCase("XLS") && !fileType.toUpperCase().equalsIgnoreCase("XLSX")) {
            return ManageResultUtil.returnFailedJson("导入的模板文件有误","visaList", "closeCurrent", "");
        }
        long startTime = System.currentTimeMillis();
        try {
            Date now = new Date();
            String fileName = now.getTime() + "." + fileType;
            String dirDate = DateUtil.systemDate.format(now);
            File dir = new File(tempfolder + dirDate);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String targetPath = tempfolder + dirDate + "/" + fileName;
            File targetFile = new File(targetPath);
            //开始列


            logger.info("执行人员文件上传..." + targetFile);
            file.transferTo(targetFile);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>(); // 花名册的所有数据
            List<Map<String, String>> faildList = new ArrayList<Map<String, String>>(); // 定义失败的list
            FileInputStream inStream = new FileInputStream(targetFile);
            Workbook workBook = WorkbookFactory.create(inStream);
            Sheet sheet = workBook.getSheetAt(0); // 读取第一个sheet
            boolean flag = true;
            // 设置初始行,
            int i = 0;
            while (flag) {
                Row row = sheet.getRow(i);
                //读取关键字行不为空，默认原因列为最后一列
                if (row != null) {
                    Map<String, String> data = new HashMap<String, String>();
                    //读取Excel中的对应列,若不存在抛出异常
                    try {
                        //把每一列放入一个map中，并且把每个map放入list中
                        if(StringUtil.isNotEmpty(ExcelUtil.getCellValue(row.getCell(1)))){
                            data.put("name",ExcelUtil.getCellValue(row.getCell(0)));
                            data.put("idNum",ExcelUtil.getCellValue(row.getCell(1)));
                            list.add(data);
                        }
                    } catch (Exception e) {
                        if (e instanceof ArsException) {
                            data.put("errorMsg", e.getMessage());
                        } else {
                            data.put("errorMsg", "格式有错");
                        }
                        faildList.add(data);
                    }
                } else {
                    flag = false;
                }
                i++;
            }
            // 花名册内没内容
            if (list.size() == 0 && faildList.size() == 0) {
                return ManageResultUtil.returnFailedJson("导入的Excle中没有记录","visaList", "closeCurrent", "");
            }


            List<String> urlList = securityCertificateService.batchexportAppPhoto(list);
            return ManageResultUtil.returnSuccessJson("操作成功","visaList","closeCurrent", "",urlList);
//
//return  null;


        } catch (Exception e) {
            e.printStackTrace();
            return ManageResultUtil.returnFailedJson("导出出错了","visaList", "closeCurrent", "");

        }


    }




    @RequestMapping("viewIdPhoto/{idnum}")
    @ResponseBody
    public AjaxResult viewIdPhoto(@PathVariable String idnum) {
        AjaxResult result = new AjaxResult();
        SecurityPerson securityPerson = securityPersonDao.findUsedByIdNum(idnum);
        if(securityPerson != null && StringUtil.isNotEmpty(securityPerson.getIdPhoto())) {
            result.setSuccessful(true);
            result.setData(securityPerson.getIdPhoto());
        }else{
            result.setMsg("没有证件照片");
            result.setSuccessful(false);
        }
        return result;
    }


    @RequestMapping("usePersonBaseImg/{idnum}")
    public @ResponseBody
    JSONObject usePersonBaseImg(@PathVariable String idnum) throws Exception{
        try {
            PersonBaseInfo personBaseInfo = personBaseInfoDao.findByIdNum(idnum);
            if(personBaseInfo != null && StringUtil.isNotEmpty(personBaseInfo.getImgPath())) {
                securityCertificateDao.resetDraw(idnum, personBaseInfo.getImgPath());
                return ManageResultUtil.returnSuccessJson("操作成功", "visaList", "refreshCurrent", "");
            }else{
                return ManageResultUtil.returnFailedJson("没有人口库照片","visaList", "closeCurrent", "");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","visaList", "closeCurrent", "");
        }
    }

    @RequestMapping("useIdPhoto/{idnum}")
    public @ResponseBody
    JSONObject useIdPhoto(@PathVariable String idnum) throws Exception{
        try {
            SecurityPerson securityPerson = securityPersonDao.findUsedByIdNum(idnum);
            if(securityPerson != null && StringUtil.isNotEmpty(securityPerson.getIdPhoto())) {
                securityCertificateDao.resetDraw(idnum, securityPerson.getIdPhoto());
                return ManageResultUtil.returnSuccessJson("操作成功", "visaList", "refreshCurrent", "");
            }else{
                return ManageResultUtil.returnFailedJson("没有APP证件照片","visaList", "closeCurrent", "");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","visaList", "closeCurrent", "");
        }
    }

    @RequestMapping("resetDraw/{idnum}")
    public @ResponseBody
    JSONObject resetDraw(@PathVariable String idnum) throws Exception{
        try {
            securityCertificateDao.resetDraw(idnum,null);
            return ManageResultUtil.returnSuccessJson("操作成功","visaList","refreshCurrent", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","visaList", "closeCurrent", "");
        }
    }

    /**
     * 批量操作将资格证信息推送给saas页面
     * @return
     */
    @RequestMapping("batch")
    public ModelAndView batchInit() {
        ModelAndView view = new ModelAndView("/manage/security/batch");
        return view;
    }




    /**
     * 批量操作将资格证信息推送给saas
     * @param idNums
     * @return
     */
    @RequestMapping("batchOperation")
    @ResponseBody
    public JSONObject batchOperation(String idNums) {
        try {
            Config config = configUtils.getConfigByKey("approvalflag");
            if (config != null && config.getValue().equals("1")) {
                config.setValue("0");
                configUtils.updateForKey(config);
                try {
                    if (StringUtil.isNotEmpty(idNums)) {
                        idNums = idNums.replaceAll("\r\n", ",");
                        idNums = idNums.replaceAll("\n", ",");
                        String[] idNumArr = idNums.split(",");
                        if (idNumArr != null && idNumArr.length > 0) {
                            for (String idNum : idNumArr) {
                                try {
                                    if (StringUtil.isNotEmpty(idNum)) {
                                        SecurityCertificate certificate = securityCertificateDao.findByIdnum(idNum);
                                        if(certificate != null) {
                                            updateSecurityPersonCertificateInfo(certificate);
                                        }
                                    }
                                } catch (Exception e) {
                                    logger.error(e.getMessage(),e);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    return ManageResultUtil.returnFailedJson("操作失败","personcertificateList", "closeCurrent", "");
                }
            } else {
                return ManageResultUtil.returnFailedJson("请勿重复操作","personcertificateList", "closeCurrent", "");
            }
            return ManageResultUtil.returnSuccessJson("操作成功","personcertificateList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","personcertificateList", "closeCurrent", "");
        }
    }


    /**
     * 批量操作将等级证信息推送给saas
     * @param idNums
     * @return
     */
    @RequestMapping("batchGradeOperation")
    @ResponseBody
    public JSONObject batchGradeOperation(String idNums) {
        try {
            Config config = configUtils.getConfigByKey("approvalflag");
            if (config != null && config.getValue().equals("1")) {
                config.setValue("0");
                configUtils.updateForKey(config);
                try {
                    if (StringUtil.isNotEmpty(idNums)) {
                        idNums = idNums.replaceAll("\r\n", ",");
                        idNums = idNums.replaceAll("\n", ",");
                        String[] idNumArr = idNums.split(",");
                        if (idNumArr != null && idNumArr.length > 0) {

                            List<GradeCertificate> certificateList = gradeCertificateService.findByIdNums(idNumArr);
                            if (certificateList != null && certificateList.size() > 0) {
                                List<GradeCertificateToSAASDto> dtoList = new ArrayList<>();
                                for (GradeCertificate gradeCertificate : certificateList) {
                                    GradeCertificateToSAASDto certificateDto = new GradeCertificateToSAASDto();
                                    certificateDto.setPerId(gradeCertificate.getPersonId());
                                    certificateDto.setCerNo(gradeCertificate.getCertificateNo());
                                    certificateDto.setPerCerLevel("0100010" + gradeCertificate.getAppraisalGrade());
                                    certificateDto.setLicenceDate(gradeCertificate.getAppraisalTime() == null ? "" : DateUtil.convertDateToString(gradeCertificate.getAppraisalTime(), DateUtil.FORMAT2));
                                    certificateDto.setTrainOrganName(gradeCertificate.getTrainOrgName());
                                    dtoList.add(certificateDto);
                                }

                                Map<String, Object> paramMap = new HashMap();
                                paramMap.put("bayDJZListStr", JSONArray.toJSONString(dtoList));

                                AjaxResult result = saasInterfaceUtil.callInterface(Constants.SAAS_GRADECERTIFICATE_URL, paramMap);

                                if (!result.isSuccessful()) {
                                    throw new ArsException("保安员等级证推送saas失败" + result.getMsg());
                                }

                                Map<Long, GradeCertificateToSAASDto> failMap = new HashMap();

                                if (result.getData() != null) {
                                    List<GradeCertificateToSAASDto> failList = JSONArray.parseArray(JSONArray.toJSONString(result.getData()), GradeCertificateToSAASDto.class);
                                    failMap = failList.stream().collect(Collectors.toMap(GradeCertificateToSAASDto::getPerId, Function.identity()));
                                }

                                List<GradeCertificate> successList = new ArrayList<>();
                                for (GradeCertificate gradeCertificate : certificateList) {
                                    if (failMap.get(gradeCertificate.getPersonId()) == null) {
                                        successList.add(gradeCertificate);
                                    }
                                }
                                /*判断是否有更新*/
                                if (successList.size() > 0) {
                                    //批量更新推送状态
                                    gradeCertificateService.batchUpdatePushState(successList);
                                    //批量更新人员等级证信息
                                    gradeCertificateService.batchUpdatePersonGradeCertificate(successList);
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    return ManageResultUtil.returnFailedJson("操作失败","personcertificateList", "closeCurrent", "");
                }
            } else {
                return ManageResultUtil.returnFailedJson("请勿重复操作","personcertificateList", "closeCurrent", "");
            }
            return ManageResultUtil.returnSuccessJson("操作成功","personcertificateList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","personcertificateList", "closeCurrent", "");
        }
    }

    /**
     * 批量操作将等级证信息推送给saas页面
     * @return
     */
    @RequestMapping("batchGrade")
    public ModelAndView batchGradeInit() {
        ModelAndView view = new ModelAndView("/manage/security/batchGrade");
        return view;
    }













    /**
     * 保安员资格申报审批通过生成证书同步保安员表
     * @param detail 保安员证书信息
     */
    private void updateSecurityPersonCertificateInfo(SecurityCertificate detail){
        //证书信息同步到保安人员
        PersonInfoDto personDto = new PersonInfoDto();
        Personcertificate personcertificate = personcertificateService.findById(detail.getSecuritypersonid());

        if(personcertificate == null){
            return;
        }

        if(personcertificate.getPersonid() == null) {
            SecurityPerson securityPerson = securityPersonDao.findByIdCard(personcertificate.getCardnumber());

            securityPerson.setZgcredential(detail.getZsbh());
            securityPerson.setZgcertificatejgno(detail.getFzjgbh());
            securityPerson.setZgcertificatejgname(detail.getFzjgmc());
            securityPerson.setZgcertificatejgtime(detail.getFzrq()==null?"":DateUtil.convertDateToString(detail.getFzrq(),"yyyy-MM-dd"));
            securityPerson.setUpdateTime(new Date());
            securityPersonDao.update(securityPerson);

            personcertificate.setPersonid(securityPerson.getId());
        }

        if(StringUtil.isNotEmpty(personcertificate.getTrainOrgName())){
            personDto.setTrainOrganName(personcertificate.getTrainOrgName());
        }

        personDto.setIsOldData(StringUtil.isEmpty(detail.getIsOldData()) ?"0":detail.getIsOldData());
        personDto.setPerId(personcertificate.getPersonid());
        personDto.setCerNo(detail.getZsbh());
        personDto.setLicenceOrgNo(detail.getFzjgbh());
        personDto.setLicenceOrg(detail.getFzjgmc());
        personDto.setLicenceDate(detail.getFzrq()==null?"":DateUtil.convertDateToString(detail.getFzrq(),"yyyy-MM-dd"));

        Config policeConfig = configUtils.getConfigByKey(Constants.POLICE);
        if (policeConfig.getValue().equals(Constants.POLICE_OUT)) {
            //电子证书
            try {
                if(detail.getSnapshotId() == null) {
                    String data = DES3.encode(JSON.toJSONString(detail.getSecuritypersonid(), SerializerFeature.WriteDateUseDateFormat));
                    Config config = configUtils.getConfigByKey("current_province");
                    if (null != config) {
                        Config H5UrlConfig = configUtils.getConfigByKey("H5URL" + config.getValue());
                        if (null != H5UrlConfig) {
                            personDto.setElectronCerUrl(bbdH5Url.replace("/#/", "/$$/") + Constants.SELECT_CARD_URL + URLEncoder.encode(data, "utf-8") + H5UrlConfig.getValue());
                        }
                    }
                }else {
                    personDto.setElectronCerUrl(securityCertificateService.getElectronCerUrl(DES3.encode(detail.getSnapshotId().toString())));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            //将保安员证书信息推送给SaaS
            AjaxResult result = saasInterfaceUtil.callInterface(Constants.SAAS_SECURITYCERTIFICATE_UPDATE, personDto);
            if(!result.isSuccessful()){
                throw new ArsException(detail.getXm() + result.getMsg() );
            }
        }

    }

    @RequestMapping("visaInit")
    public ModelAndView visaInit() {
        ModelAndView view = new ModelAndView("/manage/security/visaList");
        return view;
    }

}
