
package com.yeejoin.amos.patrol.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dao.ESPlanTaskList;
import com.yeejoin.amos.boot.module.common.api.dao.ESTaskDetail;
import com.yeejoin.amos.boot.module.common.api.dto.ESPlanTaskListDto;
import com.yeejoin.amos.boot.module.common.api.dto.ESTaskDetailDto;
import com.yeejoin.amos.boot.module.common.api.dto.PlanTaskDetailDto;
import com.yeejoin.amos.patrol.dao.entity.PlanTaskDetail;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.MessageModel;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.dao.mapper.*;
import com.yeejoin.amos.patrol.business.dao.repository.*;
import com.yeejoin.amos.patrol.business.dto.CheckDto;
import com.yeejoin.amos.patrol.business.entity.mybatis.*;
import com.yeejoin.amos.patrol.business.feign.IdxFeign;
import com.yeejoin.amos.patrol.business.feign.JcsFeignClient;
import com.yeejoin.amos.patrol.business.param.*;
import com.yeejoin.amos.patrol.business.service.intfc.ICheckService;
import com.yeejoin.amos.patrol.business.service.intfc.IEquipmentHandlerService;
import com.yeejoin.amos.patrol.business.service.intfc.IPatrolDataSyncService;
import com.yeejoin.amos.patrol.business.service.intfc.IPointService;
import com.yeejoin.amos.patrol.business.util.CheckDetailInputPageParam;
import com.yeejoin.amos.patrol.business.util.Toke;
import com.yeejoin.amos.patrol.business.vo.CheckAnalysisVo;
import com.yeejoin.amos.patrol.business.vo.CheckInfoVo;
import com.yeejoin.amos.patrol.business.vo.DefectVo;
import com.yeejoin.amos.patrol.common.enums.*;
import com.yeejoin.amos.patrol.core.common.response.*;
import com.yeejoin.amos.patrol.core.util.DateUtil;
import com.yeejoin.amos.patrol.core.util.StringUtil;
import com.yeejoin.amos.patrol.dao.entity.*;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;
import com.yeejoin.amos.patrol.quartz.IJobService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service("checkService")
public class CheckServiceImpl implements ICheckService {

    @Autowired
    private CheckMapper checkMapper;

    @Autowired
    private ICheckService checkService;
   @Autowired
   private IPointService iPointService;

    @Autowired
    private ICatalogTreeDao catalogTreeDao;
    @Resource
    ICheckShotDao checkShotDao;
    @Resource
    IPlanTaskDao planTaskDao;
    @Autowired
    PlanTaskMapper planTaskMapper;
    @Autowired
    JcsFeignClient jcsFeignClient;

    @Autowired
    IInputItemDao inputItemDao;
    @Autowired
    ICheckInputDao checkInputDao;
    @Autowired
    ICheckDao checkDao;
    @Autowired
    PlanTaskDetailMapper planTaskDetailMapper;
    @Autowired
    IPlanTaskDetailDao planTaskDetailDao;
    @Autowired
    private RemoteSecurityService remoteSecurityService;
    @Autowired
    RouteMapper routeMapper;
    @Autowired
    IEquipmentHandlerService equipmentHandlerService;

    @Autowired
    IJobService jobService;

    @Autowired
    private IPointClassifyDao iPointClassifyDao;

    @Autowired
    private PlanServiceImpl planService;

    @Autowired
    private IPatrolDataSyncService patrolDataSyncService;

    @Autowired
    private CheckInputMapper checkInputMapper;

    @Autowired
    ESTaskDetail esTaskDetail;

    @Autowired
    ESPlanTaskList esPlanTaskList;

    @Autowired
    PointMapper pointMapper;

    @Autowired
    private IdxFeign idxFeign;

    private String P_STATIC_DAY = "p_static_day";

    private String P_STATIC_MONTH = "p_static_month";

    private String P_STATIC_WEEK = "p_static_week";

    @PersistenceContext
    private final EntityManager em;

    public CheckServiceImpl(EntityManager em) {
        this.em = em;
    }

    public static final Logger log = LoggerFactory.getLogger(CheckServiceImpl.class);

    @Override
    public Page<CheckInfoVo> getCheckInfo(String toke,String product,String appKey,CheckInfoPageParam param) {
    	 long total = checkMapper.getCheckInfoCount(param);
         List<CheckInfoVo> content = Lists.newArrayList();
         if (total == 0) {
             return new PageImpl<>(content, param, total);
         }
         content = checkMapper.getCheckInfo(param);
         if (!CollectionUtils.isEmpty(content)) {
             Set<String> userIds = Sets.newHashSet(Lists.transform(content, CheckInfoVo::getUserId));

             Set<String> deptIds = Sets.newHashSet(Lists.transform(content, CheckInfoVo::getDepId));
             deptIds.remove("");
             deptIds.remove(null);
             String joinUserId="";
             for (String userId:userIds) {
                 if(!ObjectUtils.isEmpty(userId)){
                     joinUserId=joinUserId+userId+",";
                 }
             }
    //         List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds( toke, product, appKey,joinUserId);
             Map<String, String> deptMap =  new HashMap<String,String>();
//             if(!CollectionUtils.isEmpty(deptIds)){
//                 List<LinkedHashMap> deptList = remoteSecurityService.listDepartmentByDeptIds( toke, product, appKey,Joiner.on(",").join(deptIds));
//                 //deptMap = deptList.stream().collect(Collectors.toMap(DepartmentModel::getSequenceNbr, DepartmentModel::getDepartmentName));
//
//                 for (int i = 0; i < deptList.size(); i++) {
//                 	deptMap.put(deptList.get(i).get("sequenceNbr").toString(), deptList.get(i).get("departmentName").toString());
//     			}
//
//
//             }
         //    Map<String,String> userModelMap = userModels.stream().collect(Collectors.toMap(AgencyUserModel::getUserId,AgencyUserModel::getRealName ,(k1,k2)->k2));
             Map<String, String> deptMapNew= deptMap;
             List<String> userNames = new ArrayList<>();

         }
		return new PageImpl<>(content, param, total);
    }

    public Page<CheckInfoVo> getCheckInfoNew(String toke,String product,String appKey,CheckInfoPageParam param) {
        long total = checkMapper.getCheckInfoCount(param);
        List<CheckInfoVo> content = Lists.newArrayList();
        if (total == 0) {
            return new PageImpl<>(content, param, total);
        }
        content = checkMapper.getCheckInfoNew(param);
        return new PageImpl<>(content, param, total);
    }

