package com.yeejoin.amos.boot.module.elevator.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.QRCodeUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.ElevatorDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.ElevatorDtoNew;
import com.yeejoin.amos.boot.module.elevator.api.dto.ElevatorInsureDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.ElevatorWlInfoDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.Elevator;
import com.yeejoin.amos.boot.module.elevator.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.elevator.api.enums.EquimentEnum;
import com.yeejoin.amos.boot.module.elevator.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.elevator.api.mapper.ElevatorMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IElevatorService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.io.IOException;
import java.util.*;

/**
*  服务实现类
*
* @author tb
* @date 2021-06-01
*/
@Service
public class ElevatorServiceImpl extends BaseService<ElevatorDto, Elevator, ElevatorMapper> implements IElevatorService {


    private final Logger logger = LogManager.getLogger(ElevatorServiceImpl.class);

    @Autowired
    SourceFileServiceImpl sourceFileService;

    @Autowired
    AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    ElevatorMapper elevatorMapper;

    @Autowired
    private ElevatorServiceImpl iElevatorService;

    @Autowired
    EquipmentCategoryServiceImpl equipmentCategoryServiceImpl;

    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;


    @Autowired
    ElevatorInsureServiceImpl iElevatorInsureServiceImpl;

    @Autowired
    ESElevatorServiceImpl esElevatorService;

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    private RedisUtils redisUtils;
    private static final String LEVEL = "company";
    private static final String EQUSTATE = "EQU_STATE";
    /**
     * 保存电梯信息
     *
     * @param elevatorDto
     * @return
     */
    public ElevatorDto saveElevator(ElevatorDto elevatorDto) {
        elevatorDto = createWithModel(elevatorDto);

        // 保存附件
        sourceFileService.saveAttachments(elevatorDto.getSequenceNbr(), elevatorDto.getAttachments());
        return elevatorDto;
    }

    /**
     * 批量删除电梯信息
     *
     * @param seqStr 电梯主键（逗号分割）
     * @return
     */
    public boolean deleteBatchBySeq(String seqStr) {
        if (!ValidationUtil.isEmpty(seqStr)) {
            List<String> seqList = Lists.newArrayList(seqStr.split(","));
            LambdaUpdateWrapper<Elevator> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.in(Elevator::getSequenceNbr, seqList).set(Elevator::getIsDelete, true);
            this.update(lambdaUpdateWrapper);
            return true;
        }
        return false;
    }

    /**
     * 更新电梯信息
     *
     * @param elevatorDto
     * @return
     */
    public ElevatorDto updateElevator(ElevatorDto elevatorDto) {
        elevatorDto = updateWithModel(elevatorDto);

        // 保存附件
        sourceFileService.saveAttachments(elevatorDto.getSequenceNbr(), elevatorDto.getAttachments());
        return elevatorDto;
    }

