package org.springblade.utils.excel.controller;

import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.mybatis.spring.MyBatisSystemException;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.car.entity.Car;
import org.springblade.community.car.service.ICarService;
import org.springblade.community.carrecord.entity.CarRecord;
import org.springblade.community.enterprise.entity.Enterprise;
import org.springblade.community.enterprise.service.IEnterpriseService;
import org.springblade.community.houseuserthird.entity.ThirdHouseUser;
import org.springblade.community.houseuserthird.service.IThirdHouseUserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.staff.entity.EnterpriseStaff;
import org.springblade.community.staff.service.IEnterpriseStaffService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.smartapplication.carenterrecord.entity.CarEnterRecord;
import org.springblade.smartapplication.carenterrecord.service.ICarEnterRecordService;
import org.springblade.smartapplication.caroutrecord.entity.CarOutRecord;
import org.springblade.smartapplication.caroutrecord.service.ICarOutRecordService;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.system.street.service.IStreetService;
import org.springblade.utils.excel.model.ResidentialImportModule;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * title: ImportExcelController
 * package: com.sptg.gateway.controller.common.excel
 * description: 导入处理
 */
@RestController
@AllArgsConstructor
public class ImportExcelController  extends BladeController {

	private final ExportExcelController exportExcelController;

	private ISmartDeviceService smartDeviceService;
	private IEnterpriseService enterpriseService;
	private IEnterpriseStaffService enterpriseStaffService;
	private IAgencyService agencyService;
	private IResidentialService residentialService;
	private IStreetService streetService;
	private ICarService carService;

	private ICarEnterRecordService enterRecordService;
	private ICarOutRecordService outRecordService;

	private IThirdHouseUserService thirdHouseUserService;

    private static final String REGEX_EXCEL2003 = "^.+\\.(?i)(xls)$";
    private static final String REGEX_EXCEL2007 = "^.+\\.(?i)(xlsx)$";
    private static final String REGEX_MOBILE = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
    private static final String REGEX_NUMBER = "[0-9]+";
    private static final String REGEX_AREA = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private final static String IMPORT_CACHE_ORG_CODE = "sptg:import:org:code";
    private final static String IMPORT_CACHE_AREA = "sptg:import:area";
    private final static String IMPORT_CACHE_RESIDENTIAL_CODE = "sptg:import:residential:code";
    private final static String IMPORT_CACHE_UNIT_CODE_NAME = "sptg:import:unit:code:name";
    private final static String IMPORT_CACHE_ROOM_CODE_NAME = "sptg:import:room:code:name";
    private final static String IMPORT_CACHE_UNIT_CODE = "sptg:import:card:unit:code";
    private final static String IMPORT_CACHE_ROOM_CODE = "sptg:import:card:room:code";
    private final static String IMPORT_CACHE_USER_NMAE = "sptg:import:card:user:name";


	/**
	 * 功能描述: 智家设备导入
	 * @param file
	 * @return
	 */
    public R readHomeDeviceExcel(MultipartFile file) {
        List<Object> errorList = new ArrayList<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return R.data("文件格式不合法！");
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return R.data("文件内容格式不对！");
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
//            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
//                return R.data("文件过大！");
//            }
            List<SmartDevice> list = new ArrayList<>();
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                SmartDevice device = new SmartDevice();

				// 设备编码
				String deviceId = getCellValue(row.getCell(4));
				if (StringUtils.isBlank(deviceId)) {
					flag = false;
					importErrorMsg.append("设备编码为空；");
				}
				device.setDeviceId(deviceId);

				SmartDevice one = smartDeviceService.getOne(Condition.getQueryWrapper(device));
				if (one != null) {
					device = one;
				}

				// 10: 代表智家设备
                device.setDeviceUsage(10);
                // 银川可看
                device.setOrgPosition("/640000");
                //上线状态
                device.setDefenseStatus(1);


                //  产权客户名称
                String person = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(person)) {
                    flag = false;
                    importErrorMsg.append("产权客户名称为空；");
                }
                device.setPerson(person);
                //  证件号
                String idcard = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(idcard)) {
                    flag = false;
                    importErrorMsg.append("证件号为空；");
                }
                device.setIdcard(idcard);
                //  联系人电话
                String personTel = getCellValue(row.getCell(2));
                device.setPersonTel(personTel);

                //  安装位置
                String installAddress = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(installAddress)) {
                    flag = false;
                    importErrorMsg.append("设备安装位置为空；");
                }
                device.setDeviceInstallAddress(installAddress);