    public Page<CheckInfoVo> getPeoplePatrolPage(CheckInfoPageParam param) {
        long total = checkMapper.getPeoplePageCount(param);
        List<CheckInfoVo> content = Lists.newArrayList();
        if (total == 0) {
            return new PageImpl<>(content, param, total);
        }
        content = checkMapper.getPeopleCheckPage(param);
        for (CheckInfoVo infoVo : content) {
            FeignClientResult responseModel = new FeignClientResult();
            List result = new ArrayList();
            try {
                responseModel = idxFeign.queryDefectByCodes(new ArrayList<>(), infoVo.getId());
                result = (List) responseModel.getResult();
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<DefectVo> res = new ArrayList();
            if (result != null && 0 < result.size()) {
                for(Object object : result) {
                    DefectVo vo = JSON.parseObject(JSON.toJSONString(object), DefectVo.class);
                    res.add(vo);
                }
                infoVo.setError(ObjectUtils.isEmpty(res.get(0)) ? "" : res.get(0).getDefectDescribe());
                infoVo.setProblemNum(ObjectUtils.isEmpty(res.get(0)) ? "" : res.get(0).getDefectNum());
                infoVo.setHandleStatus(ObjectUtils.isEmpty(res.get(0)) ? "" : String.valueOf(res.get(0).getDefectStatus()));
            }
        }
        return new PageImpl<>(content, param, total);
    }

    @Override
    @Transactional
    public void saveCheckImg(List<CheckShot> imgList) {
        Check check = checkDao.findById(imgList.get(0).getCheckId()).get();
        check.setShotNumber(check.getShotNumber() + imgList.size());
        checkDao.saveAndFlush(check);
        for (CheckShot cs: imgList
             ) {
            em.persist(cs);
            em.flush();
            em.clear();
        }
    }

    @Override
    @Transactional
    public CheckDto saveCheckRecord(CheckRecordParam requestParam, AgencyUserModel user, DepartmentBo departmentModel, Toke token) {
        PlanTaskDetail taskDetail = null;
        PlanTask planTask = null;
        Check check = new Check();


        HashMap<String, Object> routeParam = new HashMap<String, Object>();
        Map detail = null;
        Boolean isOffline = requestParam.getIsOffline();
        Point point = iPointService.queryPointById(requestParam.getPointId());
        try {
            if (!ObjectUtils.isEmpty(requestParam) && !ObjectUtils.isEmpty(requestParam.getPlanTaskId()) && requestParam.getPlanTaskId() > 0) {
                detail = planTaskDetailMapper.findPlanTaskByTaskIdAndPointId(requestParam.getPlanTaskId(), requestParam.getPointId());
                if (!ObjectUtils.isEmpty(detail)) {
                    check = checkDao.findByPlanTaskIdAndPointId(requestParam.getPlanTaskId(), requestParam.getPointId());
                    planTask = planTaskDao.findById(requestParam.getPlanTaskId()).get();
                    routeParam.put("routeId", planTask.getRouteId());
                    routeParam.put("pointId", requestParam.getPointId());

                    if (ObjectUtils.isEmpty(check)) {
                        check = new Check();
                    }
                    check.setPlanTaskDetailId(Long.parseLong(detail.get("planTaskDetailId").toString()));
                    check.setRouteId(Long.parseLong(detail.get("routeId").toString()));
                    check.setRouteName(detail.get("routeName").toString());
                    check.setPlanTaskId(requestParam.getPlanTaskId());
                    check.setPlanId(planTask.getPlanId());
                    check.setPlanName(detail.get("planName").toString());
                    check.setPointName(detail.get("pointName").toString());
                    requestParam.setPointName(detail.get("pointName").toString());
                }
            } else {
                taskDetail = new PlanTaskDetail();
                planTask = new PlanTask();
                check.setPlanTaskDetailId(0);
                check.setRouteId(0);
                check.setPlanTaskId(0);
                check.setPlanId(0);
            }

            check.setPointId(requestParam.getPointId());
            if(ObjectUtils.isEmpty(requestParam.getPointName())){
            	check.setPointName(point==null?"":point.getName());
            }
            check.setRemark(requestParam.getRemark());
            check.setCheckTime(DateUtil.getLongDate(requestParam.getCheckTime()));
            check.setUploadTime(new Date());
            check.setOrgCode(requestParam.getOrgCode());
            check.setUserId(user.getUserId());
            check.setUserName(user.getRealName());
            if (departmentModel != null && departmentModel.getSequenceNbr() != null) {
                check.setDepId(departmentModel.getSequenceNbr().toString());
            }
            if (departmentModel != null) {
                check.setDepName(departmentModel.getDepartmentName());
            }
            check.setCheckMode(requestParam.getCheckMode());

            List<CheckInputParam> list = requestParam.getCheckItems();
            List<CheckInput> checkItemList = new ArrayList<>();
            List<Map<String, Object>> unqualifiedcheckItemList = Lists.newArrayList();
            String error = "";
            HashMap<String, String> errorClassifyNames = new HashMap<>();
            List<EquipmentInputItemRo> equipmentInputItemRoList = new ArrayList<>();
            int score = 0;
            for (CheckInputParam item : list) {
                String pointClassifyName = null;
                PointClassify pointClassify= null;
                if (StringUtil.isNotEmpty(item.getClassifyIds()) && iPointClassifyDao.existsById(item.getClassifyIds())) {
                    pointClassify = iPointClassifyDao.findById(item.getClassifyIds()).get();
                    pointClassifyName = pointClassify.getName();
                }
                InputItem inputItem = inputItemDao.findById(item.getInputItemId()).get();
                CheckInput checkInput = new CheckInput();
                if (isOffline && check.getId() != 0) {
                    checkInput = checkInputDao.findByCheckIdAndInputIdAndPointClassifyId(check.getId(), inputItem.getId(), item.getClassifyIds());
                }
                checkInput.setCreateDate(new Date());
                checkInput.setOrgCode(requestParam.getOrgCode());
                checkInput.setInputId(Long.valueOf(item.getInputItemId() + ""));
                checkInput.setInputName(inputItem.getName());
                checkInput.setOrderNo(inputItem.getOrderNo());
                checkInput.setRemark(item.getRemark());
                //1.校验结果

                if (XJConstant.INPUT_ITEM_SELECT.equals(inputItem.getItemType())) {
                    checkInput = paraseSelect(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                } else if (XJConstant.INPUT_ITEM_NUMBER.equals(inputItem.getItemType())) {
                    checkInput = paraseNumber(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                } else if (XJConstant.INPUT_ITEM_TEXT.equals(inputItem.getItemType())) {
                    checkInput = paraseText(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                }
                if(XJConstant.RISK.equals(checkInput.getInputValue())) {
                    planTask.setRiskStatus(XJConstant.RISK_NUM);
                }
                if (XJConstant.NO.equals(checkInput.getIsOk())) {
                    String classifyName = pointClassifyName != null ? pointClassifyName + "-" : "";
                    error += (classifyName + inputItem.getName() + "=" + (ObjectUtils.isEmpty(item.getInputValue()) ? "" : item.getInputValue()) + ";");
                    errorClassifyNames.put(pointClassifyName != null ? pointClassifyName : "", "");
                    checkInput.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
                    Map<String, Object> unCheckMap = Maps.newHashMap();
                    unCheckMap.put("itemId", item.getInputItemId());
                    unCheckMap.put("routeId", check.getRouteId());
                    unCheckMap.put("pointId", requestParam.getPointId());
                    unCheckMap.put("name", inputItem.getName());
                    unCheckMap.put("inputValue", item.getInputValue());
                    unqualifiedcheckItemList.add(unCheckMap);
                } else {
                    checkInput.setIsOk(CheckStatusEnum.QUALIFIED.getCode());
                }
                checkInput.setRoutePointItemId(item.getRoutePointItemId());
                checkInput.setInputValue(item.getInputValue());
                checkInput.setPointClassifyId(item.getClassifyIds());
                checkInput.setPointClassifyName(pointClassifyName);
                score += checkInput.getScore();
                checkItemList.add(checkInput);
                EquipmentInputItemRo equipmentInputItemRo = new EquipmentInputItemRo();
                if(!StringUtils.isBlank(pointClassify.getName())){
                    equipmentInputItemRo.setEquipmentName(pointClassify.getName());
                }
                equipmentInputItemRo.setCheckResult(item.getInputValue());
                equipmentInputItemRo.setRuleType(RuleTypeEnum.CHECKRESULT.getCode());
                equipmentInputItemRo.setCheckContent(inputItem.getItemNo());
                if(!StringUtils.isBlank(pointClassify.getEquipmentId())){
                    equipmentInputItemRoList.add(equipmentInputItemRo);
                }
            }

            if(ObjectUtils.isEmpty(planTask.getRiskStatus())) {
                planTask.setRiskStatus(XJConstant.NORISK_NUM);
            }
            planTaskDao.saveAndFlush(planTask);
            if (!ObjectUtils.isEmpty(error) && error.endsWith(";")) {
                error.substring(0, error.length() - 1);
                check.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
            } else {
                check.setIsOk(CheckStatusEnum.QUALIFIED.getCode());
            }
            check.setError(error);
            check.setErrorClassify(StringUtils.join(errorClassifyNames.keySet(), ","));
            //计划外巡检是否计分 ，计划内默认都是计分
            if(XJConstant.POINT_OK_SCORE.equals(point.getIsScore()) || requestParam.getPlanTaskId()!=null ){
                check.setScore(score);
            }else{
                check.setScore(Integer.parseInt(XJConstant.POINT_NOT_SCORE));
            }
            check = checkDao.save(check);
            List<CheckShot> imgList = new ArrayList<>();
            for (CheckInput item : checkItemList) {
                item.setCheckId(check.getId());
                //检查点图片保存 checkInputId
                Check finalCheck = check;
                list.forEach(x->{
                 if(x.getInputItemId()==item.getInputId()&&(x.getClassifyIds()==item.getPointClassifyId()||x.getClassifyIds()==null)){
                    if(x.getCheckInputImg()!=null && x.getCheckInputImg().size()>0){
                        for (int i = 0; i <x.getCheckInputImg().size() ; i++) {
                            CheckShot img = new CheckShot();
                            img.setCheckId(finalCheck.getId());
                            img.setOrgCode(finalCheck.getOrgCode());
                            img.setCreateDate(new Date());
                            img.setPointName(finalCheck.getPointName());
                            img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通");
                            img.setPhotoData(x.getCheckInputImg().get(i));
                            img.setCheckInputId(x.getInputItemId());
                            if(item.getPointClassifyId()==null){
                                img.setClassifyId(0);
                            }else{
                                img.setClassifyId(item.getPointClassifyId());
                            }
                            imgList.add(img);
                        }
                    }
                 } });
            }
            //现场图片保存
            if(requestParam.getCheckRecordImg()!=null&&requestParam.getCheckRecordImg().size()>0){
                for (int i = 0; i <requestParam.getCheckRecordImg().size() ; i++) {
                    CheckShot img = new CheckShot();
                    img.setCheckId(check.getId());
                    img.setOrgCode(check.getOrgCode());
                    img.setCreateDate(new Date());
                    img.setPointName(check.getPointName());
                    img.setCheckInputId(0);
                    img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通");
                    img.setPhotoData(requestParam.getCheckRecordImg().get(i));
                    img.setClassifyId(0);
                    imgList.add(img);
                }
            }
            List<CheckInput> checkInputList = checkInputDao.saveAll(checkItemList);
            //规则请求结果
            checkInputList.forEach(checkInput -> {
                InputItem inputItem = inputItemDao.findById(checkInput.getInputId()).get();
                for (int i = 0; i <equipmentInputItemRoList.size() ; i++) {
                    if(inputItem.getItemNo().equals(equipmentInputItemRoList.get(i).getCheckContent())){
                        equipmentInputItemRoList.get(i).setCheckInputId(Long.valueOf(checkInput.getId()).toString());
                    }
                }

            });
            equipmentHandlerService.getRulesCheckResult(equipmentInputItemRoList,token);
            if(imgList.size()>0){
                checkService.saveCheckImg(imgList);
            }
            if (check.getPlanTaskId() > 0) {
                planTaskDetailMapper.finishTaskDetail(Long.parseLong(detail.get("planTaskDetailId").toString()), requestParam.getPointId(), requestParam.getPlanTaskId(), user.getUserId());
            }

//            if(check.getPlanId()!=0){
//                // 任务完成、同步修改待办任务状态
//                Plan plan = planService.queryPlanById(check.getPlanId());
//                if (!ObjectUtils.isEmpty(plan) && plan.getIsSingleExecution()){
//                    // 单人执行
//                    updateTaskStatus(plan.getId(), user.getUserId());
//                }else {
//                    // 多人执行
//                    updateTaskStatus(plan.getId(), null);
//                }
//            }
            //  巡检站端与中心级数据同步
//            Check finalCheck1 = check;
//            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
//                @Override
//                public void afterCommit() {
//                    // 事物提交后业务逻辑
//                    patrolDataSyncService.checkDataSync(finalCheck1);
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("idList", checkInputList.stream().map(CheckInput::getId).collect(Collectors.toList()));
//                    List<CheckInputSyncBo> checkInputSyncBoList = checkInputMapper.getCheckInputSyncBoList(map);
//                    patrolDataSyncService.checkInputBoDataSync(checkInputSyncBoList);
//                    patrolDataSyncService.checkInputDataSync(checkInputList);
//                }
//            });
            return new CheckDto(check.getId(), unqualifiedcheckItemList);
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }


    @Override
    @Transactional
    public CheckDto saveCheckRecordNew(CheckRecordParam requestParam , PlanTask planTask) {
        try {
            PlanTaskDetail taskDetail = null;
            Check check = new Check();


            HashMap<String, Object> routeParam = new HashMap<String, Object>();
            Map detail = null;
            Point point = iPointService.queryPointById(requestParam.getPointId());

            if (!ObjectUtils.isEmpty(requestParam) &&
                    !ObjectUtils.isEmpty(requestParam.getPlanTaskId())
                    && requestParam.getPlanTaskId() > 0) {
                detail = planTaskDetailMapper.findPlanTaskByTaskIdAndPointId(requestParam.getPlanTaskId(), requestParam.getPointId());
                if (!ObjectUtils.isEmpty(detail)) {
                    Optional<PlanTaskDetail> planD = planTaskDetailDao.findById(Long.valueOf(detail.get("id").toString()));
                    taskDetail = planD.get();
                    routeParam.put("routeId", planTask.getRouteId());
                    routeParam.put("pointId", requestParam.getPointId());

                    check.setPlanTaskDetailId(Long.parseLong(detail.get("planTaskDetailId").toString()));
                    check.setRouteId(Long.parseLong(detail.get("routeId").toString()));
                    check.setRouteName(detail.get("routeName").toString());
                    check.setPlanTaskId(requestParam.getPlanTaskId());
                    check.setPlanId(planTask.getPlanId());
                    check.setPlanName(detail.get("planName").toString());
                    check.setPointName(detail.get("pointName").toString());
                    requestParam.setPointName(detail.get("pointName").toString());
                }
            } else {
                taskDetail = new PlanTaskDetail();
                planTask = new PlanTask();
                check.setPlanTaskDetailId(0);
                check.setRouteId(0);
                check.setPlanTaskId(0);
                check.setPlanId(0);
            }

            check.setPointId(requestParam.getPointId());
            if (ObjectUtils.isEmpty(requestParam.getPointName())) {
                check.setPointName(point == null ? "" : point.getName());
            }
            check.setRemark(requestParam.getRemark());
            check.setCheckTime(DateUtil.getLongDate(requestParam.getCheckTime()));
            check.setUploadTime(new Date());
            check.setOrgCode(planTask.getOrgCode());
            check.setUserId(planTask.getUserId());

            StringBuffer deptName = new StringBuffer();
            if(planTask.getUserDept().indexOf(",") > 0) {
                List<String> depts = Arrays.asList(planTask.getUserDept().split(","));
                depts.forEach(dept -> {
                    deptName.append(dept.split("@")[2]).append(",");
                });

                check.setDepName(deptName.substring(0,deptName.length() - 1));
            }

            check.setUserName(requestParam.getUserName());

//            check.setCheckMode(requestParam.getCheckMode());

            List<CheckInputParam> list = requestParam.getCheckItems();
            List<CheckInput> checkItemList = new ArrayList<>();
            List<Map<String, Object>> unqualifiedcheckItemList = Lists.newArrayList();
            String error = "";
           // HashMap<String, String> errorClassifyNames = new HashMap<>();
            int score = 0;
            for (CheckInputParam item : list) {
//                String pointClassifyName = null;
//                PointClassify pointClassify = null;
//                if (StringUtil.isNotEmpty(item.getClassifyIds()) && iPointClassifyDao.existsById(item.getClassifyIds())) {
//                    pointClassify = iPointClassifyDao.findById(item.getClassifyIds()).get();
//                    pointClassifyName = pointClassify.getName();
//                }
                InputItem inputItem = inputItemDao.findById(item.getInputItemId()).get();
                CheckInput checkInput = new CheckInput();

                checkInput.setCreateDate(new Date());
                checkInput.setOrgCode(planTask.getOrgCode());
                checkInput.setInputId(Long.valueOf(item.getInputItemId() + ""));
                checkInput.setInputName(inputItem.getName());
                checkInput.setOrderNo(inputItem.getOrderNo());
                checkInput.setRemark(item.getRemark());

                //1.校验结果
                checkInput =  setInputValueByItemType(checkInput,inputItem.getDataJson(),inputItem.getItemType(),item,inputItem.getIsScore());

                if (XJConstant.INPUT_ITEM_SELECT.equals(inputItem.getItemType())) {
                    checkInput = paraseSelect(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                } else if (XJConstant.INPUT_ITEM_NUMBER.equals(inputItem.getItemType())) {
                    checkInput = paraseNumber(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                } else if (XJConstant.INPUT_ITEM_TEXT.equals(inputItem.getItemType())) {
                    checkInput = paraseText(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                }

                if (XJConstant.NO.equals(checkInput.getIsOk())) {
                   // String classifyName = pointClassifyName != null ? pointClassifyName + "-" : "";
                    error += ( inputItem.getName() + "=" + (ObjectUtils.isEmpty(item.getInputValue()) ? "" : item.getInputValue()) + ";");
                    // errorClassifyNames.put(pointClassifyName != null ? pointClassifyName : "", "");
                    checkInput.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
                    Map<String, Object> unCheckMap = Maps.newHashMap();
                    unCheckMap.put("itemId", item.getInputItemId());
                    unCheckMap.put("routeId", check.getRouteId());
                    unCheckMap.put("pointId", requestParam.getPointId());
                    unCheckMap.put("name", inputItem.getName());
                    unCheckMap.put("inputValue", item.getInputValue());
                    unqualifiedcheckItemList.add(unCheckMap);
                    planTask.setRiskStatus(XJConstant.RISK_NUM);
                } else {
                    checkInput.setIsOk(CheckStatusEnum.QUALIFIED.getCode());
                }

                checkInput.setRoutePointItemId(item.getRoutePointItemId());
                checkInput.setInputValue(item.getInputValue());
                checkInput.setPointClassifyId(item.getClassifyIds());
                // checkInput.setPointClassifyName(pointClassifyName);
                score += checkInput.getScore();
                checkItemList.add(checkInput);
            }
            if(ObjectUtils.isEmpty(planTask.getRiskStatus()) || planTask.getRiskStatus() == XJConstant.INIT_NUM) {
                planTask.setRiskStatus(XJConstant.NORISK_NUM);
            }
            planTaskDao.saveAndFlush(planTask);
            if (!ObjectUtils.isEmpty(error) && error.endsWith(";")) {
                error.substring(0, error.length() - 1);
                check.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
                taskDetail.setStatus(CheckStatusEnum.UNQUALIFIED.getCode());
            } else {
                check.setIsOk(CheckStatusEnum.QUALIFIED.getCode());
                taskDetail.setStatus(CheckStatusEnum.QUALIFIED.getCode());
            }
            planTaskDetailDao.saveAndFlush(taskDetail);
//            ESTaskDetailDto esTaskDetailDto = esTaskDetail.findById(String.valueOf(taskDetail.getId())).get();
//            esTaskDetailDto.setPointStatus(String.valueOf(taskDetail.getIsFinish()));
//            JSONObject appCheckInput = esTaskDetailDto.getAppCheckInput();
//            List<CheckInputParam> checkItems = requestParam.getCheckItems();
//            Map<String,List<Map<String,Object>>> mapList = (Map<String,List<Map<String,Object>>>)JSON.parse(appCheckInput.toJSONString());
//
//            List<AppCheckInputRespone> appCheckInputRespones = new ArrayList<>();
//
//            for (Map<String,Object> map : mapList.get("items")) {
//                AppCheckInputRespone appCheckInputRespone = new AppCheckInputRespone();
//                CheckInputParam checkInputId = checkItems.stream().filter(x -> x.getInputItemId()== Long.valueOf(map.get("checkInputId").toString())).collect(Collectors.toList()).get(0);
//                BeanUtils.copyProperties(appCheckInputRespone, map);
//                appCheckInputRespone.setInputValue(checkInputId.getInputValue());
//                appCheckInputRespone.setPointInputImgUrls(ObjectUtils.isEmpty(checkInputId) ? new ArrayList<>() : checkInputId.getCheckInputImg());
//                appCheckInputRespones.add(appCheckInputRespone);
//            }
//            appCheckInput.put("items", appCheckInputRespones);
//            esTaskDetailDto.setPointImgUrls(requestParam.getCheckRecordImg());
//            esTaskDetailDto.setAppCheckInput(appCheckInput);
//            esTaskDetail.save(esTaskDetailDto);

            check.setError(error);
            // check.setErrorClassify(StringUtils.join(errorClassifyNames.keySet(), ","));

            try {
                log.error("手机app保存巡检记录++++++++++++++++++++++" + check.toString() + "<Over><Over><Over><Over>");
                check = checkDao.saveAndFlush(check);
            } catch (Exception e) {
                e.printStackTrace();

            }

            List<CheckShot> imgList = new ArrayList<>();

            for (CheckInput item : checkItemList) {
                item.setCheckId(check.getId());
                //检查点图片保存 checkInputId
                Check finalCheck = check;
                list.forEach(x -> {
                    if (x.getInputItemId() == item.getInputId() && (x.getClassifyIds() == item.getPointClassifyId() || x.getClassifyIds() == null)) {
                        if (x.getCheckInputImg() != null && x.getCheckInputImg().size() > 0) {
                            for (int i = 0; i < x.getCheckInputImg().size(); i++) {
                                CheckShot img = new CheckShot();
                                img.setCheckId(finalCheck.getId());
                                img.setOrgCode(finalCheck.getOrgCode());
                                img.setCreateDate(new Date());
                                img.setPointName(finalCheck.getPointName());
                                img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通");
                                img.setPhotoData(x.getCheckInputImg().get(i));
                                img.setCheckInputId(x.getInputItemId());
                                if (item.getPointClassifyId() == null) {
                                    img.setClassifyId(0);
                                } else {
                                    img.setClassifyId(item.getPointClassifyId());
                                }
                                imgList.add(img);
                            }
                        }
                    }
                });
            }
            //现场图片保存
            if (requestParam.getCheckRecordImg() != null && requestParam.getCheckRecordImg().size() > 0) {
                for (int i = 0; i < requestParam.getCheckRecordImg().size(); i++) {
                    CheckShot img = new CheckShot();
                    img.setCheckId(check.getId());
                    img.setOrgCode(check.getOrgCode());
                    img.setCreateDate(new Date());
                    img.setPointName(check.getPointName());
                    img.setCheckInputId(0);
                    img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通");
                    img.setPhotoData(requestParam.getCheckRecordImg().get(i));
                    img.setClassifyId(0);
                    imgList.add(img);
                }
            }
            for (CheckInput checkInput : checkItemList) {
                em.persist(checkInput);
                em.flush();
                em.clear();
            }

            if (imgList.size() > 0) {
                checkService.saveCheckImg(imgList);
            }
            if (check.getPlanTaskId() > 0) {
                planTaskDetailMapper.finishTaskDetail(Long.parseLong(detail.get("planTaskDetailId").toString()), requestParam.getPointId(), requestParam.getPlanTaskId(), requestParam.getUserId());
                // es 操作:更新检查点的状态（完成状态、检查状态）
                Long planTaskId = planTask.getId();
                Optional<ESPlanTaskListDto>  op  = esPlanTaskList.findById(String.valueOf(planTaskId));
                if(check.getIsOk().equals(CheckStatusEnum.UNQUALIFIED.getCode())){
                    // 结果不合格时 更新统计不合格数量，小程序任务详情 环形图上方统计使用
                    op.ifPresent(esPlanTaskListDto->{
                        String ids = String.format("(%d)",planTaskId);
                        List<PlanTaskDetail> maps = planTaskMapper.selectTaskDetails(ids);
                        int unqualified = Integer.parseInt(esPlanTaskListDto.getUnqualified()) + 1;
                        esPlanTaskListDto.setUnqualified( unqualified + "");
                        esPlanTaskListDto.setPoints(this.castPlanTaskEntry2Dto(maps));
                        esPlanTaskList.save(esPlanTaskListDto);
                    });
                } else {
                    // 结果合格时 更新点的状态
                    op.ifPresent(esPlanTaskListDto->{
                        String ids = String.format("(%d)",planTaskId);
                        List<PlanTaskDetail> maps = planTaskMapper.selectTaskDetails(ids);
                        esPlanTaskListDto.setPoints(this.castPlanTaskEntry2Dto(maps));
                        esPlanTaskList.save(esPlanTaskListDto);
                    });
                }
            }
            CheckDto checkDto= new CheckDto(check.getId(), unqualifiedcheckItemList);
            return checkDto;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private List<PlanTaskDetailDto> castPlanTaskEntry2Dto(List<PlanTaskDetail> planTaskDetails) {
        return BeanUtil.copyToList(planTaskDetails, PlanTaskDetailDto.class);
    }

    private CheckInput setInputValueByItemType(CheckInput checkInput, String dataJson, String itemType, CheckInputParam item, String isScore) {

        if (XJConstant.INPUT_ITEM_SELECT.equals(itemType)) {
            checkInput = paraseSelect(checkInput, dataJson, item, isScore);
        } else if (XJConstant.INPUT_ITEM_NUMBER.equals(itemType)) {
            checkInput = paraseNumber(checkInput, dataJson, item, isScore);
        } else if (XJConstant.INPUT_ITEM_TEXT.equals(itemType)) {
            checkInput = paraseText(checkInput, dataJson, item, isScore);
        }
        return checkInput;

    }


    private void updateTaskStatus(Long id, String userId) {
        try {
            MessageModel model = new MessageModel();
            model.setRelationId(String.valueOf(id));
            model.setIsRead(true);
            model.setMsgType("patrolSystem");
            if (!ObjectUtils.isEmpty(userId)) {
                model.setUserId(userId);
            }
            Systemctl.messageClient.update(model);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    @Override
    public void delCheckById(List<Long> list) {
//        List<Long> pointIdList = checkDao.getPointIdList(list);
        checkDao.deleteBatch(list);
    }

    @Override
    public List<Map<String, Object>> selectCheckById(Long id, Long pointId) {
        return checkMapper.selectCheckById(id, pointId);
    }

    @Override
    public void delCheckByTaskId(Long id, List<Long> ids, Long pointId) {
        checkMapper.delCheckByTaskId(id, pointId);
        checkMapper.delCheckInputByCheckId(ids);
    }

    private CheckInput paraseText(CheckInput checkInput, String json, CheckInputParam item, String isScore) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        String checkType = jsonObject.getString("CheckType");
        int score = 0;
        if (XJConstant.CHECK_TYPE_ALWAYS_OK.equals(checkType)) {
            score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_OK_SCORE);
            checkInput.setIsOk(XJConstant.OK);

        } else if (XJConstant.CHECK_TYPE_ALWAYS_NO.equals(checkType)) {
            checkInput.setIsOk(XJConstant.NO);
            score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_NOT_SCORE);

        } else if (XJConstant.CHECK_TYPE_CONTEXT_OK.equals(checkType)) {
            if (!ObjectUtils.isEmpty(item.getInputValue()) && !ObjectUtils.isEmpty(item.getInputValue().trim())) {
                checkInput.setIsOk(XJConstant.OK);
                score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_OK_SCORE);
            } else {
                checkInput.setIsOk(XJConstant.NO);
                score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_NOT_SCORE);
            }
        } else if (XJConstant.CHECK_TYPE_NO_CONTEXT_OK.equals(checkType)) {
            if (!ObjectUtils.isEmpty(item.getInputValue()) && !ObjectUtils.isEmpty(item.getInputValue().trim())) {
                checkInput.setIsOk(XJConstant.NO);
                score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_NOT_SCORE);
            } else {
                checkInput.setIsOk(XJConstant.OK);
                score = jsonObject.getIntValue(XJConstant.INPUT_ITEM_OK_SCORE);
            }
        }
        if (XJConstant.YES.equals(isScore)) checkInput.setScore(score);
        return checkInput;
    }

    private CheckInput paraseNumber(CheckInput checkInput, String json, CheckInputParam item, String isScore) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        String OkUpStr = jsonObject.get("OkUp").toString();
        ;
        String OkDownStr = jsonObject.get("OkDown").toString();
        Double OkUp = StringUtil.isNotEmpty(OkUpStr) ? Double.valueOf(OkUpStr) : null;
        Double OkDown = StringUtil.isNotEmpty(OkDownStr) ? Double.valueOf(OkDownStr) : null;
        boolean CheckOkUp = jsonObject.getBoolean("CheckOkUp");
        boolean CheckOkDown = jsonObject.getBoolean("CheckOkDown");
        int OkScore = jsonObject.getIntValue("OkScore");
        int NoScore = jsonObject.getIntValue("NoScore");
        int inputValue = 0;
        int score = 0;
        String inputVal = item.getInputValue();
        if (!ObjectUtils.isEmpty(inputVal) && StringUtils.isNumeric(inputVal)) {
            inputValue = Integer.parseInt(inputVal);
        }
        if (OkUp != null && inputValue > OkUp) {
            if (CheckOkUp) {
                checkInput.setIsOk(XJConstant.NO);
                score = NoScore;
            } else {
                checkInput.setIsOk(XJConstant.OK);
                score = OkScore;
            }
        } else if (OkDown != null && inputValue < OkDown) {
            if (CheckOkDown) {
                checkInput.setIsOk(XJConstant.NO);
                score = NoScore;
            } else {
                checkInput.setIsOk(XJConstant.OK);
                score = OkScore;
            }
        } else {
            checkInput.setIsOk(XJConstant.OK);
            score = OkScore;
        }
        if (XJConstant.YES.equals(isScore)) checkInput.setScore(score);
        return checkInput;
    }

    private CheckInput paraseSelect(CheckInput checkInput, String json, CheckInputParam item, String isScore) {
        JSONArray jsonArray = JSONArray.parseArray(json);
        int score = 0;
        if (!ObjectUtils.isEmpty(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String validateName = jsonObject.getString("name");
                String validateIsOk = jsonObject.getString("isOk");
                int OkScore = 0;
                if (jsonObject.containsKey("score") && !ObjectUtils.isEmpty(jsonObject.get("score"))) {
                    OkScore = jsonObject.getIntValue("score");
                }
                if (validateName.equals(item.getInputValue())) {
                    if (validateIsOk.equals(XJConstant.YES) || validateIsOk.equals(XJConstant.OK)) {
                        checkInput.setIsOk(XJConstant.OK);
                        checkInput.setInputValue(item.getInputValue());
                    } else {
                        checkInput.setIsOk(XJConstant.NO);
                        checkInput.setInputValue(item.getInputValue());
                    }
                    score = OkScore;
                    break;
                }
            }
        }
        if (XJConstant.YES.equals(isScore)) checkInput.setScore(score);
        return checkInput;
    }

    @Override
    public List<Map> queryUnqualifiedInputItem(int checkId) {
        return checkMapper.queryUnqualifiedInputItem(checkId);
    }

    @Override
    public int checkHasRecord(CheckRecordParam requestParam) {
        return checkMapper.checkHasRecord(requestParam);
    }

    @Override
    public AppPointCheckRespone queryCheckPointDetail(String toke,String product,String appKey,long checkId) {
//		List list = checkMapper.queryCheckPointInputItem(planTaskId, pointId);
        List<PointCheckDetailBo> list = checkMapper.findCheckPointInputItem(checkId);
        AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
        if (!list.isEmpty()) {
//                InetAddress address = InetAddress.getLocalHost();
//                String ip = address.getHostAddress();
//            String ipPort = "http://" + fileIp + ":" + filePort + "/";
            List<String> pointImgUrls = new ArrayList<>();
            PointCheckDetailBo pointCheckDetailBo = list.get(0);
            List<CheckShot> pointShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), 0l,0l);
            pointShot.forEach(action -> {
//                pointImgUrls.add(fileUrl + action.getPhotoData());
                pointImgUrls.add(action.getPhotoData());
            });
            Check check = checkDao.findById(checkId).get();
            pointCheckRespone.setPointId(pointCheckDetailBo.getPointId());
            pointCheckRespone.setPointName(pointCheckDetailBo.getPointName());
            pointCheckRespone.setPointNo(pointCheckDetailBo.getPointNo());
            pointCheckRespone.setPointStatus(pointCheckDetailBo.getPointStatus());
            pointCheckRespone.setPlanName(pointCheckDetailBo.getPlanName());
            DepartmentModel departmentBo = remoteSecurityService.getDepartmentByDeptId(toke, product, appKey,pointCheckDetailBo.getCheckDepartmentId());
            if (departmentBo != null) {
                pointCheckRespone.setDepartmentName(departmentBo.getDepartmentName());
            }
            //pointCheckRespone.setDepartmentName(pointCheckDetailBo.getDepartmentName());
            List<String> userIds = Arrays.asList(pointCheckDetailBo.getUserId().split(","));
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey,pointCheckDetailBo.getUserId());
            Map<String,String> userModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName,(k1,k2)->k2));
            if (userModelMap != null) {
                List<String> userNameList = new ArrayList<>();
                for(String userId : userIds){
                    userNameList.add(userModelMap.get(userId));
                }
                userNameList.remove("");
                userNameList.remove(null);
                pointCheckRespone.setUsername(Joiner.on(",").join(userNameList));
            }
            //pointCheckRespone.setUsername(pointCheckDetailBo.getUsername());
            pointCheckRespone.setCheckTime(pointCheckDetailBo.getCheckTime());
            pointCheckRespone.setCheckId(pointCheckDetailBo.getCheckId());
            pointCheckRespone.setRemark(pointCheckDetailBo.getCheckRemark());
            pointCheckRespone.setPointImgUrls(pointImgUrls);
            pointCheckRespone.setScore(check.getScore() + "");

            JSONObject appResponeMap = new JSONObject();
            list.forEach(action -> {
                List<String> pointInputImgUrls = new ArrayList<>();
                List<CheckShot> pointInputShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), action.getCheckInputId(),action.getClassifyId());
                pointInputShot.forEach(inputShot -> {
//                    pointInputImgUrls.add(fileUrl + inputShot.getPhotoData());
                    pointInputImgUrls.add(inputShot.getPhotoData());
                });
                AppCheckInputRespone appCheckInputRespone = new AppCheckInputRespone();
                appCheckInputRespone.setCheckInputId(action.getCheckInputId());
                appCheckInputRespone.setInputName(action.getInputName());
                appCheckInputRespone.setInputStatus(action.getInputStatus());
                appCheckInputRespone.setRiskDesc(action.getRiskDesc());
                appCheckInputRespone.setInputValue(action.getInputValue());
                appCheckInputRespone.setItemType(action.getItemType());
                appCheckInputRespone.setDataJson(action.getDataJson());
                appCheckInputRespone.setIsMust(action.getIsMust());
                appCheckInputRespone.setIsMultiline(action.getIsMultiline());
                appCheckInputRespone.setPictureJson(action.getPictureJson());
                appCheckInputRespone.setOrderNo(action.getOrderNo());
                appCheckInputRespone.setPointInputImgUrls(pointInputImgUrls);
                appCheckInputRespone.setClassifyId(action.getClassifyId());
                appCheckInputRespone.setClassifyName(action.getClassifyName());
                appCheckInputRespone.setRemark(action.getRemark());

                String key = ObjectUtils.isEmpty(action.getClassifyName()) ? "其他" : action.getClassifyName();
                if (appResponeMap.containsKey(key)) {
                    appResponeMap.getJSONArray(key).add(appCheckInputRespone);
                } else {
                    List<AppCheckInputRespone> appCheckInputResponeList = new ArrayList<AppCheckInputRespone>();
                    appCheckInputResponeList.add(appCheckInputRespone);
                    appResponeMap.put(key, appCheckInputResponeList);
                }
            });
            pointCheckRespone.setAppCheckInput(appResponeMap);
            return pointCheckRespone;
        }
        return pointCheckRespone;
    }

    @Override
    public AppPointCheckRespone queryCheckPointDetailInVersion2(String toke,String product,String appKey,long checkId, Long planTaskId, Long pointId) {
        List<PointCheckDetailBo> list = checkMapper.findCheckPointInputItem(checkId);
        AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
        if (!list.isEmpty()) {
            PointCheckDetailBo planPointInfo = planTaskMapper.getPointPlanTaskInfo(planTaskId, pointId);
            List<String> pointImgUrls = new ArrayList<>();
            PointCheckDetailBo pointCheckDetailBo = list.get(0);
            List<CheckShot> pointShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), 0l,0l);
            pointShot.forEach(action -> {
                pointImgUrls.add(action.getPhotoData());
            });
            Check check = checkDao.findById(checkId).get();
            pointCheckRespone.setId(planPointInfo.getId());
            pointCheckRespone.setPlanTaskId(planTaskId);

            pointCheckRespone.setTaskStatus(planPointInfo.getTaskStatus());
            pointCheckRespone.setPointStatus(planPointInfo.getPointStatus());
            pointCheckRespone.setBeginTime(planPointInfo.getBeginTime());
            pointCheckRespone.setEndTime(planPointInfo.getEndTime());
            pointCheckRespone.setPointId(pointCheckDetailBo.getPointId());
            pointCheckRespone.setPointName(pointCheckDetailBo.getPointName());
            pointCheckRespone.setPointNo(pointCheckDetailBo.getPointNo());
            pointCheckRespone.setPlanName(pointCheckDetailBo.getPlanName());
            pointCheckRespone.setRemark(pointCheckDetailBo.getCheckRemark());

            pointCheckRespone.setCheckTime(pointCheckDetailBo.getCheckTime());
            pointCheckRespone.setStrCheckTime(DateUtil.getLongDate(pointCheckDetailBo.getCheckTime()));
            pointCheckRespone.setCheckId(pointCheckDetailBo.getCheckId());
            pointCheckRespone.setPointImgUrls(pointImgUrls);
            pointCheckRespone.setScore(check.getScore() + "");
            pointCheckRespone.setUsername(pointCheckDetailBo.getUsername());
            pointCheckRespone.setDepartmentName(pointCheckDetailBo.getDepartmentName());
            List<AppCheckInputRespone> appCheckInputResponeList = new ArrayList<AppCheckInputRespone>();
            JSONObject appResponeMap = new JSONObject();
            list.forEach(action -> {
                List<String> pointInputImgUrls = new ArrayList<>();
                List<CheckShot> pointInputShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), action.getCheckInputId(),action.getClassifyId());
                pointInputShot.forEach(inputShot -> {
//                    pointInputImgUrls.add(fileUrl + inputShot.getPhotoData());
                    pointInputImgUrls.add(inputShot.getPhotoData());
                });
                AppCheckInputRespone appCheckInputRespone = new AppCheckInputRespone();
                appCheckInputRespone.setCheckInputId(action.getCheckInputId());
                appCheckInputRespone.setInputName(action.getInputName());
                appCheckInputRespone.setInputStatus(action.getInputStatus());
                appCheckInputRespone.setRiskDesc(action.getRiskDesc());
                appCheckInputRespone.setInputValue(action.getInputValue());
                appCheckInputRespone.setItemType(action.getItemType());
                appCheckInputRespone.setDataJson(action.getDataJson());
                appCheckInputRespone.setIsMust(action.getIsMust());
                appCheckInputRespone.setIsMultiline(action.getIsMultiline());
                appCheckInputRespone.setPictureJson(action.getPictureJson());
                appCheckInputRespone.setOrderNo(action.getOrderNo());
                appCheckInputRespone.setPointInputImgUrls(pointInputImgUrls);
                appCheckInputRespone.setClassifyId(action.getClassifyId());
                appCheckInputRespone.setClassifyName(action.getClassifyName());
                appCheckInputRespone.setRemark(action.getRemark());
                appCheckInputRespone.setPlanTaskId(action.getPlanTaskId());

                appCheckInputResponeList.add(appCheckInputRespone);

            });
            appResponeMap.put("items", appCheckInputResponeList);
            pointCheckRespone.setAppCheckInput(appResponeMap);
            return pointCheckRespone;
        }
        return pointCheckRespone;
    }







    @Override
    public AppPointCheckRespone queryCheckPointDetailInVersion2New(long checkId) {

        List<PointCheckDetailBo> list = checkMapper.findCheckPointInputItem(checkId);
        AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
        if (!list.isEmpty()) {
            List<String> pointImgUrls = new ArrayList<>();
            PointCheckDetailBo pointCheckDetailBo = list.get(0);
            List<CheckShot> pointShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), 0l,0l);
            pointShot.forEach(action -> {
                pointImgUrls.add(action.getPhotoData());
            });
            Check check = checkDao.findById(checkId).get();
            pointCheckRespone.setPointId(pointCheckDetailBo.getPointId());
            pointCheckRespone.setPointName(pointCheckDetailBo.getPointName());
            pointCheckRespone.setPointNo(pointCheckDetailBo.getPointNo());
            pointCheckRespone.setPointStatus(pointCheckDetailBo.getPointStatus());
            pointCheckRespone.setPlanName(pointCheckDetailBo.getPlanName());
            pointCheckRespone.setRemark(pointCheckDetailBo.getCheckRemark());
            pointCheckRespone.setCheckTime(pointCheckDetailBo.getCheckTime());
            pointCheckRespone.setStrCheckTime(DateUtil.getLongDate(pointCheckDetailBo.getCheckTime()));
            pointCheckRespone.setCheckId(pointCheckDetailBo.getCheckId());
            pointCheckRespone.setPointImgUrls(pointImgUrls);
            pointCheckRespone.setScore(check.getScore() + "");
            pointCheckRespone.setUsername(pointCheckDetailBo.getUsername());
            pointCheckRespone.setDepartmentName(pointCheckDetailBo.getDepartmentName());
            JSONObject appResponeMap = new JSONObject();
            list.forEach(action -> {
                List<String> pointInputImgUrls = new ArrayList<>();
                List<CheckShot> pointInputShot = checkShotDao.findAllByCheckIdAndCheckInputIdAndClassifyId(pointCheckDetailBo.getCheckId(), action.getCheckInputId(),action.getClassifyId());
                pointInputShot.forEach(inputShot -> {
                    pointInputImgUrls.add(inputShot.getPhotoData());
                });
                AppCheckInputRespone appCheckInputRespone = new AppCheckInputRespone();
                appCheckInputRespone.setCheckInputId(action.getCheckInputId());
                appCheckInputRespone.setInputName(action.getInputName());
                appCheckInputRespone.setInputStatus(action.getInputStatus());
                appCheckInputRespone.setRiskDesc(action.getRiskDesc());
                appCheckInputRespone.setInputValue(action.getInputValue());
                appCheckInputRespone.setItemType(action.getItemType());
                appCheckInputRespone.setDataJson(action.getDataJson());
                appCheckInputRespone.setIsMust(action.getIsMust());
                appCheckInputRespone.setIsMultiline(action.getIsMultiline());
                appCheckInputRespone.setPictureJson(action.getPictureJson());
                appCheckInputRespone.setOrderNo(action.getOrderNo());
                appCheckInputRespone.setPointInputImgUrls(pointInputImgUrls);
                appCheckInputRespone.setClassifyId(action.getClassifyId());
                appCheckInputRespone.setClassifyName(action.getClassifyName());
                appCheckInputRespone.setRemark(action.getRemark());

                String classifyName = action.getClassifyName();
                if (!StringUtil.isNotEmpty(classifyName)) {
                    classifyName = "其他";
                }
                String riskDesc = action.getRiskDesc();
                if (!StringUtil.isNotEmpty(riskDesc)) {
                    riskDesc = XJConstant.DEFAULT_RISKDESC;
                }

                JSONObject classifyJson;
                if (appResponeMap.containsKey(classifyName)) {
                    classifyJson = appResponeMap.getJSONObject(classifyName);
                } else {
                    classifyJson = new JSONObject();
                }
                JSONArray riskDescArr;
                if (classifyJson.containsKey(riskDesc)) {
                    riskDescArr = classifyJson.getJSONArray(riskDesc);
                } else {
                    riskDescArr = new JSONArray();
                }
                riskDescArr.add(appCheckInputRespone);
                classifyJson.put(riskDesc, riskDescArr);
                appResponeMap.put(classifyName, classifyJson);
            });
            pointCheckRespone.setAppCheckInput(appResponeMap);
            return pointCheckRespone;
        }
        return pointCheckRespone;
    }

















    @Override
    public Map<String, Object> queryRecordByPointId(HashMap<String, Object> req) {
//        if (!ObjectUtils.isEmpty(req.get("userId"))) {
//            req.put("userId", req.get("userId") + ",");
//        }
//        if (!ObjectUtils.isEmpty(req.get("planId"))) {
//            req.put("planId", req.get("planId") + ",");
//        }
//        if (!ObjectUtils.isEmpty(req.get("department"))) {
//            req.put("department", req.get("department") + ",");
//        }
//        if (!ObjectUtils.isEmpty(req.get("pointId"))) {
//            req.put("pointId", req.get("pointId") + ",");
//        }
        List<Map<String, Object>> checkMaps = checkMapper.queryRecordByPointId(req);
        Map<String, Object> resp = new HashMap<>();

        for (Map<String, Object> item : checkMaps) {
            List<Map<String, Object>> respItems = (List<Map<String, Object>>) resp.get(item.get("checkDate").toString());
            if (ObjectUtils.isEmpty(respItems)) {
                respItems = new ArrayList<>();
            }
            respItems.add(item);
            resp.put(item.get("checkDate").toString(), respItems);
        }
        return resp;
    }

    @Override
    public Map<String, Object> queryRecordById(int checkId) {
        Map<String, Object> check = checkMapper.queryCheckById(checkId);
        List<Map<String, Object>> checkInputItems = checkMapper.queryCheckInputItems(checkId);
        List<Map<String, Object>> checkimgs = checkMapper.queryCheckImgs(checkId);

        Map<String, Object> resp = new HashMap<>();
        resp.put("check", check);
        resp.put("inputItems", checkInputItems);
//        String ipPort = "http://" + fileIp + ":" + filePort + "/";
        for (Map<String, Object> map : checkimgs) {
            String imgPath = map.get("photoData").toString().replace("\\", "/");
//            map.put("photoData", fileUrl + imgPath);
//            map.put("openOperUrl", "window.open('" + fileUrl + imgPath + "')");
            map.put("photoData", imgPath);
            map.put("openOperUrl", "window.open('" + imgPath + "')");
        }
        resp.put("imgs", checkimgs);
        return resp;
    }

    @Override
    public Map<String, Object> checkCalendar(CheckRecordParam requestParam) {
        Map<String, Object> charData = checkMapper.pieChartData(requestParam);
        List<Map<String, Object>> calendarData = checkMapper.calendarData(requestParam);
        Map<String, Object> result = new HashMap<>();
        Map<String, List<CalendarStatusCountRespone>> calendarMap = new HashMap<>();
        if (!calendarData.isEmpty()) {
            calendarData.forEach(action -> {
                List<CalendarStatusCountRespone> statusCountList = new ArrayList<>();
                CalendarStatusCountRespone statusCount = new CalendarStatusCountRespone();
                statusCount.setCount(Double.valueOf(action.get("count").toString()));
                statusCount.setStatus(action.get("status").toString());
                if (calendarMap.containsKey(action.get("time"))) {
                    statusCountList = calendarMap.get(action.get("time"));
                    statusCountList.add(statusCount);
                } else {
                    statusCountList.add(statusCount);
                    calendarMap.put(action.get("time").toString(), statusCountList);
                }
            });
        }
        result.put("charData", charData);
        result.put("calendarData", calendarMap);
        return result;
    }

    @Override
    public Map<String, Object> checkCalendarNew(String checkTime, String orgCode,String type,String userId) throws ParseException {
        Map<String, Object> result = new HashMap<>();
            Calendar calendar = new GregorianCalendar();
        Calendar calendarNew = new GregorianCalendar();
        calendarNew.setTime(new Date());
        String startTime = "" ;
        String endTime = "";
        String table = "";
        if(type.equals(String.valueOf(PlanTaskTypeStatusEnum.week.getValue()))) {
            Date startMonthDate = DateUtils.getStartMonthDate(checkTime, DateUtils.DATE_PATTERN);
            Date endMonthDate = DateUtils.getEndMonthDate(checkTime, DateUtils.DATE_PATTERN);
            calendar.setTime(startMonthDate);

            int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (i == 0) {
                calendar.add(Calendar.DAY_OF_WEEK,-6);
                startTime = DateUtils.dateTimeToDateString(calendar.getTime());
            } else if(i != 1) {
                calendar.add(Calendar.DAY_OF_WEEK,-(i-1));
                startTime = DateUtils.dateTimeToDateString(calendar.getTime());
            }

            calendar.setTime(endMonthDate);
            int j = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (j != 0) {
                calendar.add(Calendar.DAY_OF_WEEK,7-j);
                endTime = DateUtils.dateTimeToDateString(calendar.getTime());
            } else {
                endTime = DateUtils.dateTimeToDateString(calendar.getTime());
            }
            int sYear = calendar.get(Calendar.YEAR);
            int year = calendarNew.get(Calendar.YEAR);
            if(sYear == year) {
                table = P_STATIC_WEEK;
            } else {
                table = P_STATIC_DAY + "_" + sYear;
            }
        }

        if(type.equals(String.valueOf(PlanTaskTypeStatusEnum.day.getValue()))) {
            calendar.setTime(DateUtils.dateParse(checkTime, DateUtils.MONTH_PATTERN));
            int sYear = calendar.get(Calendar.YEAR);
            int sMonth = calendar.get(Calendar.MONTH) + 1;
            int month = calendarNew.get(Calendar.MONTH) + 1;
            if(sMonth == month) {
                table = P_STATIC_DAY;
            } else {
                table = P_STATIC_DAY + "_" + sYear+sMonth;
            }
        }

        if(type.equals(String.valueOf(PlanTaskTypeStatusEnum.month.getValue()))) {
            table = P_STATIC_MONTH;
        }

        List<Map<String, Object>> list = checkMapper.planCountNew(checkTime, orgCode, table, type,startTime,endTime);
        result.put("calendarData", list);
        return result;
    }

    @Override
    public List<CheckInfoVo> getCheckInfoList(String toke,String product,String appKey,CheckInfoPageParam param) {
    	 List<CheckInfoVo> list= checkMapper.getCheckInfo(param);

        Set<String> userIds = Sets.newHashSet(Lists.transform(list, CheckInfoVo::getUserId));
        Set<String> deptIds = Sets.newHashSet(Lists.transform(list, CheckInfoVo::getDepId));
        deptIds.remove("");
        deptIds.remove(null);
        String joinUserId="";
        for (String userId:userIds) {
            if(!ObjectUtils.isEmpty(userId)){
                joinUserId=joinUserId+userId+",";
            }
        }
        List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds( toke, product, appKey,joinUserId);
        Map<String, String> deptMap =  new HashMap<String,String>();
        if(!CollectionUtils.isEmpty(deptIds)){
            List<LinkedHashMap> deptList = remoteSecurityService.listDepartmentByDeptIds( toke, product, appKey,Joiner.on(",").join(deptIds));
           // deptMap = deptList.stream().collect(Collectors.toMap(DepartmentModel::getSequenceNbr, DepartmentModel::getDepartmentName));
            for (int i = 0; i < deptList.size(); i++) {
            	deptMap.put(deptList.get(i).get("sequenceNbr").toString(), deptList.get(i).get("departmentName").toString());
			}
        }
        Map<String,String> userModelMap = userModels.stream().collect(Collectors.toMap(AgencyUserModel::getUserId,AgencyUserModel::getRealName ,(k1,k2)->k2));
        Map<String, String> deptMapNew= deptMap;
        List<String> userNames = new ArrayList<>();
        list.forEach(e -> {
            userNames.clear();
            List<String> userIds1 = Arrays.asList(e.getUserId().split(","));
            for(String userId : userIds1){
                userNames.add(userModelMap.get(userId));
            }
            userNames.remove(null);
            e.setUserName(Joiner.on(",").join(userNames));
            e.setDepartmentName(deptMapNew.get(e.getDepId()));
        });
        return list;

    }

    @Override
    public List<Map<String, Object>> getCheckInfoImgsList(CheckInfoPageParam param) {
        return checkMapper.getCheckInfoImgsList(param);
    }

    @Override
    public List<Map<String, Object>> getCheckInfoImgsList(Long[] ids) {
        return checkMapper.getCheckInfoImgsByCheckIdsList(ids);
    }

    @Override
    public List<CheckInfoVo> getSelectedCheckInfoList(String toke,String product,String appKey,Long[] ids) {
    	List<CheckInfoVo> list = checkMapper.getSelectedCheckInfoList(ids);
        Set<String> userIds = Sets.newHashSet(Lists.transform(list, CheckInfoVo::getUserId));
        Set<String> deptIds = Sets.newHashSet(Lists.transform(list, CheckInfoVo::getDepId));
        deptIds.remove("");
        deptIds.remove(null);
        List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds( toke, product, appKey,Joiner.on(",").join(userIds));
        Map<String, String> deptMap =  new HashMap<String,String>();
//        if(!CollectionUtils.isEmpty(deptIds)){
//            List<LinkedHashMap> deptList = remoteSecurityService.listDepartmentByDeptIds( toke, product, appKey,Joiner.on(",").join(deptIds));
//            //deptMap = deptList.stream().collect(Collectors.toMap(DepartmentModel::getSequenceNbr, DepartmentModel::getDepartmentName));
//            for (int i = 0; i < deptList.size(); i++) {
//            	deptMap.put(deptList.get(i).get("sequenceNbr").toString(), deptList.get(i).get("departmentName").toString());
//			}
//        }
        Map<String,String> userModelMap = userModels.stream().collect(Collectors.toMap(AgencyUserModel::getUserId,AgencyUserModel::getRealName ,(k1,k2)->k2));
        Map<String, String> deptMapNew= deptMap;
        List<String> userNames = new ArrayList<>();
        list.forEach(e -> {
            userNames.clear();
            List<String> userIds1 = Arrays.asList(e.getUserId().split(","));
            for(String userId : userIds1){
                userNames.add(userModelMap.get(userId));
            }
            userNames.remove(null);
            e.setUserName(Joiner.on(",").join(userNames));
//            e.setDepartmentName(deptMapNew.get(e.getDepId()));
        });

        return list;
    }

    @Override
    public List<HashMap<String, Object>> getCountMonthChkByRole(HashMap<String, Object> paramMap, String dateMonth) {
//        if (dateMonth == null) {
//            Date date = new Date();
//            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//            dateMonth = format.format(date);
//        } else {
//            dateMonth = dateMonth.substring(0, 8);
//        }
//        String startDate = DateUtil.getStartMonthDate(dateMonth, "yyyy-MM-dd");
//        String endDate = DateUtil.getEndMonthDate(dateMonth, "yyyy-MM-dd");
//        paramMap.put("startDate", startDate);
//        paramMap.put("endDate", endDate);
//        paramMap.put("finish_yes", XJConstant.TASK_STATUS_FINISH);
//        paramMap.put("finish_out", XJConstant.TASK_STATUS_TIMEOUT);
//        List<HashMap<String, Object>> content = null;
//        if (!XJConstant.PERSON_FLAG.equals(paramMap.get("roleFlag"))) {
//            content = checkMapper.getCountMonthChk(paramMap);
//        }
//        return content;
        return checkMapper.getCountMonthChkNew();
    }



    @Override
    public List<HashMap<String, Object>> getCountMonthChkByRoleNew(String orgCode) {

        return checkMapper.getCountMonthChkNewXIN(orgCode);
    }

    @SuppressWarnings("unchecked")
    @Override
    public QueryCriteriaRespone getQueryCriteriaInit(String toke,String product,String appKey,String loginOrgCode, String roleTypeName, String departmentId, String companyId) {


        QueryCriteriaRespone pointQueryCriteriaRespone = new QueryCriteriaRespone();
        if (XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase()) || XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase())) {
            List<DepartmentModel> departmentBos = remoteSecurityService.listDepartmentsByCompanyId(toke, product, appKey,companyId);
            //查询没有部门的人员信息
            CompanyModel companyModel = remoteSecurityService.listUserByCompanyId1(toke, product, appKey,companyId);
            pointQueryCriteriaRespone.setDepartments(Lists.newArrayList(getDepartmentMap(departmentBos,companyModel)));//公司下部门
        } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
            DepartmentModel departmentBo = remoteSecurityService.getDepartmentByDeptId( toke, product, appKey,departmentId);
            pointQueryCriteriaRespone.setDepartments(Lists.newArrayList(beanToMap(departmentBo)));//本公司
        } else if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())) {//个人不返回
            return null;
        }



        pointQueryCriteriaRespone.setTypes(catalogTreeDao.findByOrgCode(loginOrgCode));
        pointQueryCriteriaRespone.setStatus(PointStatusEnum.getEnumList());
        pointQueryCriteriaRespone.setPointLevel(PointLevelEnum.getEnumList());
        return pointQueryCriteriaRespone;
    }


    public List<Map<String, Object>>  getDepartmentMap(List<DepartmentModel> departmentModels, CompanyModel companyModel ){
        List<Map<String, Object>> res = new ArrayList<>();
        List<DepartmentBo> departmentBos = ModelToBo(departmentModels);
        for (DepartmentBo d : departmentBos) {
            LinkedHashMap<String, Object> dept = new LinkedHashMap<>();
            dept.put("id", String.valueOf(d.getSequenceNbr()));
            dept.put("key", String.valueOf(d.getSequenceNbr()));
            dept.put("value", String.valueOf(d.getSequenceNbr()));
            dept.put("state", "open");
            dept.put("type", "department");
            dept.put("orgCode", String.valueOf(d.getSequenceNbr()));
            dept.put("label", d.getDepartmentName());
            dept.put("title", d.getDepartmentName());
            dept.put("name", d.getDepartmentName());
            dept.put("writeable", 0);
            res.add(dept);
        }

        List children = (List) companyModel.getChildren();


        for (int i = 0; i < children.size(); i++) {
            Map<String, Object> map = (LinkedHashMap) children.get(i);
            if ("其他".equals((map.get("departmentName").toString()))) {
                LinkedHashMap<String, Object> dept = new LinkedHashMap<>();
                dept.put("id", "-1");
                dept.put("key", "-1");
                dept.put("value", "-1");
                dept.put("state", "close");
                dept.put("type", "department");
                dept.put("label", "其他");
                dept.put("title", "其他");
                dept.put("name", "其他");
                dept.put("writeable", "0");
                res.add(dept);
            }
        }
            return res;
    }


    /**
     * 类型转换  DepartmentModel => DepartmentBo
     * @param departmentModels
     * @return
     */
    private List<DepartmentBo> ModelToBo(List<DepartmentModel> departmentModels){
        List<DepartmentBo> departmentBos = new ArrayList<>();
        departmentModels.forEach(
                x -> {
                    DepartmentBo departmentBo = new DepartmentBo();
                    departmentBo.setSequenceNbr(x.getSequenceNbr());
                    departmentBo.setCompanySeq(x.getCompanySeq());
                    departmentBo.setDepartmentDesc(x.getDepartmentDesc());
                    departmentBo.setDepartmentName(x.getDepartmentName());
                    departmentBo.setDeptOrgCode(x.getDeptOrgCode());
                    departmentBo.setLevel(x.getLevel());
                    departmentBo.setOrgCode(x.getOrgCode());
                    departmentBo.setParentId(x.getParentId());
                    if (!ObjectUtils.isEmpty(x.getChildren())) {
                        Object collect = x.getChildren().stream().collect(Collectors.toList());
                        List<LinkedHashMap> children = (List<LinkedHashMap>) collect;
                        //departmentBo.setChildren(children);
                        departmentBos.addAll(ModelToBo2(children));
                    }
                    departmentBos.add(departmentBo);
                }
        );
        return departmentBos;
    }
    private List<DepartmentBo> ModelToBo2(List<LinkedHashMap> departmentModels){
        List<DepartmentBo> departmentBos = new ArrayList<>();
        departmentModels.forEach(
                x -> {
                    DepartmentBo departmentBo = new DepartmentBo();
                    departmentBo.setSequenceNbr(Long.valueOf(x.get("sequenceNbr").toString()));
                    departmentBo.setCompanySeq(Long.valueOf(x.get("companySeq").toString()));
                    departmentBo.setDepartmentDesc(x.get("departmentDesc")+"");
                    departmentBo.setDepartmentName(x.get("departmentName")+"");
                    departmentBo.setDeptOrgCode(Integer.valueOf(x.get("deptOrgCode")+""));
                    departmentBo.setLevel(x.get("level")+"");
                    departmentBo.setOrgCode(x.get("orgCode")+"");
                    departmentBo.setParentId(Long.valueOf(x.get("parentId")+""));

                    if (x.get("children")!=null) {
                        List<LinkedHashMap> collect = (List<LinkedHashMap>) x.get("children");
                        departmentBos.addAll( ModelToBo2(collect));
                    }
                    departmentBos.add(departmentBo);
                }
        );
        return departmentBos;
    }
    public static <T> Map<String, Object> beanToMap(T bean) {
    	  Map<String, Object> map = Maps.newHashMap();
    	  if (bean != null) {
    	    BeanMap beanMap = BeanMap.create(bean);
    	    for (Object key : beanMap.keySet()) {
    	    if("sequenceNbr".equals(key+"")){
      	      map.put(key+"", beanMap.get(key)+"");

    	    }else{
      	      map.put(key+"", beanMap.get(key));

    	    }
    	    }
    	  }
    	  return map;
    	}

    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
    	  List<Map<String, Object>> list = Lists.newArrayList();
    	  if (objList != null && objList.size() > 0) {
    	    Map<String, Object> map = null;
    	    T bean = null;
    	    for (int i = 0,size = objList.size(); i < size; i++) {
    	      bean = objList.get(i);
    	      map = beanToMap(bean);
    	      list.add(map);
    	    }
    	  }
    	  return list;
    }







    @Override
    public List<HashMap<String, String>> getCalCountChkInfo(HashMap<String, Object> paramsMap) {
        List<HashMap<String, String>> checkCalCountInfoList = checkMapper.getCalenderCountInfoList(paramsMap);
        return checkCalCountInfoList;
    }

    @Override
    public List<CheckUserBo> getAuthUserInfo(HashMap<String, Object> paramsMap) {
        List<CheckUserBo> checkUserBoList = checkMapper.getCheckUserInfoList(paramsMap);
        return checkUserBoList;
    }

    private Long getLastsetCheckByPointID(Long pointId) {
        Long checkID = checkMapper.getLastsetCheckByPointID(pointId);
        return checkID;
    }

    @Override
    public CommonPage<CheckInputBo> getCheckInputByCheckId(CheckDetailInputPageParam param) {
        // 如果不传巡检ID，则获取最新一条巡检点对应的巡检记录ID
        if (param.getCheckID() == -1) {
            Long checkID = getLastsetCheckByPointID(param.getPointID());
            if (checkID != null) {
                param.setCheckID(checkID);
            }
        }
        Long checkID = param.getCheckID();
        long total = checkMapper.countCheckInputByMybatis(checkID);
        List<CheckInputBo> content = checkMapper.getCheckInputByCheckId(param);
        CommonPage<CheckInputBo> result = new CommonPage<>(content, param, total);
        return result;
    }

    @Override
    public List<HashMap<String,Object>> getEquipByCheckId(CheckDetailInputPageParam param) {
        // 如果不传巡检ID，则获取最新一条巡检点对应的巡检记录ID
        if (param.getCheckID() == -1) {
            Long checkID = getLastsetCheckByPointID(param.getPointID());
            if (checkID != null) {
                param.setCheckID(checkID);
            }
        }
        List<HashMap<String,Object>>  equipList= checkMapper.getCheckEquipByCheckID(param.getCheckID());
        equipList.forEach(equip->{
            param.setClassifyId(equip.get("classifyId").toString());
            equip.put("IsOK",PointStatusEnum.QUALIFIED.getName());
            List<HashMap<String,Object>> inputContent = checkMapper.getEquipInputByCheckId(param);
            List<HashMap<String,Object>> imgContent = checkMapper.getEquipInfoImgsByCheckIdsList(param.getCheckID());
//            String ipPort = "http://" + fileIp + ":" + filePort + "/";
            inputContent.forEach(e -> {
                List<String> photoList = new ArrayList<>();
                //查询图片
                for (int i = 0; i <imgContent.size() ; i++) {
                    //checkInputId
                    if (e.get("inputId").toString().equals(imgContent.get(i).get("checkInputId").toString())
                            && e.get("classifyId").toString().equals(imgContent.get(i).get("classifyId").toString())) {
//                        photoList.add(fileUrl + imgContent.get(i).get("photoData"));
                        photoList.add(String.valueOf(imgContent.get(i).get("photoData")));
                    }
                    if (PointStatusEnum.UNQUALIFIED.getName().equals(e.get("IsOK").toString())) {
                        equip.put("IsOK", PointStatusEnum.UNQUALIFIED.getName());
                    }
                }
                e.put("photoData", photoList);
            });
            equip.put("equipIputLsit",inputContent);
//            LinkedHashMap<String,Object> jsonObject = equipment.getEquipDetail(Long.parseLong(equip.get("equipmentId").toString()));
//            LinkedHashMap<String,Object> result = (LinkedHashMap<String, Object>) jsonObject.get("result");
//            if(result!=null){
//                if(result.get("sourceName")!=null){
//                    equip.put("arec",result.get("sourceName").toString());
//                }else{
//                    equip.put("arec","");
//                }
//                if(result.get("categoryName")!=null){
//                    equip.put("equipType",result.get("categoryName").toString());
//                }else{
//                    equip.put("equipType","");
//                }
//                if(result.get("fullName")!=null){
//                    if(result.get("area")!=null){
//                        equip.put("area",result.get("fullName").toString()+result.get("area"));
//                    }else {
//                        equip.put("area",result.get("fullName").toString());
//                    }
//
//                }else{
//                    equip.put("area","");
//                }
//
//                equip.put("place", result.get("warehouseStructureName"));
//            }
        });
        return equipList;
    }

    @Override
    public List<HashMap<String,Object>> getEquipInputByCheckId(CheckDetailInputPageParam param) {
        // 如果不传巡检ID，则获取最新一条巡检点对应的巡检记录ID
        if (param.getCheckID() == -1) {
            Long checkID = getLastsetCheckByPointID(param.getPointID());
            if (checkID != null) {
                param.setCheckID(checkID);
            }
        }
        Long checkID = param.getCheckID();
        List<HashMap<String,Object>> content = checkMapper.getEquipInputByCheckId(param);
        List<HashMap<String,Object>> imgContent = checkMapper.getEquipInfoImgsByCheckIdsList(param.getCheckID());
//        String ipPort = "http://" + fileIp + ":" + filePort + "/";
        content.forEach(e -> {
            //查询图片
            for (int i = 0; i <imgContent.size() ; i++) {
                //checkInputId
                if(e.get("checkInputId").toString().equals(imgContent.get(i).get("checkInputId").toString())
                        && e.get("classifyId").toString().equals(imgContent.get(i).get("classifyId").toString())){
//                    e.put("photoData",fileUrl+imgContent.get(i).get("photoData"));
                    e.put("photoData",imgContent.get(i).get("photoData"));
                }
            }
        });
        return content;
    }

    @Override
    public CheckDetailBo getCheckDetailById( String toke,String product,String appKey,CheckDetailInputPageParam param) {
        long checkID = param.getCheckID();
        CheckDetailBo checkDetailBo = checkMapper.getCheckDetailByID(param);

        if(checkDetailBo!=null&&checkDetailBo.getCheckUserName()!=null){

      	  //处理用户信息
          String userIds="";
          Set<String> set = new HashSet<>();
          if(!ObjectUtils.isEmpty(checkDetailBo.getCheckUserName())){
              set.add(checkDetailBo.getCheckUserName());
          }
          List<String> list1 = new ArrayList<>(set);
          userIds = String.join(",", list1);
          List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds( toke,product,appKey,userIds);
          //新安全
          if(listd!=null&&listd.size()>0){
        	  checkDetailBo.setCheckUserName(listd.get(0).getRealName());
        	  checkDetailBo.setContact(listd.get(0).getMobile());
          }

      }
        checkDetailBo.setCheckID(checkID);
        checkDetailBo.setPhotosUrl(getLivePhotos(checkID));
        return checkDetailBo;
    }

    @Override
    public List<String> getCheckInputPhotoById(Long checkID) {
        List<String> photos = checkMapper.getCheckInputPhotoByID(checkID);
        return photos;
    }

    @Override
    public Page<CheckTraListBo> getCheckTraList(CheckPtListPageParam params) {
        long total = checkMapper.countCheckTraListData(params);
        List<CheckTraListBo> content = checkMapper.getCheckTraList(params);
        Page<CheckTraListBo> result = new PageImpl<CheckTraListBo>(content, params, total);
        return result;
    }

    @Override
    public List<PlanRoutePointBo> getRoutePlanPointList(CheckPtListPageParam params) {
        List<PlanRoutePointBo> content = checkMapper.getLastPointCheckList(params);
        return content;
    }

    @Override
    public QueryCriteriaRespone findCheckSystemInit(String toke,String product,String appKey,String type, String orgCode, String roleTypeName, String departmentId, String companyId) {


        QueryCriteriaRespone pointQueryCriteriaRespone = new QueryCriteriaRespone();

        if ("user".equals(type)) {
            List<AgencyUserModel> users = remoteSecurityService.listUserByCompanyId(toke, product, appKey,companyId);
            pointQueryCriteriaRespone.setUsers(objectsToMaps(users));
        } else if ("status".equals(type)) {
            pointQueryCriteriaRespone.setStatus(PointStatusEnum.getEnumList());
        } else if ("pointLevel".equals(type)) {
            pointQueryCriteriaRespone.setPointLevel(PointLevelEnum.getEnumList());
        } else if ("type".equals(type)) {
            pointQueryCriteriaRespone.setTypes(catalogTreeDao.findByOrgCode(orgCode));
        } else if ("departments".equals(type)) {
//			pointQueryCriteriaRespone.setDepartments(iUserService.getGroupListByUser(user));
            if (XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase())
                    || XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase())) {
                List<DepartmentModel> departmentBoList = remoteSecurityService.listDepartmentsByCompanyId(toke, product, appKey,companyId);
                pointQueryCriteriaRespone.setDepartments(objectsToMaps(departmentBoList));// 公司下部门
            } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
                DepartmentModel departmentBo = remoteSecurityService.getDepartmentByDeptId(toke, product, appKey,departmentId);
                pointQueryCriteriaRespone.setDepartments(Lists.newArrayList(beanToMap(departmentBo)));// 本公司
            } else if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())) {// 个人不返回
                return null;
            }
        }




      /*  QueryCriteriaRespone pointQueryCriteriaRespone = new QueryCriteriaRespone();
        String roleTypeName = loginParam.getRoleTypeName();
        String[] orgs = loginParam.getLoginOrgCode().split("\\*");
        String companyId = orgs[orgs.length - 1];
        if ("user".equals(type)) {
            if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName) ||
                    XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName)) {
                pointQueryCriteriaRespone.setUsers(userService.queryUserByOrgCode(loginParam.getLoginOrgCode()));
            } else {
                pointQueryCriteriaRespone.setUsers(userService.queryUserByOrgCode(loginParam.getUserOrgCode()));
            }
        } else if ("status".equals(type)) {
            pointQueryCriteriaRespone.setStatus(PointStatusEnum.getEnumList());
        } else if ("pointLevel".equals(type)) {
            pointQueryCriteriaRespone.setPointLevel(PointLevelEnum.getEnumList());
        } else if ("type".equals(type)) {
            pointQueryCriteriaRespone.setTypes(catalogTreeDao.findByOrgCode(loginParam.getLoginOrgCode()));
        } else if ("departments".equals(type)) {
//			pointQueryCriteriaRespone.setDepartments(iUserService.getGroupListByUser(user));
            if (XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName)
                    || XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName)) {
                pointQueryCriteriaRespone.setDepartments(groupService.findByCompanyId(Long.parseLong(companyId)));// 公司下部门
            } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)) {
                pointQueryCriteriaRespone
                        .setDepartments((List<SDepartment>) deptmentDao.findById(userDao.findById(loginParam.getUserId()).get().getDepartmentId().longValue()).get());// 本公司
            } else if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName)) {// 个人不返回
                return null;
            }
        }
*/
        return pointQueryCriteriaRespone;
    }

    @Override
    public Page<CheckInfoBo> getCheckInfoList(CheckInfoListPageParam params) {
        long total = checkMapper.countCheckInfoListData(params);
        List<CheckInfoBo> content = checkMapper.getCheckInfoList(params);
        Page<CheckInfoBo> result = new PageImpl<CheckInfoBo>(content, params, total);
        return result;
    }

    @Override
    public Page<Map<String, Object>> getCheckInfoList1(String toke,String product,String appKey,CheckInfoListPageParam params) {
        long total = checkMapper.countCheckInfoListData1(params);
        List<Map<String, Object>> content = checkMapper.getCheckInfoList1(params);


        //查询用户名称和部门名称

        if (!CollectionUtils.isEmpty(content)) {
            Set<String> userIds =new HashSet<>();
            content.forEach(e -> {
            	if(!ObjectUtils.isEmpty(e.get("userID"))){
                	userIds.add(e.get("userID")+"");
            	}
            });
            List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds( toke, product, appKey,Joiner.on(",").join(userIds));
            Map<String, String> userModelMap =  new HashMap<String,String>();

            userModels.forEach(e -> {
            	userModelMap.put(e.getUserId(), e.getMobile());
            });

           if(userModelMap!=null){
        	   content.forEach(e -> {
                   e.put("loginName",userModelMap.get(e.get("userID")+""));
               });
           }

        }



        Page<Map<String, Object>> result = new PageImpl<Map<String, Object>>(content, params, total);
        return result;
    }

    @Override
    public GraphInitDataResponse getViewModuleInitData() {
        List<Map<String, Object>> list = checkMapper.getRoutesAndPointsInfo();
        Map<String, RouteResponse> routeMap = new HashMap<String, RouteResponse>();
        Map<String, PointInfoResponse> pointMap = new HashMap<String, PointInfoResponse>();
        List<PointInfoResponse> pointInfoResponseList = new ArrayList<PointInfoResponse>();
        List<RouteResponse> routeResponseList = new ArrayList<RouteResponse>();
        Map<String, PatrolUserRespone> userMap = new HashMap<String, PatrolUserRespone>();
        GraphInitDataResponse graphInitDataResponse = new GraphInitDataResponse();
        list.forEach(action -> {
            PatrolUserRespone patrolUserRespone = null;
            if (action.get("OpenID") != null) {
                patrolUserRespone = userMap.get(action.get("OpenID").toString());
                if (patrolUserRespone == null) {
                    patrolUserRespone = new PatrolUserRespone();
                    patrolUserRespone.setUserId(action.get("OpenID") != null ? action.get("OpenID").toString() : "");
                    patrolUserRespone.setUserName(action.get("RealName") != null ? action.get("RealName").toString() : "");
                    patrolUserRespone.setOrgCode(action.get("orgCode") != null ? action.get("orgCode").toString() : "");
                    patrolUserRespone.setGroupName(action.get("GroupName") != null ? action.get("GroupName").toString() : "");
                }
            } else {
                String orgCode = null;
                if (action.get("gOrgCode") != null) {
                    orgCode = action.get("gOrgCode").toString();
                } else {
                    orgCode = action.get("compCode") != null ? action.get("compCode").toString() : null;
                }
                if (orgCode != null) {
                    patrolUserRespone = new PatrolUserRespone();
                    patrolUserRespone.setOrgCode(orgCode);
                }
            }

            if (action.get("PointID") != null) {
                getPointInfoResponseList(pointMap, action, patrolUserRespone, pointInfoResponseList);
            }
            if (action.get("RouteID") != null) {
                getRouteList(routeMap, action, patrolUserRespone, routeResponseList);
            }
        });
        graphInitDataResponse.setRoutes(routeResponseList);
        graphInitDataResponse.setPoints(pointInfoResponseList);
        return graphInitDataResponse;
    }

    private List<RouteResponse> getRouteList(Map<String, RouteResponse> route
            , Map<String, Object> data
            , PatrolUserRespone patrolUserRespone
            , List<RouteResponse> routeResponseList) {

        RouteResponse routeResponse = route.get(data.get("RouteID").toString());
        List<PatrolUserRespone> patrolUsers = new ArrayList<PatrolUserRespone>();
        if (routeResponse == null) {
            routeResponse = new RouteResponse();
            routeResponse.setRouteId(Integer.valueOf(data.get("RouteID").toString()));
            routeResponse.setRouteName(data.get("rName") != null ? data.get("rName").toString() : "");
            routeResponse.setBoss(data.get("Boss") != null ? data.get("Boss").toString() : "");
            routeResponse.setTel(data.get("Tel") != null ? data.get("Tel").toString() : "");
            if (patrolUserRespone != null) {
                patrolUsers.add(patrolUserRespone);
            }
            routeResponse.setPatrolUsers(patrolUsers);
            routeResponseList.add(routeResponse);
            route.put(data.get("RouteID").toString(), routeResponse);
        } else {
            if (patrolUserRespone != null) {
                patrolUsers = routeResponse.getPatrolUsers();
                List<String> userIds = patrolUsers.stream().filter(num -> num != null).map(arg0 -> arg0.getUserId()).collect(Collectors.toList());
                if (!userIds.contains(patrolUserRespone.getUserId())) {
                    patrolUsers.add(patrolUserRespone);
                    routeResponse.setPatrolUsers(patrolUsers);
                }
            }

        }
        return routeResponseList;

    }

    private List<PointInfoResponse> getPointInfoResponseList(Map<String, PointInfoResponse> pointMap
            , Map<String, Object> data
            , PatrolUserRespone patrolUserRespone
            , List<PointInfoResponse> pointInfoResponseList) {
        PointInfoResponse pointInfoResponse = pointMap.get(data.get("PointID").toString());
        List<PatrolUserRespone> patrolUsers = new ArrayList<PatrolUserRespone>();
        if (pointInfoResponse == null) {
            pointInfoResponse = new PointInfoResponse();
            pointInfoResponse.setPointId(Integer.valueOf(data.get("PointID").toString()));
            if (data.get("floor") != null) {
                PointPositionInfoSyn3DRespone config = new PointPositionInfoSyn3DRespone();
                config.setBelongObjModel("floor_" + data.get("floor").toString());
                config.setIsIndoor(Boolean.valueOf(data.get("isIndoor").toString()));
                pointInfoResponse.setConfig(config);
            }
            pointInfoResponse.setRouteNames(data.get("rName") != null ? data.get("rName").toString() : "");
            pointInfoResponse.setPointName(data.get("pName") != null ? data.get("pName").toString() : "");
            pointInfoResponse.setCoordinates(data.get("coordinates") != null ? data.get("coordinates").toString() : "");
            pointInfoResponse.setPointLevel(data.get("level") != null ? data.get("level").toString() : "");
            pointInfoResponse.setStatus(data.get("RealTimeStatus") != null ? data.get("RealTimeStatus").toString() : "");
            pointInfoResponse.setAddress(data.get("Address") != null ? data.get("Address").toString() : "");
            pointInfoResponse.setTaskId(data.get("taskId") != null ? Long.valueOf(data.get("taskId").toString()) : null);

            if (patrolUserRespone != null) {
                patrolUsers.add(patrolUserRespone);
            }
            pointInfoResponse.setUsers(patrolUsers);
            pointInfoResponseList.add(pointInfoResponse);
            pointMap.put(data.get("PointID").toString(), pointInfoResponse);
        } else {
            if (patrolUserRespone != null) {
                patrolUsers = pointInfoResponse.getUsers();
                List<String> userIds = patrolUsers.stream().filter(num -> num != null).map(arg0 -> arg0.getUserId()).collect(Collectors.toList());
                if (!userIds.contains(patrolUserRespone.getUserId())) {
                    patrolUsers.add(patrolUserRespone);
                    pointInfoResponse.setUsers(patrolUsers);
                }

                if (data.get("rName") != null && data.get("rName") != "") {
                    if (pointInfoResponse.getRouteNames().indexOf(data.get("rName").toString()) == -1) {
                        pointInfoResponse.setRouteNames(pointInfoResponse.getRouteNames() + "," + data.get("rName").toString());
                    }
                }
            }

        }
        return pointInfoResponseList;

    }

    @Override
    public List<CheckAnalysisVo> getCheckStatisticalAnalysis(String toke,String product,String appKey,CheckStatisticalParam param) {
        List<CheckAnalysisVo> checkAnalysisVos = checkMapper.getCheckStatisticalAnalysis(param);

        if(param.getStatisticsTyle()==3){

        	 //安全处里
            if(checkAnalysisVos!=null&&checkAnalysisVos.size()>0){

            	  //获取部门名称
                String userIds="";
                Set<String> set = new HashSet<>();
                checkAnalysisVos.forEach(s -> {
                	 set.add(s.getName());
                });

                List<String> list1 = new ArrayList<>(set);
                userIds = String.join(",", list1);
                List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( toke,product,appKey,userIds);

                //新安全
                checkAnalysisVos.forEach(s -> {
                	if(  listd != null && listd.size() > 0) {
                		List<LinkedHashMap> filterDep = listd.stream().filter(d -> d.get("sequenceNbr").toString().equals(s.getName())).collect(Collectors.toList());

            			if(filterDep != null && filterDep.size() > 0){
            				LinkedHashMap dep = filterDep.get(0);
            				 s.setName(dep.get("departmentName").toString());
                        }
                	}

                	    });
            }
        }

        if(param.getStatisticsTyle()==4){
        	//查询用户名

            //安全处里
            if(checkAnalysisVos!=null&&checkAnalysisVos.size()>0){

            	  //处理用户信息
                String userIds="";
                Set<String> set = new HashSet<>();
                checkAnalysisVos.forEach(s -> {
                	if(!ObjectUtils.isEmpty(s.getName())){
                   	 	set.add(s.getName());
                	}
                });
                List<String> list1 = new ArrayList<>(set);
                userIds = String.join(",", list1);
                List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds( toke,product,appKey,userIds);
                //新安全
                checkAnalysisVos.forEach(s -> {
                		 listd.forEach(s1 -> {
                	    		if(s.getName().equals(s1.getUserId())){
                	    			 s.setName(s1.getRealName());
                	    		}
                	        });

                	    });
            }
        }



        CheckAnalysisVo countVo = new CheckAnalysisVo();
        int planTaskCount = 0;
        int checkCount = 0;
        int ok = 0;
        int faild = 0;
        int missed = 0;
        double score = 0;
        double missedRate = 0;
        double faildRate = 0;
        int size = checkAnalysisVos.size();
        for (CheckAnalysisVo checkAnalysisVo : checkAnalysisVos) {
            planTaskCount += Integer.parseInt(checkAnalysisVo.getPlanTaskCount());
            checkCount += Integer.parseInt(checkAnalysisVo.getCheckCount());
            ok += Integer.parseInt(checkAnalysisVo.getOk());
            faild += Integer.parseInt(checkAnalysisVo.getFaild());
            missed += Integer.parseInt(checkAnalysisVo.getMissed());
            score += Double.parseDouble(checkAnalysisVo.getScore());
            missedRate += Double.parseDouble(checkAnalysisVo.getMissedRate());
            faildRate += Double.parseDouble(checkAnalysisVo.getFaildRate());
        }
        countVo.setName("合计");
        countVo.setPlanTaskCount(String.valueOf(planTaskCount));
        countVo.setCheckCount(String.valueOf(checkCount));
        countVo.setOk(String.valueOf(ok));
        countVo.setFaild(String.valueOf(faild));
        countVo.setMissed(String.valueOf(missed));
        if(size>0){
        	countVo.setScore(String.format("%.2s",String.valueOf(score / size)));
            countVo.setMissedRate(String.format("%.2s", String.valueOf(missedRate / size)));
            countVo.setFaildRate(String.format("%.2s",String.valueOf(faildRate / size)));
        }else{
        	countVo.setScore(String.valueOf(0));
            countVo.setMissedRate(String.valueOf(0));
            countVo.setFaildRate(String.valueOf(0));
        }

        checkAnalysisVos.add(countVo);
        return checkAnalysisVos;
    }

    @Override
    public long getCumulativeCheckCountByOrgCode(String loginOrgCode) {
        return checkMapper.getCumulativeCheckCountByOrgCode(loginOrgCode);
    }

    @Override
    public List<Long> getCheckDataCount(HashMap<String, Object> param) {
        return checkMapper.getCheckDataCount(param);
    }

    @Override
    public List<String> getCheckPhotosByCheckAndInputId(int checkId, int checkInputId,int classifyId) {
        return checkMapper.getPhotosByCheckIDAndInputId(checkId, checkInputId,classifyId);
    }

    @Override
    public List<String> getLivePhotos(Long checkID) {
        List<String> photos = checkMapper.getLivePhotos(checkID);
        return photos;
    }

    @Override
    public List<Long> getPlanCheckDataCount(HashMap<String, Object> param) {
        return checkMapper.getPlanCheckDataCount(param);
    }

    @Override
    public Map<String, Object> getPeopleStatistic(String bizOrgCode, String userId){
        return checkMapper.getPeopleStatistic(bizOrgCode, userId);
    }

    @Override
    public ESTaskDetailDto buildEsDetailData(CheckRecordParam requestParam, PlanTask planTask) {
        PlanTaskDetail planTaskDetail = planTaskDetailMapper.selectOne(requestParam.getPlanTaskId(), requestParam.getPointId());
        ESTaskDetailDto esTaskDetailDto = esTaskDetail.findById(String.valueOf(planTaskDetail.getId())).get();
        esTaskDetailDto.setPointStatus(String.valueOf(PlanTaskDetailIsFinishEnum.FINISHED.getValue()));
        JSONObject appCheckInput = esTaskDetailDto.getAppCheckInput();
        List<CheckInputParam> checkItems = requestParam.getCheckItems();
        Map<String,List<Map<String,Object>>> mapList = (Map<String,List<Map<String,Object>>>)JSON.parse(appCheckInput.toJSONString());
        List<AppCheckInputRespone> appCheckInputRespones = new ArrayList<>();
        if (!ObjectUtils.isEmpty(mapList.get("items"))){
            for (Map<String,Object> map : mapList.get("items")) {
                AppCheckInputRespone appCheckInputRespone = new AppCheckInputRespone();
                CheckInputParam checkInputId = checkItems.stream().filter(x -> x.getInputItemId()== Long.valueOf(map.get("checkInputId").toString())).collect(Collectors.toList()).get(0);
                try {
                    BeanUtils.copyProperties(appCheckInputRespone, map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                CheckInput checkInput = setInputValueByItemType(new CheckInput(), appCheckInputRespone.getDataJson(), appCheckInputRespone.getItemType(), checkInputId, null);
                if (XJConstant.NO.equals(checkInput.getIsOk())) {
                    planTask.setRiskStatus(XJConstant.RISK_NUM);
                    esTaskDetailDto.setIsRisk(XJConstant.NO_IS_RISK);

                }
                if(ObjectUtils.isEmpty(planTask.getRiskStatus()) || planTask.getRiskStatus() == XJConstant.INIT_NUM) {
                    planTask.setRiskStatus(XJConstant.NORISK_NUM);
                    esTaskDetailDto.setIsRisk(XJConstant.IS_RISK);
                }
                appCheckInputRespone.setInputValue(checkInputId.getInputValue());
                appCheckInputRespone.setPointInputImgUrls(ObjectUtils.isEmpty(checkInputId) ? new ArrayList<>() : checkInputId.getCheckInputImg());
                appCheckInputRespones.add(appCheckInputRespone);
            }
            appCheckInput.put("items", appCheckInputRespones);
        }
        esTaskDetailDto.setPointImgUrls(requestParam.getCheckRecordImg());
        esTaskDetailDto.setAppCheckInput(appCheckInput);
        esTaskDetailDto.setRemark(requestParam.getRemark());
        return esTaskDetailDto;
    }

    @Override
    public ESPlanTaskListDto buildEsTaskData(Long planTaskId,ESTaskDetailDto esTaskDetailDto) {
        ESPlanTaskListDto esPlanTaskListDto = esPlanTaskList.findById(String.valueOf(planTaskId)).get();
        String finishNum = String.valueOf(Integer.parseInt(esPlanTaskListDto.getFinshNum()) + 1);
        String unPlan = String.valueOf(Integer.parseInt(esPlanTaskListDto.getUnplan()) - 1);
        esPlanTaskListDto.setFinshNum(finishNum);
        esPlanTaskListDto.setOmission(esPlanTaskListDto.getOmission());
        esPlanTaskListDto.setUnqualified(esPlanTaskListDto.getUnqualified());
        esPlanTaskListDto.setUnplan(unPlan);
        esPlanTaskListDto.setTaskPlanNum(esPlanTaskListDto.getTaskPlanNum());
        String status = unPlan.equals("0") ? String.valueOf(PlanTaskFinishStatusEnum.FINISHED.getValue()) : esPlanTaskListDto.getFinishStatus();
        esPlanTaskListDto.setFinishStatus(status);
        return esPlanTaskListDto;
    }

    @Override
    public void saveMustData(ESTaskDetailDto esTaskDetailDto, ESPlanTaskListDto esPlanTaskListDto,PlanTask planTask) {
        esPlanTaskList.save(esPlanTaskListDto);
        esTaskDetail.save(esTaskDetailDto);
        if(esPlanTaskListDto.getFinishStatus().equals(String.valueOf(PlanTaskFinishStatusEnum.FINISHED.getValue()))) {
            // 更新统计表
            int riskNum = XJConstant.RISK_NUM == planTask.getRiskStatus() ? 1 : 0;
            int noRiskNum = XJConstant.NORISK_NUM == planTask.getRiskStatus() ? 1 : 0;
            String tabName = P_STATIC_DAY;
            // 更新统计表
            if (planTask.getPlanType().equals(String.valueOf(PlanTaskTypeStatusEnum.day.getValue()))) {
                tabName = P_STATIC_DAY;
            } else if (planTask.getPlanType().equals(String.valueOf(PlanTaskTypeStatusEnum.week.getValue()))) {
                tabName = P_STATIC_WEEK;
            } else {
                tabName = P_STATIC_WEEK;
            }
            planTaskMapper.updateSingle(tabName, riskNum, noRiskNum, planTask.getOrgCode(), planTask.getCheckDate());
        }
    }
}
