package com.usky.iot.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.BeanMapperUtils;
import com.usky.common.core.util.UUIDUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.*;
import com.usky.iot.mapper.BaseBuildMapper;
import com.usky.iot.mapper.BaseFacilityTypeMapper;
import com.usky.iot.mapper.BaseGgpFacilityMapper;
import com.usky.iot.service.*;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.iot.service.BaseFacilityDeviceService;
import com.usky.iot.service.BaseGgpFacilityService;
import com.usky.iot.service.vo.*;
import com.usky.system.model.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 地理信息 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-06-02
 */
@Service
public class BaseGgpFacilityServiceImpl extends AbstractCrudService<BaseGgpFacilityMapper, BaseGgpFacility> implements BaseGgpFacilityService {
    @Autowired
    private BaseFacilityDeviceService baseFacilityDeviceService;
    @Autowired
    private BaseFacilityBuildService baseFacilityBuildService;
    @Autowired
    private DmpDeviceInfoService dmpDeviceInfoService;
    @Autowired
    private BaseBuildMapper baseBuildMapper;
    @Autowired
    private BaseFacilityTypeMapper baseFacilityTypeMapper;
    @Autowired
    private DmpProductInfoService dmpProductInfoService;
    @Autowired
    private BaseAlarmService baseAlarmService;