//				device.setDeviceId(deviceId);

                // 设备名称
                String deviceName = getCellValue(row.getCell(5));
                if (StringUtils.isBlank(deviceName)) {
                    flag = false;
                    importErrorMsg.append("设备名称为空；");
                }
                device.setDeviceName(deviceName);

                if (deviceName.indexOf("燃气告警") != -1){
                	device.setDeviceType("100020");
				}
                if (deviceName.indexOf("智能烟感") != -1){
                	device.setDeviceType("100004");
				}

                list.add(device);

            }

			boolean b = smartDeviceService.saveOrUpdateBatch(list);


		} catch (IOException e) {
            e.printStackTrace();
            return R.data("服务器异常！");
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

		return R.status(true);
	}

	/**
	 * 功能描述: 企业信息导入
	 * @param file
	 * @return
	 */
    public R readEnterpriseExcel(MultipartFile file) {
        List<Object> errorList = new ArrayList<>();

        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return R.data("文件格式不合法！");
            }
            is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
            /*if (fileName.matches(REGEX_EXCEL2007)) {
				workbook = new XSSFWorkbook(is)
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }*/
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return R.data("文件内容格式不对！");
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
//            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
//                return R.data("文件过大！");
//            }
            List<Enterprise> list = new ArrayList<>();
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                Enterprise enterprise = new Enterprise();

				//  企业名称
				String name = getCellValue(row.getCell(1));
				if (StringUtils.isBlank(name)) {
					flag = false;
					importErrorMsg.append("企业名称为空；");
				}
				enterprise.setEnterpriseName(name);

				Enterprise one = enterpriseService.getOne(Condition.getQueryWrapper(enterprise));
				if (one != null){
					// 如果找到同名企业，则作更新
					enterprise = one;
				}



				//  归属分区
                String residential = getCellValue(row.getCell(0));
				String residentialIdstr = residential.split("_")[1];

				if (StringUtils.isNotBlank(residential)){
					residential = residential.split("_")[1];
					enterprise.setResidentialId(Long.parseLong(residential));
				}else {
					flag = false;
					importErrorMsg.append("归属分区为空；");
				}

				//  企业类型
                String type = getCellValue(row.getCell(1));
                enterprise.setEnterpriseType(type);

                //  详细地址
                String address = getCellValue(row.getCell(3));
				enterprise.setRegion(address);

                //  企业简介
                String introduce = getCellValue(row.getCell(4));
				enterprise.setEnterpriseIntroduce(introduce);

                //  组织机构代码
                String code = getCellValue(row.getCell(5));
				enterprise.setOrganizationCode(code);

                // 统一信用代码
                String creditCode = getCellValue(row.getCell(6));
                enterprise.setCreditCode(creditCode);

                // 注册资金
                String registeredCapital = getCellValue(row.getCell(7));
                enterprise.setRegisteredCapital(registeredCapital);

                // 注册地址
                String registeredAddress = getCellValue(row.getCell(8));
                enterprise.setRegisteredAddress(registeredAddress);

                // 法定代表人
                String representative = getCellValue(row.getCell(9));
                enterprise.setRepresentative(representative);

                // 成立日期
                String registeredDate = getCellValue(row.getCell(10));
                enterprise.setRegisteredDate(registeredDate);

                // 办公电话
                String officeNum = getCellValue(row.getCell(11));
                enterprise.setOfficeNum(officeNum);

                if (enterprise.getResidentialId() != null){
					Residential residentialById = residentialService.getById(enterprise.getResidentialId());
					enterpriseService.save(enterprise);
					enterprise.setOrgPosition(residentialById.getOrgPosition() + "/" + enterprise.getId());
				}

                list.add(enterprise);
            }

			boolean b = enterpriseService.saveOrUpdateBatch(list);


		} catch (IOException e) {
            e.printStackTrace();
            return R.data("服务器异常！");
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

		return R.status(true);
	}

	/**
	 * 功能描述: 员工信息导入
	 * @param file
	 * @return
	 */
    public R readEnterpriseStaffExcel(MultipartFile file) {
        List<Object> errorList = new ArrayList<>();
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return R.data("文件格式不合法！");
            }
            is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);

            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return R.data("文件内容格式不对！");
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
//            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
//                return R.data("文件过大！");
//            }
            List<EnterpriseStaff> list = new ArrayList<>();
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
				EnterpriseStaff staff = new EnterpriseStaff();

				//  所属企业全称
				String enterpriseName = getCellValue(row.getCell(1));
				if (StringUtils.isBlank(enterpriseName)) {
					flag = false;
					importErrorMsg.append("所属企业名称为空；");
				}
				staff.setEnterpriseName(enterpriseName);

				Enterprise enterprise = new Enterprise();
				enterprise.setEnterpriseName(enterpriseName);
				Enterprise one = enterpriseService.getOne(Condition.getQueryWrapper(enterprise));
				if (one != null) {
					staff.setEnterpriseId(one.getId());
					staff.setTenantId(one.getTenantId());

					if (one.getResidentialId() != null) {
						Residential residential = residentialService.getById(one.getResidentialId());
						Agency agency = agencyService.getById(residential.getAgencyId());
						staff.setAgencyId(agency.getId());
						staff.setResidentialId(residential.getId());
						if (staff.getId() == null){
							enterpriseStaffService.save(staff);
						}
						staff.setOrgPosition(residential.getOrgPosition() + "/" + staff.getId());
					}

//					staff.setResidentialId(one.getResidentialId());
				}

                //  姓名
                String name = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(name)) {
                    flag = false;
                    importErrorMsg.append("姓名为空；");
                }
                staff.setRealName(name);
                staff.setName(name);

                //  详细住址
                String address = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(address)) {
                    flag = false;
                    importErrorMsg.append("详细住址为空；");
                }
                staff.setAddress(address);

                //  邮箱
                String email = getCellValue(row.getCell(3));
                staff.setEmail(email);

                //  手机
                String phone = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(phone)) {
                    flag = false;
                    importErrorMsg.append("手机为空；");
                }
                staff.setPhone(phone);

                // 性别
                String sexName = getCellValue(row.getCell(5));
                if (StringUtils.isNotBlank(sexName)) {
					if (sexName.equals("男")){
						staff.setSex(1);
					}else if (sexName.equals("女")){
						staff.setSex(2);
					}
                }

                // 身份证号
                String idcard = getCellValue(row.getCell(6));
                if (StringUtils.isBlank(idcard)) {
					flag = false;
					importErrorMsg.append("身份证号为空；");
                }
				staff.setIdcard(idcard);

                // 设为审核通过
                staff.setExamine(1);

                list.add(staff);

            }

			boolean b = enterpriseStaffService.saveOrUpdateBatch(list);


		} catch (IOException e) {
            e.printStackTrace();
            return R.data("服务器异常！");
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

		return R.status(true);
	}

    /*
    *//**
     * 功能描述:机构导入
     *
     * @param file onLineUser
     * @return ResultBean<Organization>
     *//*
    public ResultBean<Object> readOrgExcel(MultipartFile file, Account onLineUser) {
        List<Object> errorList = new ArrayList<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                OrgDto orgDto = new OrgDto();
                //  机构名称
                String orgName = getCellValue(row.getCell(0));
                orgDto.setName(orgName);
                if (StringUtils.isBlank(orgName)) {
                    flag = false;
                    importErrorMsg.append("机构名称为空；");
                }
                //  机构类型
                String orgType = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(orgType)) {
                    flag = false;
                    importErrorMsg.append("机构类型为空；");
                }
                orgDto.setOrgType(Integer.parseInt(orgType));
                //  省市区
                String regionProvince = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(regionProvince)) {
                    flag = false;
                    importErrorMsg.append("小区所属省为空；");
                }
                String regionCity = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(regionCity)) {
                    flag = false;
                    importErrorMsg.append("小区所属市为空；");
                }
                String regionArea = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(regionArea)) {
                    flag = false;
                    importErrorMsg.append("小区所属县/区为空；");
                }
                //  负责人电话
                String personName = getCellValue(row.getCell(5));
                if (StringUtils.isNotBlank(personName)) {
                    orgDto.setPersonName(personName);
                }
                //  负责人电话
                String personTel = getCellValue(row.getCell(6));
                if (StringUtils.isNotBlank(personTel)) {
//                    if (!Pattern.matches(REGEX_MOBILE, personTel)) {
//                        flag = false;
//                        importErrorMsg.append("负责人电话格式错误；");
//                    }
                    orgDto.setPersonTel(personTel);
                }

                //  详细地址
                String address = getCellValue(row.getCell(7));
                if (StringUtils.isNotBlank(address)) {
                    orgDto.setAddress(address);
                }
                //  备注
                String remark = getCellValue(row.getCell(8));
                if (StringUtils.isNotBlank(remark)) {
                    orgDto.setRemark(remark);
                }

                //  从缓存中获取省市区的信息
                HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
                String cacheKey = DigestUtils.md5Hex(regionProvince + regionCity + regionArea);
                String json = hashOperations.get(IMPORT_CACHE_AREA, cacheKey);
                AreaDto dto;
                if (StringUtils.isEmpty(json)) {
                    dto = this.getArea(regionProvince, regionCity, regionArea);
                    if (null == dto) {
                        flag = false;
                        orgDto.setRegionProvince(regionProvince);
                        orgDto.setRegionCity(regionCity);
                        orgDto.setRegionArea(regionArea);
                        importErrorMsg.append("所属省市区不存在；");
                    } else {
                        orgDto.setRegionProvince(dto.getRegionProvince());
                        orgDto.setRegionCity(dto.getRegionCity());
                        orgDto.setRegionArea(dto.getRegionArea());
                        orgDto.setRegion(dto.getRegionName());
                        json = JsonUtils.objectToJson(dto);
                        hashOperations.put(IMPORT_CACHE_AREA, cacheKey, json);
                    }
                } else {
                    dto = JsonUtils.jsonToPojo(json, AreaDto.class);
                    orgDto.setRegionProvince(dto.getRegionProvince());
                    orgDto.setRegionCity(dto.getRegionCity());
                    orgDto.setRegionArea(dto.getRegionArea());
                    orgDto.setRegion(dto.getRegionName());
                }

                //没必要做缓存
                ;
                if (this.orgFeign.checkNameIsExist(orgName)) {
                    flag = false;
                    orgDto.setRegionProvince(regionProvince);
                    orgDto.setRegionCity(regionCity);
                    orgDto.setRegionArea(regionArea);
                    importErrorMsg.append("机构已存在；");
                }

                if (flag) {
                    orgDto.setCreateAccountId(onLineUser.getId());
                    Organization parent = this.orgFeign.getOrgById(1L);
                    orgDto.setRootOrgId(parent.getId());//挂在机构总管理
                    orgDto.setPid(parent.getId());//挂在机构总管理
                    orgDto.setPosition(parent.getPosition());
                    orgDto.setFlag(1);// 机构

                    orgDto.setCode("O");
                    //机构类型 { 1：内部,2：广告,3：物业, 4：社区 }
                    if ((orgDto.getOrgType() == OperationConstant.THREE || orgDto.getOrgType() == OperationConstant.TWO || orgDto.getOrgType() == OperationConstant.FOUR) && orgDto.getPid() == null){
                        //如果是新建物业或者广告商，则pid为空，隐形挂在下面，方便cyzh管理（cyzh id为1）
                        Organization org = this.orgFeign.getOrgById(1L);
                        orgDto.setPid(org.getId());
                        orgDto.setPosition(org.getPosition());
                    }

                    ResultBean<Organization> resultBean = this.orgFeign.addEntity(orgDto);
                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {

                    } else {
                        orgDto.setRegionProvince(regionProvince);
                        orgDto.setRegionCity(regionCity);
                        orgDto.setRegionArea(regionArea);
                        orgDto.setImportErrorMsg("后台添加失败，联系管理员;");
                        errorList.add(orgDto);
                    }

                } else {
                    orgDto.setImportErrorMsg(importErrorMsg.toString());
                    errorList.add(orgDto);
                }
            }

            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    *//**
     * 功能描述:单元导入
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<Object> readUnitExcel(MultipartFile file, Account onLineUser) {
        UnitDto unitImportExcelDto = new UnitDto();
        List<Unit> list = new ArrayList<>();
        List<Object> errorList = new ArrayList<>();
        Map<Long, Integer> map = new HashMap<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 9){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                UnitDto unit = new UnitDto();
                //  小区名称
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    flag = false;
                    importErrorMsg.append("所属小区编号为空;");
                }
                //  单元名称
                String name = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(name)) {
                    flag = false;
                    importErrorMsg.append("单元名称为空;");
                }
                unit.setName(name);
                //  单元编号
//                String unitNumber = getCellValue(row.getCell(2));
//                if(StringUtils.isBlank(unitNumber)){
//                    return new ResultBean<>("200","第"+rowNum+"行单元编号为空，请核实后重新操作");
//                }
//                if(!Pattern.matches(REGEX_NUMBER, unitNumber)){
//                    return new ResultBean<>("200","第"+rowNum+"行单元编号格式错误，请核实后重新操作");
//                }
//                unit.setUnitNumber(unitNumber);
                //  联系人电话
                String personTel = getCellValue(row.getCell(3));
                if (StringUtils.isNotBlank(personTel)) {
                    if (!Pattern.matches(REGEX_MOBILE, personTel)) {
                        flag = false;
                        importErrorMsg.append("联系人电话格式错误;");
                    }
                }
                unit.setPersonTel(personTel);
                //排序必须是整数
                String serial = getCellValue(row.getCell(8));
                Integer serial1 = null;
                if (StringUtils.isNotBlank(serial)) {
                    try {
                        serial1 = Integer.valueOf(serial);
                        unit.setSerial(Integer.valueOf(serial1));
                    } catch (Exception e) {
                        flag = false;
                        importErrorMsg.append("排序的值不是整数;");
                    }
                } else {
                    unit.setSerial(OperationConstant.ONE);
                }

                UnitDto unitDto = new UnitDto();
                //  获取小区信息
//                ResultBean<Residential> resultBean = this.getResidential(residentialNumber,rowNum);
                Residential residential = this.residentialFeign.findResidentialByNumber(residentialNumber);
                if (null == residential) {
                    flag = false;
                    importErrorMsg.append("所属小区编号不存在");
                } else {
                    long residentialId = residential.getId();
                    String residentialName = residential.getName();
                    unit.setResidentialId(residentialId);
                    unitDto.setResidentialId(residentialId);
//                unitDto.setUnitNumber(unitNumber);
                    //没必要做缓存
                    if (this.unitFeign.findUnitByCondition(unitDto) > 0) {
                        flag = false;
                        importErrorMsg.append("单元已存在");
                    }
                    unitDto.setResidentialName(residentialName);
                    unitDto.setOrgPid(residentialId);
                    unitDto.setOrgPidName(residentialName);
                    unitDto.setRootOrgId(residential.getRootOrgId());
                    unitDto.setOrgPosition(residential.getOrgPosition() + unit.getId() + SymbolConstant.BACK_SLASH);
                    unitDto.setEstatePosition(residential.getEstatePosition() + unit.getId() + SymbolConstant.BACK_SLASH);

                    if (map.containsKey(residentialId)) {
                        map.put(residentialId, map.get(residentialId) + 1);
                        unitDto.setUnitNumber(SymbolConstant.B_NO + CommonUtil.autoZeroFilling(4, residential.getUnitNumber() + map.get(residentialId)));
                    } else {
                        map.put(residentialId, 1);
                        unitDto.setUnitNumber(SymbolConstant.B_NO + CommonUtil.autoZeroFilling(4, residential.getUnitNumber() + 1));
                    }
                }
                unitDto.setName(name);
                unitDto.setResidentialNumber(residentialNumber);
                unitDto.setPersonTel(personTel);
                unitDto.setSerial(serial1);
                unitDto.setPersonName(getCellValue(row.getCell(2)));
                unitDto.setBuiltYear(getCellValue(row.getCell(4)));
                unitDto.setPropertyNature(getCellValue(row.getCell(5)));
                unitDto.setIncludingElevator(getCellValue(row.getCell(6)));
                unitDto.setRemark(getCellValue(row.getCell(7)));
                unitDto.setCreateAccountId(onLineUser.getId());
                unitDto.setId(IdWorker.getId());
                unitDto.setRoomNumber(OperationConstant.ZERO);
                unitDto.setUserNumber(OperationConstant.ZERO);
                unitDto.setCreateDate(new Date());
                unitDto.setStatus(OperationConstant.ZERO);
                if (flag) {
                    ResultBean<UnitDto> resultBean = this.unitFeign.addUnit(unitDto);
                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
                    } else {
                        unitDto.setImportErrorMsg("后台添加失败，联系管理员;");
                        errorList.add(unitDto);
                    }

                } else {
                    unitDto.setImportErrorMsg(importErrorMsg.toString());
                    errorList.add(unitDto);
                }


//                if(map.containsKey(residentialId)){
//                    map.put(residentialId,map.get(residentialId)+1);
//                }else{
//                    map.put(residentialId,1);
//                }
            }
//            if (!list.isEmpty() && !map.isEmpty()) {
////                unitImportExcelDto.setList(list);
////                unitImportExcelDto.setMap(map);
//                return new ResultBean<>(ExcelResultEnum.SUCCESS, errorList);
//            } else {
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:房间导入
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<RoomDto> readRoomExcel_old(MultipartFile file, Account onLineUser) {
        RoomDto roomImportExcelDto = new RoomDto();
        List<Room> list = new ArrayList<>();
        Map<Long, Integer> residentialMap = new HashMap<>();
        Map<Long, Integer> unitMap = new HashMap<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 11){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                Room room = new Room();
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行所属小区编号为空，请核实后重新操作");
                }
                String unitName = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(unitName)) {
                    return new ResultBean<>("200", "第" + rowNum + "行单元名称为空，请核实后重新操作");
                }
                String unitNumber = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(unitNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行单元编号为空，请核实后重新操作");
                }
                String name = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(name)) {
                    return new ResultBean<>("200", "第" + rowNum + "行房间名称为空，请核实后重新操作");
                }
                room.setName(name);
                String houseNumber = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(houseNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行门牌号为空，请核实后重新操作");
                }
                if (!Pattern.matches(REGEX_NUMBER, houseNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行门牌号格式错误，请核实后重新操作");
                }
                room.setHouseNumber(houseNumber);
                String area = getCellValue(row.getCell(9));
                if (StringUtils.isNotBlank(area)) {
                    if (!Pattern.matches(REGEX_AREA, area)) {
                        return new ResultBean<>("200", "第" + rowNum + "行房间面积格式错误，请核实后重新操作");
                    }
                }
                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                if (null == residential || null == residential.getId()) {
                    return new ResultBean<>("200", residentialResultBean.getMsg());
                }
                long residentialId = residential.getId();
                room.setResidentialId(residentialId);

                UnitDto unitDto = new UnitDto();
                unitDto.setResidentialId(residentialId);
                unitDto.setUnitNumber(unitNumber);
                unitDto.setName(unitName);
                ResultBean<Unit> unitResultBean = this.getUnit(unitDto, rowNum, onLineUser);
                Unit unit = unitResultBean.getData();
                if (null == unit || null == unit.getId()) {
                    return new ResultBean<>("200", unitResultBean.getMsg());
                }
                long unitId = unit.getId();
                room.setUnitId(unitId);

                RoomDto roomDto = new RoomDto();
                roomDto.setUnitId(unitId);
                roomDto.setName(name);
                roomDto.setHouseNumber(houseNumber);
                //没必要做缓存
                if (this.roomFeign.findRoomByCondition(roomDto) > 0) {
                    return new ResultBean<>("200", "第" + rowNum + "行房间名称或编号已存在，请核实后重新操作");
                }
                room.setUnitName(unit.getName());
                room.setResidentialName(unit.getResidentialName());
                room.setRootOrgId(unit.getRootOrgId());
                room.setHouseType(getCellValue(row.getCell(5)));
                room.setFloor(getCellValue(row.getCell(6)));
                room.setOrientation(getCellValue(row.getCell(7)));
                room.setOrnament(getCellValue(row.getCell(8)));
                room.setArea(area == null ? null : Double.valueOf(area));
                room.setRemark(getCellValue(row.getCell(10)));
                room.setUserNumber(OperationConstant.ZERO);
                room.setCreateDate(new Date());
                room.setStatus(OperationConstant.ZERO);
                room.setCreateAccountId(onLineUser.getId());
                room.setId(IdWorker.getId());
                room.setOrgPosition(unit.getOrgPosition() + room.getId() + SymbolConstant.BACK_SLASH);
                room.setEstatePosition(unit.getEstatePosition() + room.getId() + SymbolConstant.BACK_SLASH);
                list.add(room);
                if (residentialMap.containsKey(residentialId)) {
                    residentialMap.put(residentialId, residentialMap.get(residentialId) + 1);
                } else {
                    residentialMap.put(residentialId, 1);
                }
                if (unitMap.containsKey(unitId)) {
                    unitMap.put(unitId, unitMap.get(unitId) + 1);
                } else {
                    unitMap.put(unitId, 1);
                }
            }
            if (!list.isEmpty() && !residentialMap.isEmpty() && !unitMap.isEmpty()) {
                roomImportExcelDto.setList(list);
                roomImportExcelDto.setResidentialMap(residentialMap);
                roomImportExcelDto.setUnitMap(unitMap);
                return new ResultBean<>(ExcelResultEnum.SUCCESS, roomImportExcelDto);
            } else {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:房间导入2.0
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<Object> readRoomExcel(MultipartFile file, Account onLineUser) {
        RoomDto roomImportExcelDto = new RoomDto();
        List<Room> list = new ArrayList<>();
        List<Object> errorList = new ArrayList<>();
        Map<Long, Integer> residentialMap = new HashMap<>();
        Map<Long, Integer> unitMap = new HashMap<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 11){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                RoomDto roomDto = new RoomDto();
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    flag = false;
                    importErrorMsg.append("所属小区编号为空;");
                }
                roomDto.setResidentialNumber(residentialNumber);
                String unitNumber = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(unitNumber)) {
                    flag = false;
                    importErrorMsg.append("单元编号为空;");
                }
                roomDto.setUnitNumber(unitNumber);
                String name = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(name)) {
                    flag = false;
                    importErrorMsg.append("房间名称为空;");
                }
                roomDto.setName(name);
                String area = getCellValue(row.getCell(7));
                if (StringUtils.isNotBlank(area)) {
                    if (!Pattern.matches(REGEX_AREA, area)) {
                        flag = false;
                        importErrorMsg.append("房间面积格式错误;");
                    } else {
                        roomDto.setArea(area == null ? null : Double.valueOf(area));
                    }
                }

                //排序必须是整数
                String serial = getCellValue(row.getCell(9));
                if (StringUtils.isNotBlank(serial)) {
                    try {
                        roomDto.setSerial(Integer.valueOf(serial));
                    } catch (Exception e) {
                        flag = false;
                        importErrorMsg.append("排序的值不是整数;");
                    }
                } else {
                    roomDto.setSerial(OperationConstant.ONE);
                }


                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                long residentialId = 0L;
                if (null == residential || null == residential.getId()) {
                    flag = false;
                    importErrorMsg.append("小区编号对应的小区不存在;");
                } else {
                    residentialId = residential.getId();
                    roomDto.setResidentialId(residentialId);
                    if (residentialMap.containsKey(residentialId)) {
                        residentialMap.put(residentialId, residentialMap.get(residentialId) + 1);
                    } else {
                        residentialMap.put(residentialId, 1);
                    }
                }


                UnitDto unitDto = new UnitDto();
                unitDto.setResidentialId(residentialId);
                unitDto.setUnitNumber(unitNumber);
//                unitDto.setName(unitName);
                Unit unit = unitFeign.findUnitByNameAndNumber(unitDto);

                if (null == unit || null == unit.getId()) {
                    //去重
                    if (this.unitFeign.findUnitByCondition(unitDto) > 0) {
                        flag = false;
                        importErrorMsg.append("单元编号与小区编号不匹配;");
                    }
//                ResultBean<Unit> unitResultBean = this.getUnit(unitDto,rowNum,onLineUser);
//                Unit unit = unitResultBean.getData();
//                if(null == unit || null == unit.getId()){
//                    return new ResultBean<>("200",unitResultBean.getMsg());
                } else {
                    RoomDto roomDtoIsExit = new RoomDto();
                    long unitId = unit.getId();
                    roomDtoIsExit.setUnitId(unitId);
                    roomDtoIsExit.setName(name);
                    //没必要做缓存
                    if (this.roomFeign.findRoomByCondition(roomDtoIsExit) > 0) {
                        flag = false;
                        importErrorMsg.append("房间已存在；");
                    }
                    roomDto.setId(IdWorker.getId());
                    roomDto.setUnitName(unit.getName());
                    roomDto.setUnitId(unit.getId());
                    roomDto.setResidentialName(unit.getResidentialName());
                    roomDto.setRootOrgId(unit.getRootOrgId());
                    roomDto.setOrgPosition(unit.getOrgPosition() + roomDto.getId() + SymbolConstant.BACK_SLASH);
                    roomDto.setEstatePosition(unit.getEstatePosition() + roomDto.getId() + SymbolConstant.BACK_SLASH);
                    if (unitMap.containsKey(unitId)) {
                        unitMap.put(unitId, unitMap.get(unitId) + 1);
                        roomDto.setHouseNumber(CommonUtil.autoZeroFilling(4, unit.getRoomNumber() + unitMap.get(unitId)));
                    } else {
                        unitMap.put(unitId, 1);
                        roomDto.setHouseNumber(CommonUtil.autoZeroFilling(4, unit.getRoomNumber() + 1));
                    }
                }

                roomDto.setHouseType(getCellValue(row.getCell(3)));
                roomDto.setFloor(getCellValue(row.getCell(4)));
                roomDto.setOrientation(getCellValue(row.getCell(5)));
                roomDto.setOrnament(getCellValue(row.getCell(6)));
                roomDto.setRemark(getCellValue(row.getCell(8)));
                roomDto.setUserNumber(OperationConstant.ZERO);
                roomDto.setCreateDate(new Date());
                roomDto.setStatus(OperationConstant.ZERO);
                roomDto.setCreateAccountId(onLineUser.getId());

                if (flag) {
                    ResultBean<Boolean> resultBean = this.roomFeign.addRoom(roomDto);
                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
                    } else {
                        roomDto.setImportErrorMsg("后台添加失败，联系管理员;");
                        errorList.add(roomDto);
                    }

                } else {
                    roomDto.setImportErrorMsg(importErrorMsg.toString());
                    errorList.add(roomDto);
                }
            }
            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:住户导入
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<UserDto> readUserExcel_old(MultipartFile file, Account onLineUser, String isUpdate) {
        UserDto userImportExcelDto = new UserDto();
        List<User> list = new ArrayList<>();
        //新增集合
        List<User> addList = new ArrayList<>();
        Map<Long, Integer> residentialMap = new HashMap<>();
        Map<Long, Integer> unitMap = new HashMap<>();
        Map<Long, Integer> roomMap = new HashMap<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                User user = new User();
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行所属小区编号为空，请核实后重新操作");
                }
                String unitName = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(unitName)) {
                    return new ResultBean<>("200", "第" + rowNum + "行单元名称为空，请核实后重新操作");
                }
                String unitNumber = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(unitNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行单元编号为空，请核实后重新操作");
                }
                String roomName = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(roomName)) {
                    return new ResultBean<>("200", "第" + rowNum + "行房间名称为空，请核实后重新操作");
                }
                String houseNumber = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(houseNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行门牌号为空，请核实后重新操作");
                }
                if (!Pattern.matches(REGEX_NUMBER, houseNumber)) {
                    return new ResultBean<>("200", "第" + rowNum + "行门牌号格式错误，请核实后重新操作");
                }
                String name = getCellValue(row.getCell(5));
                if (StringUtils.isBlank(name)) {
                    return new ResultBean<>("200", "第" + rowNum + "行房间名称为空，请核实后重新操作");
                }
                user.setName(name);
                String tel = getCellValue(row.getCell(6));
                if (StringUtils.isBlank(tel)) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户联系方式为空，请核实后重新操作");
                }
                if (!Pattern.matches(REGEX_MOBILE, tel)) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户联系方式格式错误，请核实后重新操作");
                }
                user.setTel(tel);
                String sexName = getCellValue(row.getCell(7));
                if (StringUtils.isBlank(sexName)) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户性别为空，请核实后重新操作");
                }
                int sex = this.getSexBySexName(sexName);
                if (sex == OperationConstant.MINUS_ONE) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户性别填写错误，请核实后重新操作");
                }
                user.setSex(sex);
                String typeName = getCellValue(row.getCell(8));
                String idCard = getCellValue(row.getCell(9));
                if (StringUtils.isBlank(typeName)) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户类型为空，请核实后重新操作");
                }
                int type = this.getTypeByTypeName(typeName);
                if (type == OperationConstant.MINUS_ONE) {
                    return new ResultBean<>("200", "第" + rowNum + "行住户类型填写错误，请核实后重新操作");
                } else {
                    if (type == OperationConstant.ZERO) {
                        if (StringUtils.isBlank(idCard)) {
                            return new ResultBean<>("200", "第" + rowNum + "行业主身份证必填，请核实后重新操作");
                        }
                        if (idCard.length() > 18) {
                            return new ResultBean<>("200", "第" + rowNum + "行身份证格式错误，请核实后重新操作");
                        }
                    }
                }
                user.setIdCard(idCard);
                user.setType(type);
                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                if (null == residential || null == residential.getId()) {
                    return new ResultBean<>("200", residentialResultBean.getMsg());
                }
                long residentialId = residential.getId();
                user.setResidentialId(residentialId);

                UnitDto unitDto = new UnitDto();
                unitDto.setResidentialId(residentialId);
                unitDto.setUnitNumber(unitNumber);
                unitDto.setName(unitName);
                ResultBean<Unit> unitResultBean = this.getUnit(unitDto, rowNum, onLineUser);
                Unit unit = unitResultBean.getData();
                if (null == unit || null == unit.getId()) {
                    return new ResultBean<>("200", unitResultBean.getMsg());
                }
                long unitId = unit.getId();
                user.setUnitId(unitId);

                RoomDto roomDto = new RoomDto();
                roomDto.setResidentialId(residentialId);
                roomDto.setUnitId(unitId);
                roomDto.setName(roomName);
                roomDto.setHouseNumber(houseNumber);
                ResultBean<Room> roomResultBean = this.getRoom(roomDto, rowNum, onLineUser);
                Room room = roomResultBean.getData();
                if (null == room || null == room.getId()) {
                    return new ResultBean<>("200", roomResultBean.getMsg());
                }
                long roomId = room.getId();
                user.setRoomId(roomId);

                UserDto userDto = new UserDto();
                userDto.setRoomId(roomId);
                userDto.setName(name);
                userDto.setTel(tel);
                User dbUser = this.userFeign.findUserByCondition(userDto);
                if (null != dbUser) {
                    if ("1".equals(isUpdate)) {
                        user.setId(dbUser.getId());
                    } else {
                        return new ResultBean<>("200", "第" + rowNum + "行住户信息已存在，请核实后重新操作");
                    }
                }
                user.setRoomName(room.getName());
                user.setUnitName(unit.getName());
                user.setResidentialName(residential.getName());
                user.setRegionProvince(residential.getRegionProvince());
                user.setRegionCity(residential.getRegionCity());
                user.setRegionArea(residential.getRegionArea());
                user.setCheckState(OperationConstant.ZERO);
                user.setRootOrgId(room.getRootOrgId());
                user.setCreateDate(new Date());
                user.setStatus(OperationConstant.ZERO);
                user.setCreateType(OperationConstant.TWO);
                user.setBirthPlace(getCellValue(row.getCell(10)));
                user.setRemark(getCellValue(row.getCell(11)));
                user.setCreateId(onLineUser.getId());
                if (null == user.getId()) {
                    //id不存在 才算新增
                    if (residentialMap.containsKey(residentialId)) {
                        residentialMap.put(residentialId, residentialMap.get(residentialId) + 1);
                    } else {
                        residentialMap.put(residentialId, 1);
                    }
                    if (unitMap.containsKey(unitId)) {
                        unitMap.put(unitId, unitMap.get(unitId) + 1);
                    } else {
                        unitMap.put(unitId, 1);
                    }
                    if (roomMap.containsKey(roomId)) {
                        roomMap.put(roomId, roomMap.get(roomId) + 1);
                    } else {
                        roomMap.put(roomId, 1);
                    }
                    user.setId(IdWorker.getId());
                    addList.add(user);
                }
                user.setOrgPosition(room.getOrgPosition() + user.getId() + SymbolConstant.BACK_SLASH);
                user.setEstatePosition(room.getEstatePosition() + user.getId() + SymbolConstant.BACK_SLASH);
                list.add(user);
            }
            if (!list.isEmpty()) {
                userImportExcelDto.setList(list);
                userImportExcelDto.setAddList(addList);
                userImportExcelDto.setResidentialMap(residentialMap);
                userImportExcelDto.setUnitMap(unitMap);
                userImportExcelDto.setRoomMap(roomMap);
                return new ResultBean<>(ExcelResultEnum.SUCCESS, userImportExcelDto);
            } else {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:住户导入2.0版本
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<Object> readUserExcel(MultipartFile file, Account onLineUser, String isUpdate) {
        UserDto userImportExcelDto = new UserDto();
        List<User> list = new ArrayList<>();
        List<Object> errorList = new ArrayList<>();
        //新增集合
        List<User> addList = new ArrayList<>();
        Map<Long, Integer> residentialMap = new HashMap<>();
        Map<Long, Integer> unitMap = new HashMap<>();
        Map<Long, Integer> roomMap = new HashMap<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_1000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                UserDto userDto = new UserDto();
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    flag = false;
                    importErrorMsg.append("小区编号为空;");
                }
                userDto.setResidentialNumber(residentialNumber);
                String unitNumber = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(unitNumber)) {
                    flag = false;
                    importErrorMsg.append("单元编号为空;");
                }
                userDto.setUnitNumber(unitNumber);
                Unit unit0 = unitFeign.getByUnitNumber(unitNumber);
                if (unit0 == null) {
                    flag = false;
                    importErrorMsg.append("单元编号下无查询到单元;");
                } else {
                    userDto.setUnitName(unit0.getName());
                }
                String houseNumber = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(houseNumber)) {
                    flag = false;
                    importErrorMsg.append("房间编号为空;");
                }
//                if(!Pattern.matches(REGEX_NUMBER, houseNumber)){
//                    return new ResultBean<>("200","第"+rowNum+"行房间编号格式错误，请核实后重新操作");
//                }
                Room room0 = roomFeign.getByRoomNumber(houseNumber);
                if (room0 == null) {
                    flag = false;
                    importErrorMsg.append("房间编号下无查询到房间;");
                } else {
                    userDto.setRoomName(room0.getName());
                }
                String name = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(name)) {
                    flag = false;
                    importErrorMsg.append("姓名为空");
                }
                userDto.setName(name);
                String tel = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(tel)) {
                    flag = false;
                    importErrorMsg.append("联系方式为空;");
                }
//                if (null!=tel&&!Pattern.matches(REGEX_MOBILE, tel)) {
//                    flag = false;
//                    importErrorMsg.append("联系方式格式错误;");
//                }
                userDto.setTel(tel);
                String sexName = getCellValue(row.getCell(5));
                if (StringUtils.isBlank(sexName)) {
                    flag = false;
                    importErrorMsg.append("性别为空;");
                }
                int sex = this.getSexBySexName(sexName);
                if (sex == OperationConstant.MINUS_ONE) {
                    flag = false;
                    importErrorMsg.append("性别填写错误;");
                }
                userDto.setSex(sex);
                String typeName = getCellValue(row.getCell(6));
                String idCard = getCellValue(row.getCell(7));
                if (StringUtils.isBlank(typeName)) {
                    flag = false;
                    importErrorMsg.append("住户类型为空;");
                }
                int type = this.getTypeByTypeName(typeName);
                if (type == OperationConstant.MINUS_ONE) {
                    flag = false;
                    importErrorMsg.append("住户类型填写错误;");
                } else {
                    if (type == OperationConstant.ZERO) {
                        if (StringUtils.isBlank(idCard)) {
                            flag = false;
                            importErrorMsg.append("业主身份证必填;");
                        }
                        if (idCard.length() > 18) {
                            flag = false;
                            importErrorMsg.append("身份证格式错误;");
                        }
                    }
                }
                userDto.setIdCard(idCard);
                userDto.setType(type);
                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                long residentialId = 0L;
                if (null == residential || null == residential.getId()) {
                    flag = false;
                    importErrorMsg.append("小区编号对应的小区不存在；");
                } else {
                    residentialId = residential.getId();
                    userDto.setResidentialId(residentialId);
                    userDto.setResidentialName(residential.getName());
                    userDto.setRegionProvince(residential.getRegionProvince());
                    userDto.setRegionCity(residential.getRegionCity());
                    userDto.setRegionArea(residential.getRegionArea());
                }

                UnitDto unitDto = new UnitDto();
                unitDto.setResidentialId(residentialId);
                unitDto.setUnitNumber(unitNumber);
                if (unit0 != null) {
                    unitDto.setName(unit0.getName());
                } else {
                    unitDto.setName("1xx");
                }

                ResultBean<Unit> unitResultBean = this.getUnit(unitDto, rowNum, onLineUser);
                Unit unit = unitResultBean.getData();
                long unitId = 0L;
                if (null == unit || null == unit.getId()) {
                    flag = false;
                    importErrorMsg.append("单元编号与小区不对应；");
                } else {
                    unitId = unit.getId();
                    userDto.setUnitId(unitId);
                    userDto.setUnitName(unit.getName());
                }

                RoomDto roomDto = new RoomDto();
                roomDto.setResidentialId(residentialId);
                roomDto.setUnitId(unitId);
                if (room0 != null) {
                    roomDto.setName(room0.getName());
                } else {
                    roomDto.setName("1XX");
                }

                roomDto.setHouseNumber(houseNumber);
                ResultBean<Room> roomResultBean = this.getRoom(roomDto, rowNum, onLineUser);
                Room room = roomResultBean.getData();
                long roomId = 0L;
                if (null == room || null == room.getId()) {
                    flag = false;
                    importErrorMsg.append("房间编号与小区、单元编号不对应；");
                } else {
                    roomId = room.getId();
                    userDto.setRoomId(roomId);
                    userDto.setRoomName(room.getName());
                    userDto.setRootOrgId(room.getRootOrgId());
                }

                UserDto userDtoIsExist = new UserDto();
                userDtoIsExist.setRoomId(roomId);
                userDtoIsExist.setName(name);
                userDtoIsExist.setTel(tel);
                User dbUser = this.userFeign.findUserByCondition(userDtoIsExist);
                if (null != dbUser) {
                    if ("1".equals(isUpdate)) {
                        userDto.setId(dbUser.getId());
                    } else {
                        flag = false;
                        importErrorMsg.append("住户信息已存在;");
                    }
                }

//                user.setCheckState(OperationConstant.ZERO);
                userDto.setCheckState(OperationConstant.MINUS_ONE); //未上传人脸状态
                userDto.setCreateDate(new Date());
                userDto.setStatus(OperationConstant.ZERO);
                userDto.setCreateType(OperationConstant.TWO);
                userDto.setBirthPlace(getCellValue(row.getCell(8)));
                userDto.setRemark(getCellValue(row.getCell(9)));
                userDto.setCreateId(onLineUser.getId());
                userDto.setIsMember(OperationConstant.ZERO); //未激活APP
                if (null == userDto.getId()) {
                    //id不存在 才算新增
                    if (residentialId != 0L && residentialMap.containsKey(residentialId)) {
                        residentialMap.put(residentialId, residentialMap.get(residentialId) + 1);
                    } else if (residentialId != 0L) {
                        residentialMap.put(residentialId, 1);
                    }
                    if (unitId != 0L && unitMap.containsKey(unitId)) {
                        unitMap.put(unitId, unitMap.get(unitId) + 1);
                    } else if (unitId != 0L) {
                        unitMap.put(unitId, 1);
                    }
                    if (roomMap.containsKey(roomId)) {
                        roomMap.put(roomId, roomMap.get(roomId) + 1);
                    } else {
                        roomMap.put(roomId, 1);
                    }
                    userDto.setId(IdWorker.getId());
                }
                if (room != null) {
                    userDto.setOrgPosition(room.getOrgPosition() + userDto.getId() + SymbolConstant.BACK_SLASH);
                    userDto.setEstatePosition(room.getEstatePosition() + userDto.getId() + SymbolConstant.BACK_SLASH);
                }

                if (flag) {
                    ResultBean<Boolean> resultBean = this.userFeign.addUser(userDto);
                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
                    } else {
                        roomDto.setImportErrorMsg("后台添加失败，联系管理员;");
                        errorList.add(userDto);
                    }

                } else {
                    userDto.setImportErrorMsg(importErrorMsg.toString());
                    errorList.add(userDto);
                }
            }
            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:住户卡导入
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<Object> readUserCardExcel(MultipartFile file, Account onLineUser) {
        List<AccessCard> list = new ArrayList<>();
        Workbook workbook = null;
        List<Object> errorList = new ArrayList<>();
        InputStream is = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 7){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //文件数据量太大
            if (sheet.getPhysicalNumberOfRows() > 2000 && sheet.getLastRowNum() > 2000) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_2000);
            }
            int count = sheet.getLastRowNum();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                AccessCardDto accessCardDto = new AccessCardDto();
                String residentialNumber = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(residentialNumber)) {
                    flag = false;
                    importErrorMsg.append("所属小区编号为空;");
                }
                accessCardDto.setResidentialNumber(residentialNumber);
                String unitNumber = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(unitNumber)) {
                    flag = false;
                    importErrorMsg.append("所属单元编号为空;");
                }
                accessCardDto.setUnitNumber(unitNumber);
                String houseNumber = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(houseNumber)) {
                    flag = false;
                    importErrorMsg.append("所属房间编号为空;");
                }
                accessCardDto.setHouseNumber(houseNumber);
                String userName = getCellValue(row.getCell(3));
                if (StringUtils.isBlank(userName)) {
                    flag = false;
                    importErrorMsg.append("住户姓名为空;");
                }
                accessCardDto.setUserName(userName);
                String cardNo = getCellValue(row.getCell(4));
                if (StringUtils.isBlank(cardNo)) {
                    flag = false;
                    importErrorMsg.append("卡号为空;");
                }
                accessCardDto.setCardNo(cardNo);
                String beginDate = getCellValue(row.getCell(5));
                if (StringUtils.isBlank(beginDate)) {
                    flag = false;
                    importErrorMsg.append("卡号开始有效期为空;");
                } else {
                    try {
                        Date date = dateFormat.parse(beginDate);
                        accessCardDto.setBeginDate(date);
                    } catch (ParseException e) {
                        flag = false;
                        importErrorMsg.append("卡号开始有效期有误;");
                    }
                }
                String endDate = getCellValue(row.getCell(6));
                if (StringUtils.isBlank(endDate)) {
                    flag = false;
                    importErrorMsg.append("卡号结束有效期为空;");
                }else {
                    try {
                        Date date = dateFormat.parse(endDate);
                        accessCardDto.setEndDate(date);
                    } catch (ParseException e) {
                        flag = false;
                        importErrorMsg.append("卡号结束有效期有误;");
                    }
                }

                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                long residentialId = 0L;
                if (null == residential || null == residential.getId()) {
                    flag = false;
                    importErrorMsg.append("小区编号对应的小区不存在;");
                } else {
                    residentialId = residential.getId();
                    accessCardDto.setResidentialName(residential.getName());
                }

                accessCardDto.setResidentialId(residentialId);

                UnitDto unitDto = new UnitDto();
                unitDto.setResidentialId(residentialId);
                unitDto.setUnitNumber(unitNumber);
                ResultBean<Unit> unitResultBean = this.getUnitByAccessCard(unitDto, rowNum);
                Unit unit = unitResultBean.getData();
                long unitId = 0L;
                if (null == unit || null == unit.getId()) {
                    flag = false;
                    importErrorMsg.append("单元编号与小区编号不对应;");
                } else {
                    unitId = unit.getId();
                    accessCardDto.setUnitName(unit.getName());
                }

                accessCardDto.setUnitId(unitId);

                RoomDto roomDto = new RoomDto();
                roomDto.setUnitId(unitId);
                roomDto.setHouseNumber(houseNumber);
                ResultBean<Room> roomResultBean = this.getRoomByAccessCard(roomDto, rowNum);
                Room room = roomResultBean.getData();
                long roomId = 0L;
                if (null == room || null == room.getId()) {
                    flag = false;
                    importErrorMsg.append("房间编号与小区、单元编号不对应;");
                } else {
                    roomId = room.getId();
                    accessCardDto.setRoomName(room.getName());
                }
                accessCardDto.setRoomId(roomId);

                UserDto userDto = new UserDto();
                userDto.setRoomId(roomId);
                userDto.setName(userName);
                HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
                StringBuffer sb = new StringBuffer(roomId + "" + userName);
                String hashKey = sb.toString();
                String json = hashOperations.get(IMPORT_CACHE_USER_NMAE, hashKey);
                User user;
                long userId = 0L;
                if (StringUtils.isEmpty(json)) {
                    user = this.userFeign.findUserByName(userDto);
                    if (null == user || null == user.getId()) {
                        flag = false;
                        importErrorMsg.append("所属住户姓名不存在;");
                    }else {
                        user = JsonUtils.jsonToPojo(json, User.class);
                        userId = user.getId();
                        accessCardDto.setUserName(user.getName());
                        accessCardDto.setRootOrgId(user.getRootOrgId());
                        accessCardDto.setOrgPosition(user.getOrgPosition());
                    }
                    json = JsonUtils.objectToJson(user);
                    hashOperations.put(IMPORT_CACHE_USER_NMAE, hashKey, json);
                }
                accessCardDto.setUserId(String.valueOf(userId));

                AccessCardDto accessCardDtoIsExist = new AccessCardDto();
                accessCardDtoIsExist.setResidentialId(residentialId);
                accessCardDtoIsExist.setCardNo(cardNo);
                List<AccessCard> accessCardList = accessCardFeign.findAccessCardByCondition(accessCardDtoIsExist);
                if (null != accessCardList && !accessCardList.isEmpty()) {
                    flag = false;
                    importErrorMsg.append("卡号已存在;");
                }

                accessCardDto.setType(OperationConstant.ZERO);
                accessCardDto.setCreateDate(new Date());
                accessCardDto.setStatus(OperationConstant.ZERO);
                accessCardDto.setCreateAccountId(onLineUser.getId());
                if (flag) {
                    ResultBean<Boolean> resultBean = this.accessCardFeign.addAccessCard(accessCardDto);
                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
                    } else {
                        accessCardDto.setImportErrorMsg("后台添加失败，联系管理员;");
                        errorList.add(accessCardDto);
                    }

                } else {
                    accessCardDto.setImportErrorMsg(importErrorMsg.toString());
                    errorList.add(accessCardDto);
                }
            }
            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:管理卡导入
     *
     * @param file onLineUser
     * @return ResultBean<ResidentialDto>
     *//*
    public ResultBean<Object> readAccessCardExcel(MultipartFile file, Account onLineUser) {
        List<AccessCard> list = new ArrayList<>();
        List<Object> errorList = new ArrayList<>();
        Workbook workbook = null;
        InputStream is = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
                return new ResultBean<>(ExcelResultEnum.FILE_TYPE_ERROR);
            }
            is = file.getInputStream();
            if (fileName.matches(REGEX_EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.matches(REGEX_EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            //默认第一页
            Sheet sheet = workbook.getSheetAt(0);
            //空白页或空白内容
            if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
            }
            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 6){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
            //  获取第2000行数据
            Row maxRow = sheet.getRow(2001);
            //  判断是否超出大小
            if (null != maxRow && org.springframework.util.StringUtils.hasText(getCellValue(maxRow.getCell(0)))) {
                return new ResultBean<>(ExcelResultEnum.FILE_IS_BIG_2000);
            }
            long nowTime = System.currentTimeMillis();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int count = sheet.getLastRowNum();
            List<AccessCardDto> accessCardList = new ArrayList<>();
            for (int j = 1; j <= count; j++) {
                //判断该行数据是否有误
                boolean flag = true;
                //造成行数据导入失败的错误信息
                StringBuffer importErrorMsg = new StringBuffer();
                int rowNum = j + 1;
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                AccessCardDto accessCardDto = new AccessCardDto();
                String cardNo = getCellValue(row.getCell(0));
                if (StringUtils.isBlank(cardNo)) {
                    flag = false;
                    importErrorMsg.append("卡号为空;");
                }
                accessCardDto.setCardNo(cardNo);
                String beginDate = getCellValue(row.getCell(1));
                if (StringUtils.isBlank(beginDate)) {
                    flag = false;
                    importErrorMsg.append("卡号开始有效期为空;");
                } else {
                    try {
                        Date date = dateFormat.parse(beginDate);
                        accessCardDto.setBeginDate(date);
                    } catch (ParseException e) {
                        flag = false;
                        importErrorMsg.append("卡号开始有效期有误;");
                    }
                }

                String endDate = getCellValue(row.getCell(2));
                if (StringUtils.isBlank(endDate)) {
                    flag = false;
                    importErrorMsg.append("卡号结束有效期为空;");
                }
                //  判断有效期是否已小于当前时间
                try {
                    Date parse = dateFormat.parse(endDate);
                    accessCardDto.setEndDate(parse);
                    if (parse.getTime() < nowTime) {
                        flag = false;
                        importErrorMsg.append("卡号有效期已超时;");
                    }
                } catch (ParseException e) {
                    flag = false;
                    importErrorMsg.append("卡号结束有效期有误;");
                }
                String residentialNumber = getCellValue(row.getCell(3));
                accessCardDto.setResidentialNumber(residentialNumber);
                if (StringUtils.isBlank(residentialNumber)) {
                    flag = false;
                    importErrorMsg.append("所属小区编号为空;");
                }
                ResultBean<Residential> residentialResultBean = this.getResidential(residentialNumber, rowNum);
                Residential residential = residentialResultBean.getData();
                long residentialId = 0L;
                if (null == residential || null == residential.getId()) {
                    flag = false;
                    importErrorMsg.append("小区编号对应的小区不存在;");
                } else {
                    residentialId = residential.getId();
                    accessCardDto.setResidentialId(residentialId);
                    accessCardDto.setResidentialName(residential.getName());
                    accessCardDto.setOrgPosition(residential.getOrgPosition());
                    accessCardDto.setEstatePosition(residential.getEstatePosition());
                    accessCardDto.setType(OperationConstant.THREE);
                    accessCardDto.setRootOrgId(residential.getRootOrgId());
                }


                String unitNumber = getCellValue(row.getCell(4));
                accessCardDto.setUnitNumber(unitNumber);
                if (StringUtils.isNotBlank(unitNumber)) {
                    UnitDto unitDto = new UnitDto();
                    unitDto.setResidentialId(residentialId);
                    unitDto.setUnitNumber(unitNumber);
                    ResultBean<Unit> unitResultBean = this.getUnitByAccessCard(unitDto, rowNum);
                    Unit unit = unitResultBean.getData();
                    long unitId = 0L;
                    if (null == unit || null == unit.getId()) {
                        flag = false;
                        importErrorMsg.append("单元编号与小区编号不对应;");
                    } else {
                        unitId = unit.getId();
                        accessCardDto.setUnitId(unitId);
                        accessCardDto.setUnitName(unit.getName());
                        accessCardDto.setType(OperationConstant.TWO);
                        accessCardDto.setOrgPosition(unit.getOrgPosition());
                        accessCardDto.setEstatePosition(unit.getEstatePosition());
                    }


                    String houseNumber = getCellValue(row.getCell(5));
                    accessCardDto.setHouseNumber(houseNumber);
                    if (StringUtils.isNotBlank(houseNumber)) {
                        RoomDto roomDto = new RoomDto();
                        roomDto.setUnitId(unitId);
                        roomDto.setHouseNumber(houseNumber);
                        ResultBean<Room> roomResultBean = this.getRoomByAccessCard(roomDto, rowNum);
                        Room room = roomResultBean.getData();
                        long roomId = 0L;
                        if (null == room || null == room.getId()) {
                            flag = false;
                            importErrorMsg.append("房间编号与小区、单元编号不对应;");
                        }else {
                            roomId = room.getId();
                            accessCardDto.setRoomId(roomId);
                            accessCardDto.setRoomName(room.getName());
                            accessCardDto.setType(OperationConstant.ONE);
                            accessCardDto.setOrgPosition(room.getOrgPosition());
                            accessCardDto.setEstatePosition(room.getEstatePosition());
                        }
                    }
                }

                accessCardDto.setCreateDate(new Date());
                accessCardDto.setStatus(OperationConstant.ZERO);
                accessCardDto.setCreateAccountId(onLineUser.getId());

                ResultBean<AccessCardDto> resultBean = this.accessCardFeign.simpleAddOrUpdateUserCard(accessCardDto);
                if(resultBean.getData() != null){
                    accessCardList.add(resultBean.getData());
                }
//                if (flag) {
//                    ResultBean<Boolean> resultBean = this.accessCardFeign.addAccessCard(accessCardDto);
//                    System.out.println(resultBean.getCode() + " " + resultBean.getData() + " " + resultBean.getMsg());
//                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
//                    } else {
//                        accessCardDto.setImportErrorMsg("后台添加失败，联系管理员;");
//                        errorList.add(accessCardDto);
//                    }
//
//                } else {
//                    accessCardDto.setImportErrorMsg(importErrorMsg.toString());
//                    errorList.add(accessCardDto);
//                }
            }
            if (!errorList.isEmpty()) {
                return new ResultBean<>(ExcelResultEnum.SUCCESS_ERROR, errorList);
            } else {
                //批量不记名门禁卡下发
                if(accessCardList.size() > 0){
                    this.accessCardFeign.pushAccessCardBatch(accessCardList);
                }
                return new ResultBean<>(ExcelResultEnum.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 功能描述:获取单元格中的对象
     *
     * @param cell 一格
     * @return String
     *//*
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellTypeEnum()) {
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
                }
                return new BigDecimal(cell.getNumericCellValue()).toString().trim();
            case STRING:
                return StringUtils.trimToEmpty(cell.getStringCellValue());
            case FORMULA:
                return StringUtils.trimToEmpty(cell.getCellFormula());
            case BLANK:
                return null;
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case ERROR:
                return null;
            default:
                return cell.toString().trim();
        }
    }

    *//**
     * 功能描述:根据名称和层级获取区域
     *
     * @param regionProvince 省名称
     * @param regionCity     市名称
     * @param regionArea     区名称
     * @return Area
     *//*
    private AreaDto getArea(String regionProvince, String regionCity, String regionArea) {
        AreaDto dto = new AreaDto();
        dto.setRegionProvince(regionProvince);
        dto.setRegionCity(regionCity);
        dto.setRegionArea(regionArea);
        Map<String, Object> map = this.areaFeign.selectByNameAndLayer(dto);
        if (map != null) {
            dto.setRegionProvince(String.valueOf((map.get("regionProvince"))));
            dto.setRegionCity(String.valueOf((map.get("regionCity"))));
            dto.setRegionArea(String.valueOf((map.get("regionArea"))));
            dto.setRegionName(String.valueOf((map.get("regionName"))));
        } else {
            dto = null;
        }

        return dto;
    }

    *//**
     * 功能描述:获取小区并存入缓存
     *
     * @param residentialNumber 小区编号
     * @param rowNum            行好
     * @return ResultBean<Residential>
     *//*
    private ResultBean<Residential> getResidential(String residentialNumber, int rowNum) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        String hashKey = residentialNumber;
        String json = hashOperations.get(IMPORT_CACHE_RESIDENTIAL_CODE, hashKey);
        Residential residential;
        if (StringUtils.isEmpty(json)) {
            residential = this.residentialFeign.findResidentialByNumber(residentialNumber);
            if (null == residential || null == residential.getId()) {
                return new ResultBean<>("200", "第" + rowNum + "行所属小区编号不存在，请核实后重新操作");
            } else {
                json = JsonUtils.objectToJson(residential);
                hashOperations.put(IMPORT_CACHE_RESIDENTIAL_CODE, hashKey, json);
            }
        } else {
            residential = JsonUtils.jsonToPojo(json, Residential.class);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, residential);
    }

    *//**
     * 功能描述:获取单元 并存入缓存
     *
     * @param dto        单元业务对象
     * @param rowNum     行号
     * @param onLineUser 登陆用户
     * @return ResultBean<Unit>
     *//*
    private ResultBean<Unit> getUnit(UnitDto dto, int rowNum, Account onLineUser) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        long residentialId = dto.getResidentialId();
        String unitName = dto.getName();
        String unitNumber = dto.getUnitNumber();
        StringBuffer sb = new StringBuffer(residentialId + "-" + unitName + "-" + unitNumber);
        String hashKey = sb.toString();
        String json = hashOperations.get(IMPORT_CACHE_UNIT_CODE_NAME, hashKey);
        Unit unit;
        if (StringUtils.isEmpty(json)) {
            unit = this.unitFeign.findUnitByNameAndNumber(dto);
            if (null == unit || null == unit.getId()) {
                //去重
                if (this.unitFeign.findUnitByCondition(dto) > 0) {
                    return new ResultBean<>("200", "第" + rowNum + "行单元名称与编号不匹配，请核实后重新操作");
                }
                //新增单元
                unit = new Unit();
                unit.setCreateAccountId(onLineUser.getId());
                unit.setResidentialId(residentialId);
                unit.setUnitNumber(unitNumber);
                unit.setName(unitName);
                unit = this.unitFeign.addUnitByImport(unit);
                if (null != unit && null == unit.getId()) {
                    return new ResultBean<>("200", "第" + rowNum + "行生成单元信息有误，请核实后重新操作");
                }
            }
            json = JsonUtils.objectToJson(unit);
            hashOperations.put(IMPORT_CACHE_UNIT_CODE_NAME, hashKey, json);
        } else {
            unit = JsonUtils.jsonToPojo(json, Unit.class);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, unit);
    }

    *//**
     * 功能描述:获取小区，并存入缓存
     *
     * @param dto        单元业务对象
     * @param rowNum     行号
     * @param onLineUser 登陆用户
     * @return ResultBean<Room>
     *//*
    private ResultBean<Room> getRoom(RoomDto dto, int rowNum, Account onLineUser) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        long residentialId = dto.getResidentialId();
        long unitId = dto.getUnitId();
        String roomName = dto.getName();
        String houseNumber = dto.getHouseNumber();
        StringBuffer sb = new StringBuffer(residentialId + "" + unitId + "-" + roomName + "-" + houseNumber);
        String hashKey = sb.toString();
        String json = hashOperations.get(IMPORT_CACHE_ROOM_CODE_NAME, hashKey);
        Room room;
        if (StringUtils.isEmpty(json)) {
            room = this.roomFeign.findRoomByNameAndNumber(dto);
            if (null == room || null == room.getId()) {
                //去重
                if (this.roomFeign.findRoomByCondition(dto) > 0) {
                    return new ResultBean<>("200", "第" + rowNum + "行房间名称与门牌号不匹配，请核实后重新操作");
                }
                room = new Room();
                room.setCreateAccountId(onLineUser.getId());
                room.setResidentialId(residentialId);
                room.setUnitId(unitId);
                room.setHouseNumber(houseNumber);
                room.setName(roomName);
                room = this.roomFeign.addRoomByImport(room);
                if (null != room && null == room.getId()) {
                    return new ResultBean<>("200", "第" + rowNum + "行生成房间信息有误，请核实后重新操作");
                }
            }
            json = JsonUtils.objectToJson(room);
            hashOperations.put(IMPORT_CACHE_ROOM_CODE_NAME, hashKey, json);
        } else {
            room = JsonUtils.jsonToPojo(json, Room.class);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, room);
    }

    *//**
     * 功能描述:住户卡或卡管理 获取单元 并存入缓存
     *
     * @param dto    单元业务对象
     * @param rowNum 行号
     * @return ResultBean<Unit>
     *//*
    private ResultBean<Unit> getUnitByAccessCard(UnitDto dto, int rowNum) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        long residentialId = dto.getResidentialId();
        String unitNumber = dto.getUnitNumber();
        StringBuffer sb = new StringBuffer(residentialId + "" + unitNumber);
        String hashKey = sb.toString();
        String json = hashOperations.get(IMPORT_CACHE_UNIT_CODE, hashKey);
        Unit unit;
        if (StringUtils.isEmpty(json)) {
            unit = this.unitFeign.findUnitByNameAndNumber(dto);
            if (null == unit || null == unit.getId()) {
                return new ResultBean<>("200", "第" + rowNum + "行所属单元编号不存在，请核实后重新操作");
            }
            json = JsonUtils.objectToJson(unit);
            hashOperations.put(IMPORT_CACHE_UNIT_CODE, hashKey, json);
        } else {
            unit = JsonUtils.jsonToPojo(json, Unit.class);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, unit);
    }

    *//**
     * 功能描述:住户卡或卡管理 获取房间元 并存入缓存
     *
     * @param dto    房间业务对象
     * @param rowNum 行号
     * @return ResultBean<Room>
     *//*
    private ResultBean<Room> getRoomByAccessCard(RoomDto dto, int rowNum) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        long unitId = dto.getUnitId();
        String houseNumber = dto.getHouseNumber();
        StringBuffer sb = new StringBuffer(unitId + "" + houseNumber);
        String hashKey = sb.toString();
        String json = hashOperations.get(IMPORT_CACHE_ROOM_CODE, hashKey);
        Room room;
        if (StringUtils.isEmpty(json)) {
            room = this.roomFeign.findRoomByNameAndNumber(dto);
            if (null == room || null == room.getId()) {
                return new ResultBean<>("200", "第" + rowNum + "行所属房间编号不存在，请核实后重新操作");
            }
            json = JsonUtils.objectToJson(room);
            hashOperations.put(IMPORT_CACHE_ROOM_CODE, hashKey, json);
        } else {
            room = JsonUtils.jsonToPojo(json, Room.class);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, room);
    }*/

    /**
     * 功能描述:根据类型名称获取类型状态
     *
     * @param typeName 类型名称
     * @return int
     */
    private int getTypeByTypeName(String typeName) {
        if(null == typeName){
            return -1;
        }
        switch (typeName) {
            case "业主":
                return 0;
            case "家属":
                return 1;
            case "租客":
                return 2;
            default:
                return -1;
        }
    }

    /**
     * 功能描述:根据性别名称获取性别状态
     *
     * @param sexName 性别名称
     * @return int
     */
    private int getSexBySexName(String sexName) {
        if(null == sexName){
            return -1;
        }
        switch (sexName) {
            case "未定义":
                return 0;
            case "男":
                return 1;
            case "女":
                return 2;
            default:
                return -1;
        }
    }

	/**
	 * 功能描述:获取单元格中的对象
	 *
	 * @param cell 一格
	 * @return String
	 */
	private static String getCellValue(Cell cell) {
		if (cell == null) {
			return null;
		}
		switch (cell.getCellTypeEnum()) {
			case NUMERIC:
				String cellValue = "";
				if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
					short format = cell.getCellStyle().getDataFormat();
					if (format == 0){
						DecimalFormat df = new DecimalFormat("#");
						cellValue = df.format(cell.getNumericCellValue());
					}else if (format == 14 || format == 31 || format == 57 || format == 58 || format == 20 || format == 32){
						SimpleDateFormat sdf = null;
						if(format == 14 || format == 31 || format == 57 || format == 58){
							//日期
							sdf = new SimpleDateFormat("yyyy-MM-dd");
						}else if (format == 20 || format == 32) {
							//时间
							sdf = new SimpleDateFormat("HH:mm");
						}
						double value = cell.getNumericCellValue();
						Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
						cellValue = sdf.format(date);
					}else {
						cellValue = new BigDecimal(cell.getNumericCellValue()).toString().trim();
					}

				}
				return cellValue;
//				if (DateUtil.isCellDateFormatted(cell)) {
//					return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
//				}
//				return new BigDecimal(cell.getNumericCellValue()).toString().trim();
			case STRING:
				return StringUtils.trimToEmpty(cell.getStringCellValue());
			case FORMULA:
				return StringUtils.trimToEmpty(cell.getCellFormula());
			case BLANK:
				return null;
			case BOOLEAN:
				return String.valueOf(cell.getBooleanCellValue());
			case ERROR:
				return null;
			default:
				return cell.toString().trim();
		}
	}

	/**
	 * 功能描述: 社区信息导入
	 * @param file
	 * @return
	 */
	public R readAgencyExcel(MultipartFile file) {
		List<Object> errorList = new ArrayList<>();

		InputStream is = null;
		try {
			String fileName = file.getOriginalFilename();
			if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
				return R.data("文件格式不合法！");
			}
			is = file.getInputStream();
//			Workbook workbook = new XSSFWorkbook(is);
			Workbook workbook = new HSSFWorkbook(is);
			/*Workbook workbook = null;
			if (fileName.matches(REGEX_EXCEL2007)) {
				workbook = new XSSFWorkbook(is);
			}
			if (fileName.matches(REGEX_EXCEL2003)) {
				workbook = new HSSFWorkbook(is);
			}*/
			//默认第一页
			Sheet sheet = workbook.getSheetAt(0);
			//空白页或空白内容
			if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
				return R.data("文件内容格式不对！");
			}
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
			//文件数据量太大