    /**
     * 根据id查询电梯信息
     *
     * @param sequenceNbr
     * @return
     */
    public ElevatorDto selectBySeq(Long sequenceNbr) {
        ElevatorDto elevatorDto = this.queryBySeq(sequenceNbr);
        Map<String, List<AttachmentDto>> attachment = sourceFileService.getAttachments(sequenceNbr);
        // 获取附件
        elevatorDto.setAttachments(attachment);
        // 判断是否存在qrcode 如果不存在则生成qrcode
        if(attachment.get("qrCode") == null) {
            this.saveElevatorQrCode(sequenceNbr);
            attachment = sourceFileService.getAttachments(sequenceNbr);
            // 获取附件
            elevatorDto.setAttachments(attachment);
        }
        // 封装设备类别 使用场所 和 使用状态
        EquipmentCategory equipmentCategory = equipmentCategoryServiceImpl.getOne(new LambdaQueryWrapper<EquipmentCategory>().eq(EquipmentCategory::getCode,elevatorDto.getCategory()));
        if(equipmentCategory != null) {
            elevatorDto.setCategoryName(equipmentCategory.getName());
        }

        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "USE_SITE_CATEGORY").eq("code", elevatorDto.getUseSiteCategory());
        DataDictionary useSiteCategory = iDataDictionaryService.getOne(queryWrapper);
        if(useSiteCategory != null) {
            elevatorDto.setUseSiteCategoryName(useSiteCategory.getName());
        }
        if("1".equals(elevatorDto.getUseStatus())) {
            elevatorDto.setUseStatusStr("在用");
        } else {
            elevatorDto.setUseStatusStr("停用");
        }
        // 获取保险信息
        ElevatorInsureDto elevatorInsureDto = iElevatorInsureServiceImpl.getInsureInfoByElevatorCode(elevatorDto.getRegisterCode());
        if(elevatorInsureDto == null ) {
            elevatorInsureDto = new ElevatorInsureDto();
        }
        elevatorDto.setElevatorInsureDto(elevatorInsureDto);
        return elevatorDto;
    }

    public Map<String, Object> selectByRecord(String sequenceNbr) {
        Map<String, Object> map = baseMapper.selectByRecord(sequenceNbr);
        Map<String, Object> designFiles = baseMapper.selectFiles(sequenceNbr);
        ArrayList<Map<String, Object>> designFilesList = new ArrayList<>();
        changeData(designFiles, "DESIGN_DOC", designFilesList);
        changeData(designFiles, "DESIGN_STANDARD", designFilesList);
        changeData(designFiles, "FACTORY_STANDARD", designFilesList);
        changeData(designFiles, "TYPE_TEST_CREDENTIAL", designFilesList);
        changeData(designFiles, "PRODUCT_QUALITY_YIELD_PROVE", designFilesList);
        changeData(designFiles, "INS_USE_MAINTAIN_EXPLAIN", designFilesList);
        changeData(designFiles, "SUPERVISION_AGENCY_CREDENTIAL", designFilesList);
        map.put("designFiles", designFilesList);
        Map<String, Object> registerFiles = baseMapper.selectRegisterFiles(sequenceNbr);
        ArrayList<Map<String, Object>> registerFilesList = new ArrayList<>();
        changeData(registerFiles, "USE_REGISTRATION_CERTIFICATE", registerFilesList);
        changeData(registerFiles, "USE_SIGN", registerFilesList);
        changeData(registerFiles, "PRODUCT_PHOTO", registerFilesList);
        map.put("registerFiles", registerFilesList);
        Map<String, Object> maintenanceInspectionFiles = baseMapper.selectMaintenanceInspectionFiles(sequenceNbr);
        ArrayList<Map<String, Object>> maintenance = new ArrayList<>();
        ArrayList<Map<String, Object>> inspection = new ArrayList<>();
        changeData(maintenanceInspectionFiles, "maintenanceFile", maintenance);
        map.put("maintenanceFile", maintenance);
        changeData(maintenanceInspectionFiles, "inspectionFile", inspection);
        map.put("inspectionFile", inspection);

        return map;

    }

    private void changeData(Map<String, Object> data, String column, ArrayList<Map<String, Object>> maps) {
        if (!ObjectUtils.isEmpty(data) && data.containsKey(column)) {
            JSONArray list = JSON.parseArray(String.valueOf(data.get(column)));
            for (Object o : list) {
                Map<String, Object> objectMap = (Map<String, Object>) o;
                maps.add(objectMap);
            }
        }

    }

    @Override
    public Map<String,Object> selectByAlertId(Long alertId) {
        AlertCalledDto alertCalledDto = alertCalledServiceImpl.queryBySeq(alertId);
        if (ValidationUtil.isEmpty(alertCalledDto)
                || ValidationUtil.isEmpty(alertCalledDto.getDeviceId())) {
	        throw new BadRequest("警情不存在或者设备编码不存在");
        }
        // 设备类型 和 编码 确定设备的使用单位或者维保单位
        String equipmentClassificationCode = alertCalledDto.getEquipmentClassificationCode();
        String deviceId = alertCalledDto.getEquipmentId();
        // 目前只有电梯类型
        Elevator elevator = new Elevator();
        elevator.setOriginalId(deviceId);
        Map<String,Object> map =  iElevatorService.selectElevator(elevator);
//        LambdaQueryWrapper<Elevator> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Elevator::getSequenceNbr, deviceId);
//        Elevator elevator = this.getOne(queryWrapper);
        if (ValidationUtil.isEmpty(map)) {
	        throw new BadRequest("设备未找到");
        }
        return map;
    }

    @Override
    public String saveElevatorQrCode(Long elevatorId) {
        // 二维码生成规则
        JSONObject qrString = new JSONObject();
        Elevator elevator = this.getById(elevatorId);
        if(elevator == null) {
            throw new BadRequest("未找到电梯数据");
        }
        qrString.put("elevatorId",elevator.getSequenceNbr());
        qrString.put("rescueCode",elevator.getRescueCode());
        byte[] bytes = QRCodeUtil.generateQRCodeImageByteData(qrString.toJSONString(), 480);
        MultipartFile file = new MockMultipartFile("elevator_" + elevator.getSequenceNbr() + ".png","elevator_" + elevator.getSequenceNbr() + ".png","application/octet-stream" ,bytes);
        FeignClientResult<Map<String, String>> result =  Systemctl.fileStorageClient.updateCommonFile(file);
        Map<String, String> map = result.getResult();
        if(map.isEmpty()) {
            logger.error("未生成二维码文件");
            throw new BadRequest("未生成二维码文件");
        }
        String filePath = "";
        for(Map.Entry<String,String> fileResult : map.entrySet()) {
            filePath = fileResult.getKey();
        }
        // 保存qrCode
        List<AttachmentDto> qrCode = new ArrayList<>();
        AttachmentDto temp = new AttachmentDto();
        temp.setName("elevator_" + elevator.getSequenceNbr() + ".png");
        temp.setType("image");
        temp.setUrl(filePath);
        qrCode.add(temp);
        Map<String, List<AttachmentDto>> attachmentMap = sourceFileService.getAttachments(elevatorId);
        attachmentMap.put(TzsCommonParam.QR_CODE,qrCode);
        sourceFileService.saveAttachments(elevatorId,attachmentMap);
        return filePath;
    }

    @Override
    public List<ElevatorDto> selectExportData(String exportId) {
        List<String> ids = null;
        if(StringUtils.isNotEmpty(exportId)) {
            String[] idStr = exportId.split(",");
            ids = Arrays.asList(idStr);
        }
        return baseMapper.selectExportData(ids);
    }


    @Override
    public List<Map<String,Object>> selectElevatorList(Elevator elevator) {
        return elevatorMapper.selectElevatorList(elevator);
    }

    @Override
    public Map<String,Object> selectElevator(Elevator elevator) {
        return elevatorMapper.selectElevator(elevator);
    }


    @Override
    public List<Map<String, Object>> selectElevatorEsList(int pageNum,int pageSize) {
        return elevatorMapper.selectElevatorEsList(pageNum,pageSize);
    }

    @Override
    public Integer selectUseInfoCount() {
        return elevatorMapper.selectUseInfoCount();
    }

    @Override
    public List<Map<String,Object>> selectMtByAlertId(String sequenceNbr) {
        return elevatorMapper.selectMtByAlertId(sequenceNbr);
    }

    @Override
    public Map<String, Object> selectUseUnitByAlertId(String sequenceNbr) {
        return elevatorMapper.selectUseUnitByAlertId(sequenceNbr);
    }


    @Override
    public Page<Map<String, Object>> selectElevators(Page<Map<String, Object>> page, ElevatorDto dto) {
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        dto.setOrgCode(companyModels.get(0).getOrgCode());
        return elevatorMapper.selectElevators(page, dto);
    }

    @Override
    public List<ElevatorDtoNew> selectExportDataNew(ElevatorDto dto) {
        return baseMapper.selectExportDataNew(dto, dto.getIds());
    }

    public Page<JSONObject> queryByKeys(JSONObject map) {
//        //根据当前登录人查询
        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquimentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }
        JSONObject object = getCompanyType().get(0);
        String level = object.getString("level");
        String code = object.getString("orgCode");
        String companyCode = object.getString("companyCode").contains("_") ?
                object.getString("companyCode").split("_")[1] : object.getString("companyCode");
        if (!ValidationUtil.isEmpty(level)) {
            if (LEVEL.equals(level)) {
                //企业
                map.put("USE_UNIT_CREDIT_CODE", companyCode);
            } else {
                //监管单位
                map.put("ORG_BRANCH_CODE", code);
            }
        }
        Page<JSONObject> result = new Page<>(map.getInteger("number"), map.getInteger("size"));
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        //通用匹配规则，条件构建
        //SEQUENCE_NBR
        if (!ObjectUtils.isEmpty(map.getString("SEQUENCE_NBR"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("SEQUENCE_NBR"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("SEQUENCE_NBR", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("ORG_BRANCH_NAME"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ORG_BRANCH_NAME"));
            query.must(QueryBuilders.matchPhraseQuery("ORG_BRANCH_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("ORG_BRANCH_CODE"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ORG_BRANCH_CODE"));
            query.must(QueryBuilders.matchPhrasePrefixQuery("ORG_BRANCH_CODE", test));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_NAME"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_NAME"));
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_CREDIT_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("USE_UNIT_CREDIT_CODE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST", "*" + test + "*"));
            boolMust.must(meBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString("USE_ORG_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_ORG_CODE").toLowerCase());
            meBuilder.must(QueryBuilders.matchPhraseQuery("USE_ORG_CODE", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("CODE96333"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("CODE96333"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("CODE96333", "*" + test + "*"));
            boolMust.must(meBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString("USE_PLACE"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_PLACE"));
            query.must(QueryBuilders.matchPhraseQuery("USE_PLACE", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("ADDRESS"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ADDRESS"));
            query.must(QueryBuilders.matchPhraseQuery("ADDRESS", "*" + test + "*"));
            boolMust.must(query);
        }

        if (!ObjectUtils.isEmpty(map.getString("STATUS"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("STATUS"));
            if (test.contains("非")) {
                meBuilder.must(QueryBuilders.matchPhraseQuery("STATUS", test.replace("非", "")));
                boolMust.mustNot(meBuilder);
            } else {
                meBuilder.must(QueryBuilders.matchPhraseQuery("STATUS", test));
                boolMust.must(meBuilder);
            }
        }
        if (!ObjectUtils.isEmpty(map.getString("CLAIM_STATUS"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("CLAIM_STATUS"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("STATUS", test));
            boolMust.must(meBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_NAME"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_NAME"));
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("MAINTAIN_UNIT"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("MAINTAIN_UNIT"));
            query.must(QueryBuilders.matchPhraseQuery("MAINTAIN_UNIT", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("SAFETY_MANAGER"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("SAFETY_MANAGER"));
            query.must(QueryBuilders.matchPhraseQuery("SAFETY_MANAGER", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("PHONE"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("PHONE"));
            query.must(QueryBuilders.matchPhraseQuery("PHONE", "*" + test + "*"));
            boolMust.must(query);
        }
        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((map.getInteger("number") - 1) * map.getInteger("size"));
        builder.size(map.getInteger("size"));
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (org.elasticsearch.search.SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");
                if (!ValidationUtil.isEmpty(dto2.get(EQUSTATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQUSTATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQUSTATE, status);
                }
                if (!ValidationUtil.isEmpty(dto2.get("ADDRESS"))){
                    String address = StringUtils.substringAfter(String.valueOf(dto2.get("ADDRESS")), "/");
                    if (!ObjectUtils.isEmpty(address)){
                        dto2.put("ADDRESS", address);
                    }
                }
                list.add(dto2);
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 获取当前登录人单位类型
     *
     * @return
     */

    public List<JSONObject> getCompanyType() {


        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        List<CompanyModel> companys = reginParams.getUserModel().getCompanys();

        List<JSONObject> objectList = new ArrayList<>();
        for (CompanyModel company : companys) {
            JSONObject object = new JSONObject();
            object.put("level", company.getLevel());
            object.put("orgCode", company.getOrgCode());
            object.put("companyCode", company.getCompanyCode());
            objectList.add(object);
        }
        return objectList;
    }

    public List<ElevatorWlInfoDto> queryElevatorList(ElevatorWlInfoDto esElevatorDto) {
       return elevatorMapper.queryElevatorList(esElevatorDto.getAddress(),
                esElevatorDto.getRegisterCode(),esElevatorDto.getRescueCode(),
                esElevatorDto.getType(), !ValidationUtil.isEmpty(esElevatorDto.getDealStatus()) ? Integer.parseInt(esElevatorDto.getDealStatus()) :null
                , esElevatorDto.getSequenceNbr(),(esElevatorDto.getPage()-1)*esElevatorDto.getSize(), esElevatorDto.getSize());
    }

    public List<ElevatorWlInfoDto> queryElevatorListDetails(ElevatorWlInfoDto esElevatorDto) {
        return elevatorMapper.queryElevatorListDetails(
                esElevatorDto.getSequenceNbr());
    }

    public int queryElevatorListCount() {
        return elevatorMapper.queryElevatorListCount();
    }
}
