package org.springblade.community.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.entity.Agency;
import org.springblade.community.entity.Residential;
import org.springblade.community.excel.model.ResidentialImportModule;
import org.springblade.community.service.IAgencyService;
import org.springblade.community.service.IResidentialService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
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 IAgencyService agencyService;
	private IResidentialService residentialService;
	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 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为空，隐形挂在常运智慧科技下面，方便常运智慧管理（常运智慧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 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.setName(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;
		StringBuffer importErrorMsg = new StringBuffer();
		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;
				//造成行数据导入失败的错误信息
				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.setName(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(j + " 找不到对应园区：" + agencyName + "\r");
					}
				}else{
					flag = false;
					importErrorMsg.append(j + " 园区名称为空；");
				}

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

//				// 物业名称
//				String estatePidName = getCellValue(row.getCell(3));
//				residential.setEstateName(estatePidName);
//
//				// 物业电话
//				String estatePidPhone = getCellValue(row.getCell(4));
//				residential.setEstatePhone(estatePidPhone);

				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.data(importErrorMsg);
	}

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

}