//            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
//                return R.data("文件过大！");
//            }
			List<Agency> list = new ArrayList<>();
			int count = sheet.getLastRowNum();
			for (int j = 1; j <= count; j++) {
				//判断该行数据是否有误
				boolean flag = true;
				//造成行数据导入失败的错误信息
				StringBuffer importErrorMsg = new StringBuffer();
				Row row = sheet.getRow(j);
				if (null == row) {
					continue;
				}

				Agency agency = new Agency();

				// 社区名称
				String agencyName = getCellValue(row.getCell(4));
				if (StringUtils.isBlank(agencyName)) {
					flag = false;
					importErrorMsg.append("社区名称为空；");
				}
				agency.setAgencyName(agencyName);

				// 省ID
				String regionProvince = getCellValue(row.getCell(0));
				if (StringUtils.isNotBlank(regionProvince)){
					regionProvince = regionProvince.split("_")[1];
					agency.setRegionProvince(regionProvince);
				}else {
					flag = false;
					importErrorMsg.append("所属省为空；");
				}


				Agency one = agencyService.getOne(Condition.getQueryWrapper(agency));
				if (one != null) {
					agency = one;
				}

				// 市ID
				String regionCity = getCellValue(row.getCell(1));
				if (StringUtils.isNotBlank(regionCity)){
					regionCity = regionCity.split("_")[1];
					agency.setRegionCity(regionCity);
				}else {
					flag = false;
					importErrorMsg.append("所属市为空；");
				}

				// 区/县ID
				String regionArea = getCellValue(row.getCell(2));
				if (StringUtils.isNotBlank(regionArea)){
					regionArea = regionArea.split("_")[1];
					agency.setRegionArea(regionArea);
				}else {
					flag = false;
					importErrorMsg.append("所属区/县ID为空；");
				}


				// 所属街道
				String regionStreet = getCellValue(row.getCell(3));

				if (StringUtils.isNotBlank(regionStreet)){
					regionStreet = regionStreet.split("_")[1];
					agency.setRegionStreet(regionStreet);
				}else {
					flag = false;
					importErrorMsg.append("所属街道为空；");
				}

				// 负责人名称
				String address = getCellValue(row.getCell(5));
				agency.setAddress(address);

				// 注册地址
				String personName = getCellValue(row.getCell(6));
				agency.setPersonName(personName);

				// 负责人联系方式
				String personPhone = getCellValue(row.getCell(7));
				agency.setPersonPhone(personPhone);

				agency.setOrgPosition("/" + regionProvince + "/" + regionCity + "/" + regionArea + "/" + regionStreet);
				if (agencyService.saveOrUpdate(agency)){
					agency.setOrgPosition(agency.getOrgPosition() + "/" + agency.getId());
					list.add(agency);
				}
			}

			boolean b = agencyService.saveOrUpdateBatch(list);

		} catch (IOException e) {
			e.printStackTrace();
			return R.data("服务器异常！");
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return R.status(true);
	}

	/**
	 * 功能描述: 小区信息导入
	 * @param file
	 * @return
	 */
	public R readResidentialExcel(MultipartFile file, HttpServletResponse response) {
		List<ResidentialImportModule> errorList = new ArrayList<>();
		InputStream is = null;
		try {
			String fileName = file.getOriginalFilename();
			if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
				return R.data("文件格式不合法！");
			}
			is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
			//默认第一页
			Sheet sheet = workbook.getSheetAt(0);
			//空白页或空白内容
			if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
				return R.data("文件内容格式不对！");
			}