    @Override
    public boolean add(BaseGgpFacility baseGgpFacility) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        List<BaseFacilityType> typeList = baseFacilityTypeMapper.typeList(baseGgpFacility.getFacilityType());
        baseGgpFacility.setFacilityNum(typeList.get(0).getTypeAbbrevia()+'-'+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date));
        baseGgpFacility.setCreator(SecurityUtils.getUsername());
        baseGgpFacility.setCreateTime(LocalDateTime.now());
        baseGgpFacility.setTenantId(SecurityUtils.getTenantId());
        return this.save(baseGgpFacility);
    }

    @Override
    public void update(BaseGgpFacility baseGgpFacility) {
        baseGgpFacility.setUpdateTime(LocalDateTime.now());
        baseGgpFacility.setUpdatePerson(SecurityUtils.getUsername());
        this.updateById(baseGgpFacility);
    }

    @Override
    public CommonPage<BaseGgpFacility> page(BaseGgpFacilityRequest piRequest) {
        IPage<BaseGgpFacility> page = new Page<>(piRequest.getCurrent(), piRequest.getSize());
        LambdaQueryWrapper<BaseGgpFacility> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .like(StringUtils.isNotBlank(piRequest.getFacilityName()),BaseGgpFacility::getFacilityName,
                        piRequest.getFacilityName())
                .eq(StringUtils.isNotBlank(piRequest.getFacilityNum()),BaseGgpFacility::getFacilityNum,piRequest.getFacilityNum())
                .eq(null != piRequest.getFacilityType(),BaseGgpFacility::getFacilityType,piRequest.getFacilityType())
                .eq(null != piRequest.getId(),BaseGgpFacility::getId,piRequest.getId())
                .eq(BaseGgpFacility::getTenantId, SecurityUtils.getTenantId())
                .orderByDesc(BaseGgpFacility::getId);
        page = this.page(page,lambdaQuery);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public List<BaseFacilityDeviceVO> facilityDeviceList(String deviceId,Integer facilityId){
        List<BaseFacilityDeviceVO> list = new ArrayList<>();
        LambdaQueryWrapper<BaseFacilityDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BaseFacilityDevice::getDeviceId,deviceId)
                    .like(null != facilityId,BaseFacilityDevice::getFacilityId,facilityId);
        List<BaseFacilityDevice> list1 = baseFacilityDeviceService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list1)){
            List<Integer> facilityIds = new ArrayList<>();
            for(int i=0;i<list1.size();i++){
                facilityIds.add(list1.get(i).getFacilityId());
            }
            LambdaQueryWrapper<BaseGgpFacility> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(BaseGgpFacility::getId,BaseGgpFacility::getFacilityName,BaseGgpFacility::getAddress)
                    .in(BaseGgpFacility::getId,facilityIds);
            List<BaseGgpFacility> list2 = this.list(queryWrapper1);
            if(CollectionUtils.isNotEmpty(list2)){
                for(int i=0;i<list2.size();i++){
                    BaseFacilityDeviceVO facilityDeviceVO = new BaseFacilityDeviceVO(list2.get(i).getId(),list2.get(i).getFacilityName(),list2.get(i).getAddress());
                    list.add(facilityDeviceVO);
                }
            }
        }

        return list;
    }

    @Override
    public boolean remove(Integer id) {
        return this.removeById(id);
    }

    @Override
    public List<BaseGgpFacilityExportVo> recordLsitExport(BaseGgpFacilityRequest exRequest) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LambdaQueryWrapper<BaseGgpFacility> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(BaseGgpFacility::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(exRequest.getFacilityName()), BaseGgpFacility::getFacilityName, exRequest.getFacilityName())
                .eq(StringUtils.isNotBlank(exRequest.getFacilityNum()), BaseGgpFacility::getFacilityNum, exRequest.getFacilityNum())
                .eq(exRequest.getFacilityType() != 0,BaseGgpFacility::getFacilityType,exRequest.getFacilityType())
                .orderByDesc(BaseGgpFacility::getId);
        List<BaseGgpFacility> baseGgpFacilityList = this.list(queryWrapper);
        List<BaseGgpFacilityExportVo> list = new ArrayList<>();
        List<BaseGgpFacilityTypeNumVO> typeList = baseFacilityTypeMapper.typeNumList(SecurityUtils.getTenantId());
        if (CollectionUtils.isNotEmpty(baseGgpFacilityList)) {
            for (int i = 0; i < baseGgpFacilityList.size(); i++) {
                BaseGgpFacilityExportVo baseGgpFacilityExportVo = new BaseGgpFacilityExportVo();
                baseGgpFacilityExportVo.setFacilityNum(baseGgpFacilityList.get(i).getFacilityNum());
                baseGgpFacilityExportVo.setFacilityType("未知");
                if (CollectionUtils.isNotEmpty(typeList)) {
                    for (int j = 0; j < typeList.size(); j++) {
                        if (baseGgpFacilityList.get(i).getFacilityType().equals(typeList.get(j).getTypeCode())) {
                            baseGgpFacilityExportVo.setFacilityType(typeList.get(j).getTypeName());
                        }
                    }
                }

                baseGgpFacilityExportVo.setFacilityName(baseGgpFacilityList.get(i).getFacilityName());
                baseGgpFacilityExportVo.setAddress(baseGgpFacilityList.get(i).getAddress());
                baseGgpFacilityExportVo.setImagesUrl(baseGgpFacilityList.get(i).getImagesUrl());
                baseGgpFacilityExportVo.setContact(baseGgpFacilityList.get(i).getContact());
                baseGgpFacilityExportVo.setContactPhone(baseGgpFacilityList.get(i).getContactPhone());
                baseGgpFacilityExportVo.setFacilityStatus(baseGgpFacilityList.get(i).getFacilityStatus());
                baseGgpFacilityExportVo.setLongitude(baseGgpFacilityList.get(i).getLongitude());
                baseGgpFacilityExportVo.setLatitude(baseGgpFacilityList.get(i).getLatitude());
                baseGgpFacilityExportVo.setCreateTime(baseGgpFacilityList.get(i).getCreateTime().format(df));
                list.add(baseGgpFacilityExportVo);
            }
        }
        return list;
    }

    @Override
    public List<BaseGgpFacility> facilityInfo(Integer id) {
        LambdaQueryWrapper<BaseGgpFacility> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(null != id,BaseGgpFacility::getId, id);
        List<BaseGgpFacility> baseGgpFacilityList = this.list(queryWrapper);
        return baseGgpFacilityList;
    }

    @Override
    public CommonPage<DmpDeviceInfo> deviceInfo(String deviceId,Integer id,Integer current,Integer size) {
        IPage<DmpDeviceInfo> page = new Page<>(current, size);
        LambdaQueryWrapper<BaseFacilityDevice> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BaseFacilityDevice::getFacilityId,id);
        List<BaseFacilityDevice> baseFacilityDeviceList = baseFacilityDeviceService.list(lambdaQuery);
        if (CollectionUtils.isNotEmpty(baseFacilityDeviceList)) {
            List<String> deviceIdList = new ArrayList<>();
            for (int i = 0; i < baseFacilityDeviceList.size(); i++) {
                deviceIdList.add(baseFacilityDeviceList.get(i).getDeviceId());
            }
            if (CollectionUtils.isNotEmpty(deviceIdList)) {
                if (StringUtils.isNotBlank(deviceId)){
                    LambdaQueryWrapper<DmpDeviceInfo> queryWrapper1 = Wrappers.lambdaQuery();
                    queryWrapper1.select(DmpDeviceInfo::getId, DmpDeviceInfo::getDeviceId,
                            DmpDeviceInfo::getDeviceName, DmpDeviceInfo::getInstallAddress)
                            .in(DmpDeviceInfo::getDeviceId, deviceIdList)
                            .eq(DmpDeviceInfo::getDeviceId, deviceId)
                            .eq(DmpDeviceInfo::getDeleteFlag,0);
                    page = dmpDeviceInfoService.page(page,queryWrapper1);
                }else {
                    LambdaQueryWrapper<DmpDeviceInfo> queryWrapper1 = Wrappers.lambdaQuery();
                    queryWrapper1.select(DmpDeviceInfo::getId, DmpDeviceInfo::getDeviceId,
                            DmpDeviceInfo::getDeviceName, DmpDeviceInfo::getInstallAddress)
                            .in(DmpDeviceInfo::getDeviceId, deviceIdList)
                            .eq(DmpDeviceInfo::getDeleteFlag,0);
                    page = dmpDeviceInfoService.page(page,queryWrapper1);
                }
            }
        }
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public CommonPage<Object> deviceBindInfo(String deviceType,String deviceId,Integer id,Integer current,
                                             Integer size) {
        List<Object> list = new ArrayList<>();
        IPage<DmpDeviceInfo> page = new Page<>(current, size);
        LambdaQueryWrapper<BaseFacilityDevice> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BaseFacilityDevice::getFacilityId,id);
        List<BaseFacilityDevice> baseFacilityDeviceList = baseFacilityDeviceService.list(lambdaQuery);
        LambdaQueryWrapper<DmpDeviceInfo> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(DmpDeviceInfo::getId, DmpDeviceInfo::getDeviceId,
                DmpDeviceInfo::getDeviceName, DmpDeviceInfo::getInstallAddress,DmpDeviceInfo::getDeviceType)
                .eq(StringUtils.isNotBlank(deviceId),DmpDeviceInfo::getDeviceId, deviceId)
                .eq(StringUtils.isNotBlank(deviceType),DmpDeviceInfo::getDeviceType,deviceType)
                .eq(DmpDeviceInfo::getTenantId,SecurityUtils.getTenantId())
                .eq(DmpDeviceInfo::getDeleteFlag,0);
        page = dmpDeviceInfoService.page(page,queryWrapper1);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", page.getRecords().get(i).getId());
                map.put("deviceId", page.getRecords().get(i).getDeviceId());
                map.put("deviceName", page.getRecords().get(i).getDeviceName());
                map.put("deviceType", page.getRecords().get(i).getDeviceType());
                map.put("installAddress", page.getRecords().get(i).getInstallAddress());
                map.put("bindStatus", 0);
                map.put("bindId", 0);
                if (CollectionUtils.isNotEmpty(baseFacilityDeviceList)) {
                    for (int j = 0; j < baseFacilityDeviceList.size(); j++) {
                        if (page.getRecords().get(i).getDeviceId().equals(baseFacilityDeviceList.get(j).getDeviceId())) {
                            map.put("bindStatus", 1);
                            map.put("bindId", baseFacilityDeviceList.get(j).getId());
                        }
                    }
                }
                list.add(map);
            }
        }
        return new CommonPage<>(list,page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public CommonPage<BaseBuild> buildInfo(String buildNum, Integer id, Integer current, Integer size) {
        IPage<BaseBuild> page = new Page<>(current, size);
        LambdaQueryWrapper<BaseFacilityBuild> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BaseFacilityBuild::getFacilityId,id);
        List<BaseFacilityBuild> baseFacilityBuildList = baseFacilityBuildService.list(lambdaQuery);
        if (CollectionUtils.isNotEmpty(baseFacilityBuildList)) {
            List<Integer> buildIdList = new ArrayList<>();
            for (int i = 0; i < baseFacilityBuildList.size(); i++) {
                buildIdList.add(baseFacilityBuildList.get(i).getBuildId());
            }
            if (CollectionUtils.isNotEmpty(buildIdList)) {
                if (StringUtils.isNotBlank(buildNum)){
                    LambdaQueryWrapper<BaseBuild> queryWrapper1 = Wrappers.lambdaQuery();
                    queryWrapper1.select(BaseBuild::getId, BaseBuild::getBuildNum,
                            BaseBuild::getBuildName, BaseBuild::getAddress)
                            .in(BaseBuild::getId, buildIdList)
                            .eq(BaseBuild::getBuildNum, buildNum)
                            .eq(BaseBuild::getDeleteFlag,0);
//                    page = baseBuildService.page(page,queryWrapper1);
                }else {
                    LambdaQueryWrapper<BaseBuild> queryWrapper1 = Wrappers.lambdaQuery();
                    queryWrapper1.select(BaseBuild::getId, BaseBuild::getBuildNum,
                            BaseBuild::getBuildName, BaseBuild::getAddress)
                            .in(BaseBuild::getId, buildIdList)
                            .eq(BaseBuild::getDeleteFlag,0);
//                    page = baseBuildService.page(page,queryWrapper1);
                }
            }
        }
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public List<BaseGgpFacility> baseGgpFacilityList(BaseGgpFacilityVO baseGgpFacilityVO) {
        LambdaQueryWrapper<BaseGgpFacility> query = Wrappers.lambdaQuery();
        query.eq(StringUtils.isNotBlank(baseGgpFacilityVO.getStreetTown()),BaseGgpFacility::getStreetTown, baseGgpFacilityVO.getStreetTown());
        query.in(CollectionUtils.isNotEmpty(baseGgpFacilityVO.getFacilityType()),BaseGgpFacility::getFacilityType,
                baseGgpFacilityVO.getFacilityType());
        query.eq(BaseGgpFacility::getTenantId, SecurityUtils.getTenantId());
        List<BaseGgpFacility> list = this.list(query);
        return list;
    }

    @Override
    public List<Object> facilityPopInfo(Integer id) {
        List<Object> list = new ArrayList<>();
        List<Object> list5 = new ArrayList<>();
        LambdaQueryWrapper<BaseGgpFacility> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BaseGgpFacility::getId, id);
        List<BaseGgpFacility> baseGgpFacilityList = this.list(queryWrapper);
        LambdaQueryWrapper<BaseFacilityDevice> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BaseFacilityDevice::getFacilityId,id);
        List<BaseFacilityDevice> baseFacilityDeviceList = baseFacilityDeviceService.list(lambdaQuery);
        LambdaQueryWrapper<BaseBuild> lambdaQuery3 = Wrappers.lambdaQuery();
        lambdaQuery3.eq(BaseBuild::getFacilityId,id);
        List<BaseBuild> baseFacilityBuildList = baseBuildMapper.selectList(lambdaQuery3);
        Map<String, Object> map = new HashMap<>();
        map.put("id", baseGgpFacilityList.get(0).getId());
        map.put("facilityName", baseGgpFacilityList.get(0).getFacilityName());
        map.put("facilityAddress", baseGgpFacilityList.get(0).getFacilityAddress());
        map.put("contact", baseGgpFacilityList.get(0).getContact());
        map.put("contactPhone", baseGgpFacilityList.get(0).getContactPhone());
        map.put("buildId", null);
        if (CollectionUtils.isNotEmpty(baseFacilityBuildList)){
            map.put("buildId", baseFacilityBuildList.get(0).getId());
        }
        LambdaQueryWrapper<DmpProductInfo> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(DmpProductInfo::getTenantId,SecurityUtils.getTenantId())
                .eq(DmpProductInfo::getDeleteFlag,0);
        List<DmpProductInfo> dmpProductInfoList = dmpProductInfoService.list(queryWrapper2);
        if (CollectionUtils.isNotEmpty(baseFacilityDeviceList)) {
            List<String> deviceIdList = new ArrayList<>();
            for (int i = 0; i < baseFacilityDeviceList.size(); i++) {
                deviceIdList.add(baseFacilityDeviceList.get(i).getDeviceId());
            }
            QueryWrapper<BaseAlarm> query1 = Wrappers.query();
            query1.select("product_code as productCode","count(id) as count")
                    .in("device_id",deviceIdList)
                    .groupBy("product_code");
            List<Map<String, Object>> baseAlarmList = baseAlarmService.listMaps(query1);
            QueryWrapper<BaseAlarm> query2 = Wrappers.query();
            query2.select("product_code as productCode","count(id) as count")
                    .in("device_id",deviceIdList)
                    .eq("handle_status",1)
                    .groupBy("product_code");
            List<Map<String, Object>> baseAlarmList1 = baseAlarmService.listMaps(query2);
            List<Map<String, Object>> list1 = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(baseAlarmList)){
                for (int k = 0; k < baseAlarmList.size(); k++){
                    if (CollectionUtils.isNotEmpty(baseAlarmList1)){
                        for (int l = 0; l < baseAlarmList1.size(); l++){
                            if (baseAlarmList.get(k).get("productCode").equals(baseAlarmList1.get(l).get("productCode"))){
                                int count1 = Integer.parseInt(String.valueOf(baseAlarmList1.get(l).get("count")));
                                int count = Integer.parseInt(String.valueOf(baseAlarmList.get(k).get("count")));
                                double disposalRate = 0;
                                if (count>0){
                                    disposalRate = Math.round(count1/count)*100;
                                }
                                Map<String, Object> map1 = new HashMap<>();
                                map1.put("productCode",baseAlarmList.get(k).get("productCode"));
                                map1.put("disposalRate",disposalRate);
                                list1.add(map1);
                            }
                        }
                    }
                }
            }
            QueryWrapper<DmpDeviceInfo> query = Wrappers.query();
            query.select("product_code as productCode","count(id) as count")
                    .in("device_id",deviceIdList)
                    .eq("delete_flag",0)
                    .groupBy("product_code");
            List<Map<String, Object>> dmpDeviceInfoList = dmpDeviceInfoService.listMaps(query);
            if (CollectionUtils.isNotEmpty(dmpDeviceInfoList)){
                if (CollectionUtils.isNotEmpty(dmpProductInfoList)){
                    for (int m = 0; m < dmpProductInfoList.size(); m++){
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("productName",dmpProductInfoList.get(m).getProductName());
                        map2.put("deviceCount",0);
                        map2.put("disposalRate",100);
                        for (int n = 0; n < dmpDeviceInfoList.size(); n++){
                            if (dmpProductInfoList.get(m).getProductCode().equals(dmpDeviceInfoList.get(n).get("productCode"))){
                                map2.put("deviceCount",dmpDeviceInfoList.get(n).get("count"));
                            }
                        }
                        if (CollectionUtils.isNotEmpty(list1)){
                            for (int o = 0; o < list1.size(); o++){
                                if (dmpProductInfoList.get(m).getProductCode().equals(list1.get(o).get("productCode"))){
                                    map2.put("disposalRate",list1.get(o).get("disposalRate"));
                                }
                            }
                        }else {
                            map2.put("disposalRate",0);
                        }
                        list5.add(map2);
                    }
                }
                map.put("productList",list5);
            }else {
                if (CollectionUtils.isNotEmpty(dmpProductInfoList)) {
                    for (int m = 0; m < dmpProductInfoList.size(); m++) {
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("productName", dmpProductInfoList.get(m).getProductName());
                        map2.put("deviceCount", 0);
                        map2.put("disposalRate", 100);
                        list5.add(map2);
                    }
                    map.put("productList",list5);
                }
            }
        }else {
            if (CollectionUtils.isNotEmpty(dmpProductInfoList)) {
                for (int m = 0; m < dmpProductInfoList.size(); m++) {
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("productName", dmpProductInfoList.get(m).getProductName());
                    map2.put("deviceCount", 0);
                    map2.put("disposalRate", 100);
                    list5.add(map2);
                }
                map.put("productList",list5);
            }
        }
        list.add(map);
        return list;
    }

    @Override
    public void facilityImport(MultipartFile multipartFile) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        String err="文件导入失败";
        try {
            List<FacilityImportVo> facilityImportVos = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                    FacilityImportVo.class, params);
            if (CollectionUtils.isNotEmpty(facilityImportVos)){
                int rot=3;
                for (FacilityImportVo facilityImportVo:facilityImportVos) {
                    BaseGgpFacility baseGgpFacility = BeanMapperUtils.map(facilityImportVo, BaseGgpFacility.class);
                    List<BaseGgpFacilityTypeNumVO> typeList = baseFacilityTypeMapper.facilitTypeNumList();
                    if (CollectionUtils.isNotEmpty(typeList)) {
                        for (int j = 0; j < typeList.size(); j++) {
                            if (baseGgpFacility.getFacilityType().equals(typeList.get(j).getTypeName())) {
                                baseGgpFacility.setFacilityType(typeList.get(j).getTypeCode());
                            }
                        }
                    }
                    if (StringUtils.isBlank(baseGgpFacility.getFacilityType())||StringUtils.isBlank(baseGgpFacility.getFacilityName())||StringUtils.isBlank(baseGgpFacility.getAddress())||StringUtils.isBlank(baseGgpFacility.getLatitude())||StringUtils.isBlank(baseGgpFacility.getLongitude())){

                        String tmp = ",第"+rot+"行数据导入失败,必填字段不能为空";
                        err = err.concat(tmp);
                        throw  new Exception(err);
                    }
                    if(StringUtils.isNotBlank(baseGgpFacility.getContactPhone())){
                        if(!validator(baseGgpFacility.getContactPhone())){
                            String tmp = ",请检查第"+rot+"行手机号是否正确";
                            err = err.concat(tmp);
                            throw new Exception(err);
                        }
                    }
                    try{
                        this.add(baseGgpFacility);
                    }catch (Exception e){
                        String tt = ",第"+rot+"行数据导入失败";
                        err = err.concat(tt);
                        throw  new Exception(err);
                    }
                    rot++;
                }
            }else {
                err = err.concat(",文件不能为空");
                throw new Exception(err);
            }
        }catch (Exception e){
            throw  new BusinessException(e.getMessage());
        }
    }


    public static boolean validator(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[0,1,5,6,7,8,9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

//    @Override
//    public void facilityImport(MultipartFile multipartFile) {
//        String FILE_IMPORT_FAILED = "文件导入失败";
//        String FILE_EMPTY = "文件不能为空";
//        String ROW_IMPORT_FAILED = "第%d行数据导入失败";
//
//        ImportParams params = new ImportParams();
//        params.setHeadRows(1);
//        params.setTitleRows(1);
//
//        try (InputStream inputStream = multipartFile.getInputStream()) {
//            List<BaseGgpFacility> facilityList = new ArrayList<>();
//            List<FacilityImportVo> facilityImportVos = ExcelImportUtil.importExcel(inputStream, FacilityImportVo.class, params);
//            if (CollectionUtils.isEmpty(facilityImportVos)) {
//                throw new BusinessException(FILE_EMPTY);
//            }
//
//            for (int i = 0; i < facilityImportVos.size(); i++) {
//                FacilityImportVo facilityImportVo = facilityImportVos.get(i);
//                BaseGgpFacility baseGgpFacility = BeanMapperUtils.map(facilityImportVo, BaseGgpFacility.class);
//                if (isBlank(baseGgpFacility.getFacilityType()) || isBlank(baseGgpFacility.getFacilityName()) || isBlank(baseGgpFacility.getAddress()) || isBlank(baseGgpFacility.getLatitude()) || isBlank(baseGgpFacility.getLongitude())) {
//                    throw new BusinessException(String.format(ROW_IMPORT_FAILED, i + 1));
//                }
//                Calendar cal1 = Calendar.getInstance();
//                Date date = cal1.getTime();
//                List<BaseFacilityType> typeList = baseFacilityTypeMapper.typeList(baseGgpFacility.getFacilityType());
//                if (CollectionUtils.isEmpty(typeList)) {
//                    String FILE_TYPE_ERROR = "设施类型有误";
//                    throw new BusinessException(FILE_TYPE_ERROR);
//                }
//                baseGgpFacility.setFacilityNum(typeList.get(0).getTypeAbbrevia()+'-'+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date));
//                baseGgpFacility.setCreator(SecurityUtils.getUsername());
//                baseGgpFacility.setCreateTime(LocalDateTime.now());
//                baseGgpFacility.setTenantId(SecurityUtils.getTenantId());
//                facilityList.add(baseGgpFacility);
//            }
//            try {
//                this.saveBatch(facilityList);
//            } catch (Exception e) {
//                throw new BusinessException(FILE_IMPORT_FAILED);
//            }
//        } catch (Exception e) {
//            log.error("文件导入失败", e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            throw new BusinessException(FILE_IMPORT_FAILED);
//        }
//    }

    private boolean isBlank(String str) {
        return StringUtils.isBlank(str) || StringUtils.isBlank(str.trim());
    }
}
