package com.yeejoin.amos.maintenance.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.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.maintenance.business.constants.XJConstant;
import com.yeejoin.amos.maintenance.business.dao.mapper.CheckMapper;
import com.yeejoin.amos.maintenance.business.dao.mapper.PlanMapper;
import com.yeejoin.amos.maintenance.business.dao.mapper.PlanTaskDetailMapper;
import com.yeejoin.amos.maintenance.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.maintenance.business.dao.mapper.RouteMapper;
import com.yeejoin.amos.maintenance.business.dao.repository.*;
import com.yeejoin.amos.maintenance.business.dto.CheckDto;
import com.yeejoin.amos.maintenance.business.dto.CheckInputDto;
import com.yeejoin.amos.maintenance.business.dto.CheckRecordDto;
import com.yeejoin.amos.maintenance.business.dto.CheckShotDto;
import com.yeejoin.amos.maintenance.business.entity.mybatis.*;
import com.yeejoin.amos.maintenance.business.feign.EquipFeignClient;
import com.yeejoin.amos.maintenance.business.param.*;
import com.yeejoin.amos.maintenance.business.service.intfc.ICheckService;
import com.yeejoin.amos.maintenance.business.service.intfc.IEquipmentHandlerService;
import com.yeejoin.amos.maintenance.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.maintenance.business.service.intfc.IPointService;
import com.yeejoin.amos.maintenance.business.util.CheckDetailInputPageParam;
import com.yeejoin.amos.maintenance.business.util.DaoCriteria;
import com.yeejoin.amos.maintenance.business.util.ToolUtils;
import com.yeejoin.amos.maintenance.business.vo.CheckAnalysisVo;
import com.yeejoin.amos.maintenance.business.vo.CheckInfoVo;
import com.yeejoin.amos.maintenance.common.enums.*;
import com.yeejoin.amos.maintenance.core.common.request.CommonPageable;
import com.yeejoin.amos.maintenance.core.common.response.*;
import com.yeejoin.amos.maintenance.core.enums.QueryOperatorEnum;
import com.yeejoin.amos.maintenance.core.util.DateUtil;
import com.yeejoin.amos.maintenance.core.util.StringUtil;
import com.yeejoin.amos.maintenance.core.util.query.BaseQuerySpecification;
import com.yeejoin.amos.maintenance.dao.entity.*;
import com.yeejoin.amos.maintenance.feign.RemoteSecurityService;
import com.yeejoin.amos.maintenance.mqtt.MqttGateway;
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.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.Bean;

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 ICheckService checkService;

    @Autowired
    private IPointService iPointService;

    @Autowired
    private IPlanTaskService planTaskService;

    @Autowired
    private ICatalogTreeDao catalogTreeDao;

    @Autowired
    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
    MqttGateway mqttGateway;

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

    @Autowired
    IRouteDao iRouteDao;

    @Autowired
    PlanServiceImpl planService;

    final String CHECK_UPDATE_TOPIC = "maintenance/date/update";


    @Override
    public Page<CheckInfoVo> getCheckInfo(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 CheckDto saveCheckRecord(CheckRecordParam recordParam, ReginParams reginParams) throws Exception {
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        //执行人-维保人员，非amos 账号
        String mtUserSeq = personIdentity.getPersonSeq();
        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());
        Route route = iRouteDao.findById(planTask.getRouteId()).orElseThrow(() -> new RuntimeException("路线不存在"));
        Check check = new Check();
        if (ObjectUtils.isEmpty(point) || ObjectUtils.isEmpty(detail)) {
            throw new Exception("前置校验不通过");
        }
        //2.加工准备的数据
        try {
            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.setPointNo(point.getPointNo());
            check.setRiskAndManage(point.getRemark());
            check.setRemark(recordParam.getRemark());
            check.setCheckTime(new Date());
            check.setBeginTime(planTask.getBeginTime());
            check.setEndTime(planTask.getEndTime());
            check.setUploadTime(new Date());
            check.setOrgCode(recordParam.getOrgCode());
            check.setUserId(mtUserSeq);
            check.setOwnerId(route.getOwnerId());
            check.setOwnerName(route.getOwnerName());
            check.setBuildingName(point.getBuildingName());
            check.setAddress(point.getAddress());
            check.setEquipmentName(point.getEquipmentName());
            check.setPlanType(detail.get("planType").toString());
            check.setUserName(personIdentity.getPersonName());
            check.setCompanyId(personIdentity.getCompanyId());
            check.setCompanyName(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;
            for (CheckInputParam item : list) {
                List<CheckShot> checkShots = new ArrayList<>();
                InputItem inputItem = inputItemDao.findById(item.getInputItemId()).get();
                CheckInput checkInput = new CheckInput();
                checkInput.setCreateDate(new Date());
                checkInput.setOrgCode(recordParam.getOrgCode());
                checkInput.setInputId(inputItem.getId());
                checkInput.setInputName(inputItem.getName());
                checkInput.setOrderNo(inputItem.getOrderNo());
                checkInput.setRemark(item.getRemark());
                //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 (CheckShotDto shotDto : item.getCheckInputShot()) {
                    CheckShot img = new CheckShot();
                    img.setCreateDate(new Date());
                    img.setPointName(check.getPointName());
                    img.setShotType(shotDto.getShotType());
                    img.setPhotoData(shotDto.getFileUrl());
                    img.setPhotoConfKey(shotDto.getPhotoConfKey());
                    checkShots.add(img);
                }
                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()));
            // 提交维保任务执行记录，关联任务详情id，作为数据回显关联查询id, 修复bug：6131
            checkItemList.forEach(checkInput -> checkInput.setCheckId(recordParam.getPlanTaskId()));
            if (!checkItemList.isEmpty()) {
                checkInputDao.saveAll(checkItemList);
            }
            List<CheckShot> allShot = new ArrayList<>();
            checkItemList.forEach(c -> {
                c.getCheckShotList().forEach(s -> {
                    s.setCheckId(c.getCheckId());
                    s.setOrgCode(recordParam.getOrgCode());
                    s.setCheckInputId(c.getId());
                });
                allShot.addAll(c.getCheckShotList());
            });
            //5.图片入库
            if (!allShot.isEmpty()) {
                checkShotDao.saveAll(allShot);
            }

            planTaskDetailMapper.finishTaskDetail(Long.parseLong(detail.get("planTaskDetailId").toString()), recordParam.getPointId(), recordParam.getPlanTaskId(), mtUserSeq);
            //6.消息广播最近维保日期
            if (StringUtil.isNotEmpty(point.getOriginalId())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("fireFacilityId", point.getOriginalId());
                jsonObject.put("maintenanceTime", check.getCheckTime());
                mqttGateway.publish(CHECK_UPDATE_TOPIC, jsonObject.toJSONString());
            }
            Plan plan = planService.queryPlanById(planTask.getPlanId());
            if (!ObjectUtils.isEmpty(plan) && plan.getIsSingleExecution()){
                // 单人执行
                updateTaskStatus(plan.getId(), reginParams.getUserModel().getUserId());
            }else {
                // 多人执行
                updateTaskStatus(plan.getId(), null);
            }

            //7.返回不合格记录
            return new CheckDto(check.getId(), unqualifiedCheckItemList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        }
    }
    private void updateTaskStatus(Long planId, String userId){
        MessageModel model = new MessageModel();
        model.setRelationId(String.valueOf(planId));
        model.setIsRead(true);
        model.setMsgType("maintenance");
        if (!ObjectUtils.isEmpty(userId)){
            model.setUserId(userId);
        }
        log.info("修改待办任务参数-->{}", JSON.toJSON(model));
         Systemctl.messageClient.update(model);
    }

    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 void delCheckById(List<Long> list) {
        checkDao.deleteBatch(list);
    }

    public static 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;
    }

    public static 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;
    }

    public static 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 int checkHasRecord(Long planTaskId, Long pointId) {
        return checkMapper.checkHasRecord(planTaskId, pointId);
    }

    @Override
    public Page<Map<String, Object>> getCheckListByOriginalId(String originalId, CommonPageable pageable) {
        Point point = iPointDao.findByOriginalId(originalId);
        if (point == null) {
            throw new RuntimeException("不存在该设备设施");
        }
        List<DaoCriteria> criterias = new ArrayList<>();
        DaoCriteria daoCriteria = new DaoCriteria();
        daoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
        daoCriteria.setPropertyName("pointId");
        daoCriteria.setValue(point.getId());
        criterias.add(daoCriteria);
        BaseQuerySpecification<Check> spec = new BaseQuerySpecification<>(criterias);
        Sort.Order idOrder = new Sort.Order(Sort.Direction.DESC, "id");
        List<Sort.Order> orders = new ArrayList<Sort.Order>();
        orders.add(idOrder);
        Sort sort = Sort.by(orders);
        pageable.setSort(sort);
        Page<Check> page = checkDao.findAll(spec, pageable);
        List<Map<String, Object>> content = page.getContent().stream().map(r -> {
            Map<String, Object> target = Bean.BeantoMap(r);
            if (StringUtil.isNotEmpty(r.getPlanType())) {
                PlanTypeEnum planTypeEnum = PlanTypeEnum.getEnumByCode(r.getPlanType());
                target.put("planTypeDesc", planTypeEnum != null ? planTypeEnum.getName() : "");
            }
            if (StringUtil.isNotEmpty(r.getIsOk())) {
                CheckStatusEnum checkStatusEnum = CheckStatusEnum.getEnum(r.getIsOk());
                target.put("isOkDesc", checkStatusEnum != null ? checkStatusEnum.getName() : "");
            }
            return target;
        }).collect(Collectors.toList());
        return new PageImpl<>(content, pageable, page.getTotalElements());
    }

    @Override
    public List<CheckInputDto> getInputDetail(String checkId) {
        List<CheckInputDto> list = this.checkMapper.queryCheckInputDetail(checkId, fileUrl);
        list.forEach(input -> {
            CheckStatusEnum statusEnum = CheckStatusEnum.getEnum(input.getIsOk());
            if (statusEnum != null) {
                input.setIsOkDesc(statusEnum.getName());
            }
        });
        return list;
    }

    @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());
            });
            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 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());
            });
            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(Map<String, Object> param) {
        Map<String, Object> charData = checkMapper.pieChartData(param);
        List<Map<String, Object>> calendarData = checkMapper.calendarData(param);
        Map<String, Object> result = new HashMap<>();
        Map<String, List<CalendarStatusCountRespone>> calendarMap = calendarData.stream().collect(Collectors.groupingBy(map -> map.get("time").toString(), Collectors.mapping(c -> {
            CalendarStatusCountRespone countRespone = new CalendarStatusCountRespone();
            countRespone.setCount(Long.parseLong(c.get("count").toString()));
            countRespone.setStatus(c.get("status").toString());
            return countRespone;
        }, Collectors.toList())));
        result.put("charData", charData);
        result.put("calendarData", calendarMap);
        return result;
    }

    @Override
    public List<CheckInfoVo> getCheckInfoListNoPage(CheckInfoPageParam param) {
        return checkMapper.getCheckInfo(param);
    }

    @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(Long[] ids) {
        return checkMapper.getSelectedCheckInfoList(ids);
    }

    @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 EquipFeignClient 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<Map<String, Object>> getCheckPage(HashMap<String, Object> params, CommonPageable page) {
        List<Map<String, Object>> content = Lists.newArrayList();
        long total = checkMapper.getCheckCount(params);
        if (total == 0) {
            return new PageImpl<>(content, page, total);
        }
        params.put("offset", page.getOffset());
        params.put("pageSize", page.getPageSize());
        content = checkMapper.getChecks(params);
        if (0 < content.size()) {
            for (Map<String, Object> map : content) {
                if (map.containsKey("isOk")) {
                    map.put("status", CheckStatusEnum.getEnum(String.valueOf(map.get("isOk"))).getName());
                }
            }
        }
        return new PageImpl<>(content, page, total);
    }

    @Override
    public Map<String, Object> getCheckDetail(String checkId) {
        Map<String, Object> result = new HashMap<>();
        result.put("facility", this.buildCheckMainInfo(checkId));
        result.put("itemList", this.getInputDetail(checkId));
        return result;
    }

    private Map<String, Object> buildCheckMainInfo(String checkId) {
        Map<String, Object> facility = checkMapper.getCheckDetail(checkId);
        if (facility.containsKey("isOk")) {
            facility.put("isOkDesc", CheckStatusEnum.getEnum(String.valueOf(facility.get("isOk"))).getName());
        }
        if (facility.containsKey("planType")) {
            PlanTypeEnum planType = PlanTypeEnum.getEnumByCode(String.valueOf(facility.get("planType")));
            facility.put("planTypeDesc", planType != null ? planType.getName() : "其他");
        }
        return facility;
    }

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