//            //文件格式错误
//            if(sheet.getRow(0) != null &&  sheet.getRow(0).getPhysicalNumberOfCells() != 12){
//                return new ResultBean<>(ExcelResultEnum.FILE_CONTENT_ERROR);
//            }
			//文件数据量太大
//            if (sheet.getPhysicalNumberOfRows() > 1000 && sheet.getLastRowNum() > 1000) {
//                return R.data("文件过大！");
//            }
			List<Residential> list = new ArrayList<>();
			int count = sheet.getLastRowNum();
			for (int j = 1; j <= count; j++) {
				//判断该行数据是否有误
				boolean flag = true;
				//造成行数据导入失败的错误信息
				StringBuffer importErrorMsg = new StringBuffer();
				Row row = sheet.getRow(j);
				if (null == row) {
					continue;
				}

				Residential residential = new Residential();
				// 小区名字
				String residentialName = getCellValue(row.getCell(0));
				if (StringUtils.isBlank(residentialName)) {
					flag = false;
					importErrorMsg.append("小区名称为空；");
				}
				residential.setName(residentialName);

				// 社区名称
				String agencyName = getCellValue(row.getCell(1));
				Agency agency = new Agency();
				if (StringUtils.isNotBlank(agencyName)){
					agency.setAgencyName(agencyName);

					agency = agencyService.getOne(Condition.getQueryWrapper(agency));
					if (agency != null){
						residential.setAgencyId(agency.getId());

						try {
							// 如果小区已存在（根据社区id和小区名称匹配），则只做更新操作
							Residential residen = residentialService.getOne(Condition.getQueryWrapper(residential));
							if (residen != null){
								residential = residen;
							}
						}catch (MyBatisSystemException e){
							System.out.println( "小区=" + residentialName + "TooManyResultsException······"+ e.getMessage());
						}


						residential.setRegionProvince(agency.getRegionProvince());
						residential.setRegionCity(agency.getRegionCity());
						residential.setRegionArea(agency.getRegionArea());
					}else {
						flag = false;
						importErrorMsg.append("找不到对应社区；" + agencyName);
					}
				}else{
					flag = false;
					importErrorMsg.append("社区名称为空；");
				}

				// 详细地址
				String address = getCellValue(row.getCell(2));
				residential.setAddress(address);

				// 物业名称
				String estatePidName = getCellValue(row.getCell(3));
				residential.setEstatePidName(estatePidName);

				// 物业电话
				String estatePidPhone = getCellValue(row.getCell(4));
				residential.setEstatePidPhone(estatePidPhone);

				// 负责人
				String personName = getCellValue(row.getCell(5));
				residential.setPersonName(personName);

				// 负责人电话
				String  personTel = getCellValue(row.getCell(6));
				residential.setPersonTel(personTel);

				if (!flag) {
					System.out.println("导入错误信息----" + importErrorMsg);
					errorList.add(residentialToImportModule(residential));
				}else{

					residentialService.saveOrUpdate(residential);
					residential.setOrgPosition(agency.getOrgPosition() + "/" + residential.getId());
					list.add(residential);
				}

//				if (!errorList.isEmpty()){
//					this.exportExcelController.writeExcel(response, errorList,"",null,new ResidentialImportModule());
//				}

			}

			boolean b = residentialService.saveOrUpdateBatch(list);

		} catch (IOException e) {
			e.printStackTrace();
			return R.data("服务器异常！");
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return R.status(true);
	}

	public ResidentialImportModule residentialToImportModule(Residential residential){
		ResidentialImportModule module = new ResidentialImportModule();
		module.setName(residential.getName());
		module.setAgencyName(residential.getAgencyId());
		return module;
	}

	public R readCarExcel(MultipartFile file, HttpServletResponse response) {
		List<ResidentialImportModule> errorList = new ArrayList<>();
		InputStream is = null;
		try {
			String fileName = file.getOriginalFilename();
			if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
				return R.data("文件格式不合法！");
			}
			is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
			//默认第一页
			Sheet sheet = workbook.getSheetAt(0);
			//空白页或空白内容
			if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
				return R.data("文件内容格式不对！");
			}

			List<Car> list = new ArrayList<>();
			List<CarEnterRecord> listEnterRecord = new ArrayList<>();
			List<CarOutRecord> listOutRecord = new ArrayList<>();

			int count = sheet.getLastRowNum();
			for (int j = 1; j <= count; j++) {
				//判断该行数据是否有误
				boolean flag = true;
				//造成行数据导入失败的错误信息
				StringBuffer importErrorMsg = new StringBuffer();
				Row row = sheet.getRow(j);
				if (null == row) {
					continue;
				}

				Car car = new Car();

				// 车牌号
				String carNumber = getCellValue(row.getCell(2));
				if (StringUtil.isNotBlank(carNumber)){
					car.setNumber(carNumber);
					Car one = carService.getOne(Condition.getQueryWrapper(car));
					if (one != null){
						car = one;
					}
				}

				// 企业名称
				String enterpriseName = getCellValue(row.getCell(0));
				if (StringUtils.isBlank(enterpriseName)) {
					flag = false;
					importErrorMsg.append("企业名称为空；");
				}
				Enterprise wrapper = new Enterprise();
				wrapper.setEnterpriseName(enterpriseName);
				Enterprise enterprise = enterpriseService.getOne(Condition.getQueryWrapper(wrapper));
				if (enterprise != null){
					car.setEnterpriseId(enterprise.getId());
					car.setAgencyId(enterprise.getAgencyId());
					car.setResidentialId(enterprise.getResidentialId());
//					car.setOrgPosition(enterprise.getOrgPosition());

					// 车主姓名
					String personName = getCellValue(row.getCell(1));
					car.setPersonName(personName);

					// 车主电话
					String personPhone = getCellValue(row.getCell(3));
					car.setPersonPhone(personPhone);

					if (car.getId() == null){
						carService.save(car);
					}
					car.setOrgPosition(enterprise.getOrgPosition() + "/" + car.getId());
					list.add(car);

					String carOrgPosition = car.getOrgPosition();

					//更新车辆进出记录
					CarEnterRecord enterWrapper = new CarEnterRecord();
					enterWrapper.setCarNo(carNumber);
					List<CarEnterRecord> enterRecordList = enterRecordService.list(Condition.getQueryWrapper(enterWrapper));
					enterRecordList.forEach(item -> {
						item.setAgencyId(enterprise.getAgencyId());
						item.setResidentialId(enterprise.getResidentialId());
						item.setEnterpriseId(enterprise.getId());
						item.setOrgPosition(carOrgPosition);
					});
					listEnterRecord.addAll(enterRecordList);

					CarOutRecord outWrapper = new CarOutRecord();
					outWrapper.setCarNo(carNumber);
					List<CarOutRecord> outRecordList = outRecordService.list(Condition.getQueryWrapper(outWrapper));
					outRecordList.forEach(item -> {
						item.setAgencyId(enterprise.getAgencyId());
						item.setResidentialId(enterprise.getResidentialId());
						item.setEnterpriseId(enterprise.getId());
						item.setOrgPosition(carOrgPosition);
					});
					listOutRecord.addAll(outRecordList);
				}

			}

			carService.saveOrUpdateBatch(list);
			enterRecordService.updateBatchById(listEnterRecord);
			outRecordService.updateBatchById(listOutRecord);

		} catch (IOException e) {
			e.printStackTrace();
			return R.data("服务器异常！");
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return R.status(true);
	}

	public R readThirdHouseUserExcel(MultipartFile file, HttpServletResponse response) {
		InputStream is = null;
		try {
			String fileName = file.getOriginalFilename();
			if (!fileName.matches(REGEX_EXCEL2003) && !fileName.matches(REGEX_EXCEL2007)) {
				return R.data("文件格式不合法！");
			}
			is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
			//默认第一页
			Sheet sheet = workbook.getSheetAt(0);
			//空白页或空白内容
			if (sheet.getPhysicalNumberOfRows() < 2 || sheet.getLastRowNum() < 1) {
				return R.data("文件内容格式不对！");
			}

			List<ThirdHouseUser> list = new ArrayList<>();

			int count = sheet.getLastRowNum();
			for (int j = 2; j <= count; j++) {
				//判断该行数据是否有误
				Row row = sheet.getRow(j);
				if (null == row) {
					continue;
				}

				ThirdHouseUser thirdHouseUser = new ThirdHouseUser();

				// 姓名
				String name = getCellValue(row.getCell(1));
				thirdHouseUser.setName(name);
				// 性别
				String sex = getCellValue(row.getCell(2));
				thirdHouseUser.setSex(sex);
				// 社区
				String agencyName = getCellValue(row.getCell(3));
				thirdHouseUser.setAgencyName(agencyName);
				// 小区
				String residentialName = getCellValue(row.getCell(4));
				thirdHouseUser.setResidentialName(residentialName);
				// 房屋信息
				String houseInfo = getCellValue(row.getCell(5));
				thirdHouseUser.setHouseInfo(houseInfo);
				// 照片
				String image = getCellValue(row.getCell(6));
				thirdHouseUser.setImage(image);
				// 身份证
				String idcard = getCellValue(row.getCell(7));
				thirdHouseUser.setIdcard(idcard);
				// 手机
				String tel = getCellValue(row.getCell(8));
				thirdHouseUser.setTel(tel);
				// 国籍
				String nationality = getCellValue(row.getCell(9));
				thirdHouseUser.setNationality(nationality);
				// 民族
				String nation = getCellValue(row.getCell(10));
				thirdHouseUser.setNation(nation);
				// 文化程度
				String education = getCellValue(row.getCell(11));
				thirdHouseUser.setEducation(education);
				// 政治面貌
				String political = getCellValue(row.getCell(12));
				thirdHouseUser.setPolitical(political);
				// 职业
				String occupation = getCellValue(row.getCell(13));
				thirdHouseUser.setOccupation(occupation);
				// 婚姻状况
				String maritalStatus = getCellValue(row.getCell(14));
				thirdHouseUser.setMaritalStatus(maritalStatus);
				// 户主关系
				String relationship = getCellValue(row.getCell(15));
				thirdHouseUser.setRelationship(relationship);
				// 户籍地-籍贯
				String nativePlace = getCellValue(row.getCell(16));
				thirdHouseUser.setNativePlace(nativePlace);
				// 现居住地
				String address = getCellValue(row.getCell(17));
				thirdHouseUser.setAddress(address);
				// 工作单位
				String workplace = getCellValue(row.getCell(18));
				thirdHouseUser.setWorkplace(workplace);
				// 是否建档立卡户
				String isFile = getCellValue(row.getCell(19));
				thirdHouseUser.setIsFile(isFile);
				// 五保
				String wubao = getCellValue(row.getCell(20));
				thirdHouseUser.setWubao(wubao);
				// 低保
				String dibao = getCellValue(row.getCell(21));
				thirdHouseUser.setDibao(dibao);
				// 孤儿
				String guer = getCellValue(row.getCell(22));
				thirdHouseUser.setGuer(guer);
				// 残疾
				String canji = getCellValue(row.getCell(23));
				thirdHouseUser.setCanji(canji);
				// 优抚
				String youfu = getCellValue(row.getCell(24));
				thirdHouseUser.setYoufu(youfu);
				// 车牌号-货车
				String carNoTruck = getCellValue(row.getCell(25));
				thirdHouseUser.setCarNoTruck(carNoTruck);
				// 车牌号-小汽车
				String carNo = getCellValue(row.getCell(26));
				thirdHouseUser.setCarNo(carNo);
				// 备注
				String remark = getCellValue(row.getCell(27));
				thirdHouseUser.setRemark(remark);

				list.add(thirdHouseUser);

			}

			boolean b = thirdHouseUserService.saveBatch(list);


		} catch (IOException e) {
			e.printStackTrace();
			return R.data("服务器异常！");
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return R.status(true);
	}
}

