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

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.bo.ReginParams;
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.supervision.business.constants.XJConstant;
import com.yeejoin.amos.supervision.business.dao.mapper.*;
import com.yeejoin.amos.supervision.business.dao.repository.*;
import com.yeejoin.amos.supervision.business.dto.CheckInputItemDto;
import com.yeejoin.amos.supervision.business.dto.CheckRecordDto;
import com.yeejoin.amos.supervision.business.dto.HiddenDangerDto;
import com.yeejoin.amos.supervision.business.entity.mybatis.*;
import com.yeejoin.amos.supervision.business.feign.DangerFeignClient;
import com.yeejoin.amos.supervision.business.feign.EquipFeign;
import com.yeejoin.amos.supervision.business.param.*;
import com.yeejoin.amos.supervision.business.service.intfc.*;
import com.yeejoin.amos.supervision.business.util.CheckDetailInputPageParam;
import com.yeejoin.amos.supervision.business.util.ToolUtils;
import com.yeejoin.amos.supervision.business.vo.CheckAnalysisVo;
import com.yeejoin.amos.supervision.business.vo.CheckInfoVo;
import com.yeejoin.amos.supervision.business.vo.CheckVo;
import com.yeejoin.amos.supervision.common.enums.*;
import com.yeejoin.amos.boot.biz.common.enums.RuleTypeEnum;
import com.yeejoin.amos.supervision.core.common.dto.DangerDto;
import com.yeejoin.amos.supervision.core.common.request.CommonPageable;
import com.yeejoin.amos.supervision.core.common.response.*;
import com.yeejoin.amos.supervision.core.util.DateUtil;
import com.yeejoin.amos.supervision.core.util.StringUtil;
import com.yeejoin.amos.supervision.dao.entity.*;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.common.util.CollectionUtils;
import org.assertj.core.util.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.typroject.tyboot.core.foundation.utils.Bean;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private CheckMapper checkMapper;

    @Autowired
    private IPointService iPointService;

    @Autowired
    private ICatalogTreeDao catalogTreeDao;

    @Resource
    ICheckShotDao checkShotDao;

    @Autowired
    PlanTaskMapper planTaskMapper;

    @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
    IPointDao iPointDao;

    @Autowired
    IPlanTaskService planTaskService;

    @Autowired
    private IPlanService planService;

    @Autowired
    private RulePlanService rulePlanService;

    @Autowired
    DangerFeignClient DangerFeignClient;

    @Autowired
    HiddenDangerMapper hiddenDangerMapper;

    @Autowired
    IHiddenDangerDao hiddenDangerDao;

    @Autowired
    IPlanService iPlanService;

    @Autowired
    ICheckReportService iCheckReportService;

    private final int HTTP_OK_STATUS = 200;

    @Value("${file.url}")
    private String fileUrl;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    IHiddenDangerService iHiddenDangerService;

    @Override
    public Page<CheckInfoVo> getCheckInfo(String toke, String product, String appKey, CheckInfoPageParam param) {
        long total = checkMapper.countCheckInfoData(param);
        List<CheckInfoVo> content = Lists.newArrayList();
        if (total == 0) {
            return new PageImpl<>(content, param, total);
        }
        content = checkMapper.getCheckInfo(param);
        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.save(check);
        checkShotDao.saveAll(imgList);
    }

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

    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(XJConstant.YES);
                    } else {
                        checkInput.setIsOk(XJConstant.NO);
                        checkInput.setInputValue(XJConstant.NOT);
                    }
                    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 AppPointCheckRespone queryCheckPointDetail(String toke, String product, String appKey, 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(fileUrl + 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());
                });
                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) {
        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(fileUrl + 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.setDepartmentName(pointCheckDetailBo.getDepartmentName());
            //pointCheckRespone.setUsername(pointCheckDetailBo.getUsername());
//            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.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(fileUrl + 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 + "')");
        }
        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 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 (userId != null && !userId.trim().equals("")) {
                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();
    }

    @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", d.getSequenceNbr());
            dept.put("key", d.getSequenceNbr());
            dept.put("value", d.getSequenceNbr());
            dept.put("state", "open");
            dept.put("type", "department");
            dept.put("orgCode", 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("orgCode") + ""));
                    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;
    }

    @Autowired
    private EquipFeign equipment;

    @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"));

                    }
                    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 Map<String, CheckRecordDto> obtainLastCheckRecord(String[] relationIds) {
        Map<String, CheckRecordDto> checkRecordMap = new HashMap<>();
        for (String relationId : relationIds) {
            List<Point> points = iPointDao.findAllByOriginalId(relationId);
            if (points.isEmpty()) {
                continue;
            }
            Point point = points.get(0);
            if (StringUtil.isNotEmpty(point.getLastCheckId())) {
                Check check = checkDao.getById(Long.parseLong(point.getLastCheckId()));
                CheckRecordDto checkRecordDto = new CheckRecordDto();
                Bean.copyExistPropertis(check, checkRecordDto);
                checkRecordMap.put(relationId, checkRecordDto);
            }
        }
        return checkRecordMap;
    }

    @Override
    public Page<HashMap<String, Object>> getPlanExecuteInfo(HashMap<String, Object> map, CommonPageable page) {
        List<HashMap<String, Object>> content = org.assertj.core.util.Lists.newArrayList();
        long total = checkMapper.getItemCount(map);
        if (total == 0) {
            return new PageImpl<>(content, page, total);
        }
        map.put("offset", page.getOffset());
        map.put("pageSize", page.getPageSize());
        content = checkMapper.getCheckItems(map);
        content.forEach(c -> {
            if (c.containsKey("finishStatus")) {
                String finishStatusDesc = CheckItemFinishStatusEnum.getName(c.get("finishStatus").toString());
                c.put("finishStatus", finishStatusDesc);
            }
        });
        return new PageImpl<>(content, page, total);
    }

    @Override
    public List<Map<String, Object>> getPlanExecuteStates() {
        return CheckItemFinishStatusEnum.getEnumList();
    }

    @Override
    public List<Map<String, Object>> getPlanExecuteTeams() {
        List<Map<String, Object>> list = checkMapper.getPlanExecuteTeams();
        return list;
    }

    @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"));
                }
            }
        });
        return content;
    }

    @Override
    public CheckDetailBo getCheckDetailById(CheckDetailInputPageParam param) {
        long checkID = param.getCheckID();
        CheckDetailBo checkDetailBo = checkMapper.getCheckDetailByID(param);
        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 -> {
                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 -> {
                    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) {
        return checkMapper.getLivePhotos(checkID);
    }

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

    @Override
    @Transactional
    public List<CheckInputItemDto> saveCheckRecord(CheckRecordParam recordParam, ReginParams reginParams) throws Exception {
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (ObjectUtils.isEmpty(reginParams.getUserModel()) && ObjectUtils.isEmpty(reginParams.getCompany()) && ObjectUtils.isEmpty(personIdentity)) {
            throw new RuntimeException("获取用户信息失败");
        }
        String mtUserSeq = personIdentity.getPersonSeq();
        String userName = personIdentity.getPersonName();

        PlanTask planTask = planTaskService.selectPlanTaskStatus(recordParam.getPlanTaskId());
        Map detail = planTaskDetailMapper.findPlanTaskByTaskIdAndPointId(recordParam.getPlanTaskId(), recordParam.getPointId());
        //1.前置校验
        this.checkCanFinishTask(mtUserSeq, planTask, recordParam.getPointId());
        Point point = iPointService.queryPointById(recordParam.getPointId());
        Check check = new Check();
        if (ObjectUtils.isEmpty(point) || ObjectUtils.isEmpty(detail)) {
            throw new Exception("前置校验不通过");
        }
        //2.加工准备的数据
        try {
            // 检查记录表中是否有该点记录
            Check checkByPointId = checkDao.findByPlanTaskIdAndPointId(recordParam.getPlanTaskId(), recordParam.getPointId());
            if (ObjectUtils.isEmpty(checkByPointId)) {
                // 新增
                check.setPlanTaskDetailId(Long.parseLong(detail.get("planTaskDetailId").toString()));
                check.setRouteId(Long.parseLong(detail.get("routeId").toString()));
                check.setRouteName(detail.get("routeName").toString());
                check.setPlanTaskId(recordParam.getPlanTaskId());
                check.setPlanId(planTask.getPlanId());
                check.setPlanName(detail.get("planName").toString());
                check.setPointName(point.getName());
                check.setPointId(point.getId());
                check.setRemark(recordParam.getRemark());
                check.setOrgCode(recordParam.getOrgCode());
                check.setUserId(mtUserSeq);
                check.setCheckTime(new Date());
                check.setUploadTime(new Date());
                check.setUserName(personIdentity.getPersonName());
                check.setCompanyId(reginParams.getCompany().getSequenceNbr().toString());
                check.setCompanyName(reginParams.getCompany().getCompanyName());
                check.setDepId(personIdentity.getCompanyId());
                check.setDepName(personIdentity.getCompanyName());
            } else {
                // 更新
                check = checkByPointId;
                check.setCheckTime(new Date());
                check.setUploadTime(new Date());
                String userId = check.getUserId();
                String userName1 = check.getUserName();
                String companyId = check.getCompanyId();
                String companyName = check.getCompanyName();
                String depId = check.getDepId();
                String depName = check.getDepName();
                if (!userId.contains(mtUserSeq)) {
                    check.setUserId(userId + "," + mtUserSeq);
                    check.setUserName(userName1 + "," + userName);
                }
                if (!companyId.contains(reginParams.getCompany().getSequenceNbr().toString())) {
                    check.setCompanyId(companyId + "," + reginParams.getCompany().getSequenceNbr().toString());
                }
                if (!companyName.contains(reginParams.getCompany().getCompanyName())) {
                    check.setCompanyName(companyName + "," + reginParams.getCompany().getCompanyName());
                }
                if (!depId.contains(personIdentity.getCompanyId())) {
                    check.setDepId(depId + "," + personIdentity.getCompanyId());
                }
                if (!depName.contains(personIdentity.getCompanyName())) {
                    check.setDepName(depName + "," + personIdentity.getCompanyName());
                }
            }

            List<CheckInputParam> list = recordParam.getCheckItems();
            List<CheckInput> checkItemList = new ArrayList<>();
            List<Map<String, Object>> unqualifiedCheckItemList = Lists.newArrayList();
            StringBuilder error = new StringBuilder();
            int score = 0;
            int size = 0;
            for (CheckInputParam item : list) {
                List<CheckShot> checkShots = new ArrayList<>();
                InputItem inputItem = inputItemDao.getOne(item.getInputItemId());
                CheckInput checkInput = new CheckInput();
                if (!ObjectUtils.isEmpty(item.getId()) && item.getId() != 0) {
                    checkInput.setId(item.getId());
                    // 更新操作，将该点下所有图片删除，其余更新
                    checkShotDao.deleteByCheckInputId(item.getId());
                } else {
                    size += 1;
                }
                checkInput.setCreateDate(new Date());
                checkInput.setOrgCode(recordParam.getOrgCode());
                checkInput.setInputId(inputItem.getId());
                checkInput.setInputName(inputItem.getName());
                checkInput.setOrderNo(inputItem.getOrderNo());
                checkInput.setRemark(item.getRemark());
                checkInput.setUserId(item.getUserId());
                checkInput.setUserName(item.getUserName());
                checkInput.setAccompanyUserId(item.getAccompanyUserId());
                checkInput.setAccompanyUserName(item.getAccompanyUserName());
                checkInput.setDepId(item.getDepId());
                checkInput.setDepName(item.getDepName());
                //1.校验结果
                if (XJConstant.INPUT_ITEM_SELECT.equals(inputItem.getItemType())) {
                    paraseSelect(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                } else if (XJConstant.INPUT_ITEM_NUMBER.equals(inputItem.getItemType())) {
                    paraseNumber(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());

                } else if (XJConstant.INPUT_ITEM_TEXT.equals(inputItem.getItemType())) {
                    paraseText(checkInput, inputItem.getDataJson(), item, inputItem.getIsScore());
                }
                if (XJConstant.NO.equals(checkInput.getIsOk())) {
                    error.append(inputItem.getName()).append("=").append(ObjectUtils.isEmpty(item.getInputValue()) ? "" : item.getInputValue()).append(";");
                    checkInput.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
                    Map<String, Object> unCheckMap = Maps.newHashMap();
                    unCheckMap.put("itemId", item.getInputItemId());
                    unCheckMap.put("routeId", check.getRouteId());
                    unCheckMap.put("pointId", point.getId());
                    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());
                score += checkInput.getScore();
                for (CheckShot shotDto : item.getCheckInputShot()) {
                    CheckShot img = new CheckShot();
                    img.setCreateDate(new Date());
                    img.setPointName(check.getPointName());
                    img.setShotType(shotDto.getShotType());
                    img.setPhotoData(shotDto.getPhotoData());
                    checkShots.add(img);
                }

                // 安全隐患个数
                int safetyDangerNum = 0;
                // 重大隐患个数
                int majorDangerNum = 0;
                // 遍历点下的隐患列表
                for (DangerDto dangerDto : item.getDangerList()) {
                    if (!dangerDto.getDeleted()) {
                        if ("majorDanger".equals(dangerDto.getDangerLevel())) {
                            majorDangerNum += 1;
                        }
                        safetyDangerNum += 1;
                    }
                }
                checkInput.setSafetyDangerNum(safetyDangerNum);
                checkInput.setMajorDangerNum(majorDangerNum);
                checkInput.setDangerDtoList(item.getDangerList());
                checkInput.setCheckShotList(checkShots);
                checkItemList.add(checkInput);
            }
            if (!ObjectUtils.isEmpty(error.toString()) && error.toString().endsWith(";")) {
                error.substring(0, error.length() - 1);
                check.setIsOk(CheckStatusEnum.UNQUALIFIED.getCode());
            } else {
                check.setIsOk(CheckStatusEnum.QUALIFIED.getCode());
            }
            check.setError(error.toString());
            //计划外巡检是否计分 ，计划内默认都是计分
            if (XJConstant.POINT_OK_SCORE.equals(point.getIsScore()) || recordParam.getPlanTaskId() != null) {
                check.setScore(score);
            } else {
                check.setScore(Integer.parseInt(XJConstant.POINT_NOT_SCORE));
            }
            //3.主表入库
            check = checkDao.save(check);
            //冗余记录最新一次检查记录，方便其他业务查询--当前为维保到期时间用到
            point.setLastCheckId(String.valueOf(check.getId()));
            iPointDao.save(point);
            Check finalCheck = check;


            //4.检查项入库
            checkItemList.forEach(checkInput -> checkInput.setCheckId(finalCheck.getId()));
            if (!checkItemList.isEmpty()) {
                checkInputDao.saveAll(checkItemList);
            }
            List<CheckShot> allShot = new ArrayList<>();
            List<DangerDto> allDanger = new ArrayList<>();
            List<CheckInputItemDto> checkInputItemDtoList = new ArrayList<>();
            checkItemList.forEach(c -> {
                CheckInputItemDto checkInputItemDto = new CheckInputItemDto();
                checkInputItemDto.setCheckId(c.getCheckId());
                checkInputItemDto.setCheckInputId(c.getId());
                checkInputItemDto.setRoutPointItemId(c.getRoutePointItemId());
                checkInputItemDtoList.add(checkInputItemDto);
                c.getCheckShotList().forEach(s -> {
                    s.setCheckId(c.getCheckId());
                    s.setOrgCode(recordParam.getOrgCode());
                    s.setCheckInputId(c.getId());
                });
                allShot.addAll(c.getCheckShotList());

                // 隐患
                c.getDangerDtoList().forEach(d -> {
                    d.setBizId(c.getId());
                    d.setBizType(contextPath.substring(1));
                    d.setCheckMode(DangerHandleTypeEnum.SUPERVISION.getCode());
                    d.setInputItemName(c.getInputName());
                });
                allDanger.addAll(c.getDangerDtoList());

            });

            // 5.图片入库
            if (!allShot.isEmpty()) {
                checkShotDao.saveAll(allShot);
            }

            // 更改状态
            String planTaskStatus = recordParam.getPlanTaskStatus();
            planTaskDetailMapper.finishTaskDetail(Long.parseLong(detail.get("planTaskDetailId").toString()), recordParam.getPointId(),
                    recordParam.getPlanTaskId(), mtUserSeq, userName, size, planTaskStatus);

            Plan plan = planService.queryPlanById(planTask.getPlanId());
            // 计划完成，规则推送消息
            if (PlanStatusEnum.COMPLETED.getValue() == plan.getStatus()) {
                rulePlanService.addPlanRule(plan, null, RuleTypeEnum.计划完成, null);
            }

            // p_plan_task_detail更新隐患个数
            planTaskDetailMapper.updateDanger(Long.parseLong(detail.get("planTaskDetailId").toString()));

            // 隐患入库
            if (!ObjectUtils.isEmpty(allDanger)) {
                saveDanger(allDanger, planTask, check, recordParam);
            }

            // 任务完成后生成检查报告
            iCheckReportService.genCheckReport(planTask);

            return checkInputItemDtoList;
        } catch (Exception e) {
            throw new Exception(e.getMessage(), e);
        }
    }

    /**
     * 保存隐患数据
     */
    private void saveDanger(List<DangerDto> allDanger, PlanTask planTask, Check check, CheckRecordParam recordParam) {
        if (!ObjectUtils.isEmpty(allDanger)) {

            // 根据bizId删除关系表
            List<Long> collect = allDanger.stream().map(DangerDto::getId).collect(Collectors.toList());
            hiddenDangerDao.deleteByDangerIdIn(collect);
            allDanger.forEach(dangerDto -> {
                HiddenDangerDto hiddenDangerDto = new HiddenDangerDto();
                hiddenDangerDto.setPlanId(planTask.getPlanId());
                hiddenDangerDto.setPointId(recordParam.getPointId());
                hiddenDangerDto.setCheckInputId(dangerDto.getBizId());
                hiddenDangerDto.setInputItemName(dangerDto.getInputItemName());
                hiddenDangerDto.setDangerType(DangerHandleTypeEnum.SUPERVISION.getCode());
                try {
                    dangerDto.setBizInfo(iHiddenDangerService.buildBizInfo(hiddenDangerDto));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw new RuntimeException("组织基本数据失败");
                }
            });
            // 1.feign调用保存隐患
            log.info(String.format("隐患参数：%s", JSON.toJSONString(allDanger)));
            FeignClientResult<List<DangerDto>> listFeignClientResult = DangerFeignClient.saveOrUpdateBatch(allDanger,recordParam.getPlanTaskStatus());
            if (ObjectUtils.isEmpty(listFeignClientResult.getResult()) || listFeignClientResult.getStatus() != HTTP_OK_STATUS) {
                throw new RuntimeException(listFeignClientResult.getDevMessage());
            }
            List<DangerDto> result = listFeignClientResult.getResult();
            if (!ObjectUtils.isEmpty(result)) {
                // 2.根据保存返回的隐患主键id,保存p_check_input_danger数据
                List<HiddenDanger> hiddenDangerList = result.stream().filter(d -> !d.getDeleted()).map(dangerDto -> {
                    HiddenDanger hiddenDanger = new HiddenDanger();
                    hiddenDanger.setLatentDangerId(dangerDto.getId());
                    hiddenDanger.setPointId(recordParam.getPointId());
                    hiddenDanger.setPlanId(planTask.getPlanId());
                    hiddenDanger.setCheckId(check.getId());
                    hiddenDanger.setCheckInputId(dangerDto.getBizId());
                    hiddenDanger.setDangerType(DangerHandleTypeEnum.SUPERVISION.getCode());
                    hiddenDanger.setDangerTypeName(DangerHandleTypeEnum.SUPERVISION.getName());
                    return hiddenDanger;
                }).collect(Collectors.toList());
                // 批量保存数据
                hiddenDangerDao.saveAll(hiddenDangerList);
            }
        }
    }

    private void checkCanFinishTask(String mtUserSeq, PlanTask planTask, Long pointId) throws Exception {
        int status;
//        int count = checkService.checkHasRecord(planTask.getId(), pointId);
//        if (count > 0) {
//            throw new RuntimeException("任务已执行，不能重复执行");
//        }
        if (!ToolUtils.transBeanList(planTask.getUserId()).contains(mtUserSeq)) {
            throw new RuntimeException("无权执行该任务");
        }
        status = planTask.getFinishStatus();
        if (status == PlanTaskFinishStatusEnum.OVERTIME.getValue()) {
            throw new RuntimeException("任务已超时，上传失败！");
        } else if (status == PlanTaskFinishStatusEnum.FINISHED.getValue()) {
            throw new RuntimeException("任务已完成！");
        }
        Date checkTime = new Date();
        Date beginTime = DateUtil.getLongDate(planTask.getBeginTime());
        Date endTime = DateUtil.getLongDate(planTask.getEndTime());
        int beginCompareTo = checkTime.compareTo(beginTime);
        int endCompareTo = checkTime.compareTo(endTime);
        if (beginCompareTo < 0 || endCompareTo > 0) {
            throw new RuntimeException("请在计划时间内完成任务！");
        }
    }

    @Override
    public int checkHasRecord(Long planTaskId, Long pointId) {
        return checkMapper.checkHasRecord(planTaskId, pointId);
    }

    @Override
    public Page<CheckVo> queryPage(CheckPageParam param) {
        long total = checkMapper.queryPageCount(param);
        List<CheckVo> content = checkMapper.queryPage(param);
        Page<CheckVo> result = new PageImpl<CheckVo>(content, param, total);
        return result;
    }

    @Override
    public List<String> getPictureByCheckId(String checkId, String id) {
        return checkMapper.getPictureByCheckId(checkId,id);
    }
}
