package com.sptg.gateway.controller.estate;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SymbolConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.dto.DeviceDto;
import com.sptg.device.api.dto.DevicePathDto;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.entity.DevicePath;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.device.api.feigns.DevicePathFeign;
import com.sptg.estate.api.constant.EstateSecurityToken;
import com.sptg.estate.api.dto.*;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.permissions.api.dto.RegionAuthorizeDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.entity.RegionAuthorize;
import com.sptg.permissions.api.feigns.AccountFeign;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.permissions.api.feigns.RegionAuthorizeFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import com.sptg.third.api.entity.qinlin.QLinCommunityDevices;
import com.sptg.third.api.feigns.grid.GridEstateFeign;
import com.sptg.third.api.feigns.qinlin.QLinAuthFeign;
import com.sptg.third.api.feigns.qinlin.QLinFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

/**
 * title: ResidentialController
 * package: com.sptg.gateway.controller.estate
 * description: 小区 网关控制器
 *
 *             
 *                
 */
@RestController
@RequestMapping("/estate/residential")
@RequiredArgsConstructor
public class ResidentialController {

    private final ResidentialFeign residentialFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final OrgFeign orgFeign;
    private final UnitFeign unitFeign;
    private final RoomFeign roomFeign;
    private final UserFeign userFeign;
    private final DevicePathFeign devicePathFeign;
    private final DeviceFeign deviceFeign;
    private final FaceChargeProjectFeign faceChargeProjectFeign;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final RegionAuthorizeFeign regionAuthorizeFeign;
    private final ConfFeign confFeign;
    private final AgencyFeign agencyFeign;
    private final GridEstateFeign gridEstateFeign;
    private final QLinAuthFeign qLinAuthFeign;
    private final BuildingFeign buildingFeign;
    private final FloorFeign floorFeign;
    private final QLinFeign qLinFeign;
    private final AccountFeign accountFeign;
    private final AccessRecordsFeign accessRecordsFeign;
    private final ApplyUserFeign applyUserFeign;
    private final ServerUserFeign serverUserFeign;
    private final NoticeFeign noticeFeign;


    /**
     * 功能描述:小区页面初始化
     * @return ModelAndView
     *             
     *                      
     */
    @GetMapping("/index")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView index(){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        ModelAndView modelAndView = new ModelAndView("estate/residential-manage");
        modelAndView.addObject("userOrg", userOrg);
        return  modelAndView;
    }

    /**
     * 功能描述:小区页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/manage/{residentialId}/{index}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView manage(@PathVariable(value = "residentialId") Long residentialId,@PathVariable(value = "index") Integer index){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        ModelAndView modelAndView = null;
        switch (index){
            case 1:
                modelAndView = new ModelAndView("estate/residential-unit");
                break;
            case 2:
                modelAndView = new ModelAndView("estate/residential-room");
                break;
            case 3:
                modelAndView = new ModelAndView("estate/residential-user");
                break;
            case 4:
                modelAndView = new ModelAndView("estate/residential-apply-user");
                break;
            case 5:
                modelAndView = new ModelAndView("estate/residential-access");
                modelAndView.addObject("fastDfsServer",this.confFeign.getFileServerHost());
                break;
            case 6:
                modelAndView = new ModelAndView("estate/residential-access-card");
                break;
            case 7:
                modelAndView = new ModelAndView("estate/residential-access-records");
                modelAndView.addObject("fastDfsServer",this.confFeign.getFileServerHost());
                break;
            case 8:
                modelAndView = new ModelAndView("estate/residential-server-user");
                modelAndView.addObject("fastDfsServer", this.confFeign.getFileServerHost());
                break;
            case 9:
                modelAndView = new ModelAndView("estate/residential-device");
                break;
            case 10:
                modelAndView = new ModelAndView("estate/residential-device-path");
                break;
            /*case 8:
                modelAndView = new ModelAndView("estate/residential-user-order");
                modelAndView.addObject("fastDfsServer",this.confFeign.getFileServerHost());
                break;
            case 9:
                modelAndView = new ModelAndView("estate/residential-apply-pay-refund");
                break;*/
            default:
                return new ModelAndView("common/404");
        }
        modelAndView.addObject("userOrg", userOrg);
        modelAndView.addObject("residentialId",residentialId);
        return  modelAndView;
    }

    /**
     * 功能描述:小区页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/trash")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_TRASH,format = DataFormatEnum.VIEW)
    public ModelAndView trash(){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        ModelAndView modelAndView = new ModelAndView("estate/residential-manage-trash");
        modelAndView.addObject("userOrg", userOrg);
        return  modelAndView;
    }

    /**
     * 功能描述: 管理页面初始化
     * @param id 必填
     * @return ModelAndView
     *
     *
     */
    @GetMapping(value = "/detail/{id}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_UPDATE,format = DataFormatEnum.VIEW)
    public ModelAndView detail(@PathVariable(value = "id")Long id){
        Residential residential =  this.residentialFeign.findResidentialById(id);
        if (null == residential){
            //  没有找到要的小区
            return new ModelAndView("common/404");
        }
        ModelAndView  modelAndView = new ModelAndView("estate/residential");
        modelAndView.addObject("residential",residential);
        return modelAndView;
    }

    /**
     * 功能描述:小区列表查询
     * @param residentialDto 小区业务对象（含查询条件）
     * @param page 分页条件
     * @return ResultBean<Page<Residential>>
     *             
     *                      
     */
    @GetMapping(value = "/showResidentialList")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<Residential>> showResidentialList(ResidentialDto residentialDto, Page<Residential> page) {
        //根据树形选择加载数据；如果没有选中ID，则根据当前账号查询
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
//        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
//        if(null == residentialDto.getSelectTreeId()) {
//            if (userOrg.getOrgType() == OperationConstant.THREE){//物业账号
//                residentialDto.setEstatePosition(onLineUser.getOrgPosition());
//            }else{//机构账号
//                residentialDto.setOrgPosition(onLineUser.getOrgPosition());
//            }
////            residentialDto.setEstatePosition(onLineUser.getOrgPosition());
//        }else{
//            //1 机构 2 小区
//            Organization organization = this.orgFeign.getOrgById(residentialDto.getSelectTreeId());
//            if (organization.getOrgType() == OperationConstant.THREE){//选中的是物业
//                residentialDto.setEstatePosition(organization.getPosition());
//            }else{//选中的是机构
//                residentialDto.setOrgPosition(organization.getPosition());
//            }
////            residentialDto.setEstatePosition(organization.getPosition());
//        }
        residentialDto.setOrgPosition(onLineUser.getOrgPosition());
        residentialDto.setPage(page);
        return this.residentialFeign.showResidentialList(residentialDto);
    }


    @GetMapping(value = "/getSourceByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Building> getSourceByPid(BuildingDto dto){
        //  参数校验
        if (null == dto || null == dto.getResidentialId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential residential = this.residentialFeign.findResidentialById(dto.getResidentialId());
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());

        List<Building> list = buildingFeign.getListByCondition(dto);

        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }
        return new ResultBean<>(ResultEnum.SUCCESS,list);
    }

    @GetMapping(value = "/getUnitsByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Unit> getFloorsByPid(UnitDto dto){
        //  参数校验
        if (null == dto || null == dto.getBuildingId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());

        List<Unit> unitList = unitFeign.getListByBuildingId(dto.getBuildingId());


        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }
        return new ResultBean<>(ResultEnum.SUCCESS, unitList);
    }

    @GetMapping(value = "/getFloorsByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Floor> getFloorsByPid(FloorDto dto){
        //  参数校验
        if (null == dto || null == dto.getUnitId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());

        List<Floor> list = floorFeign.getFloorByUnitId(dto.getUnitId());

        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }
        return new ResultBean<>(ResultEnum.SUCCESS, list);
    }

    @GetMapping(value = "/getRoomsByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<List<Room>> getRoomsByPid(RoomDto dto){
        //  参数校验
        if (null == dto || null == dto.getFloorId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());

        List<Room> list = roomFeign.getListByCondition(dto);


        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }
        return new ResultBean<List<Room>>(ResultEnum.SUCCESS, list);
    }

    @GetMapping(value = "/getUsersByPid")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<List<User>> getUsersByPid(UserDto dto){
        //  参数校验
        if (null == dto || null == dto.getRoomId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取当前用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());

//        User list = userFeign.findUserByCondition(dto);
        List<User> list = userFeign.getListByCondition(dto);

        //  判断是否需要树形排序
//        if (dto.getIsTreeSort() == OperationConstant.ONE){
//            list = TreeUtil.tree(list);
//        }

        return new ResultBean<List<User>>(ResultEnum.SUCCESS, list);
    }

    /**
     * 功能描述:小区列表查询
     * @param residentialDto 小区业务对象（含查询条件）
     * @return ResultBean<Page<Residential>>
     *
     *
     */
    @GetMapping(value = "/findListByPosition")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Residential> findListByPosition(ResidentialDto residentialDto) {
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        if(null == residentialDto.getSelectTreeId()) {
            if (userOrg.getOrgType() == OperationConstant.THREE){
                residentialDto.setEstatePosition(onLineUser.getOrgPosition());
            }else{
                residentialDto.setOrgPosition(onLineUser.getOrgPosition());
            }
        }else{
            Organization organization = this.orgFeign.getOrgById(residentialDto.getSelectTreeId());
            if (organization.getOrgType() == OperationConstant.THREE){
                residentialDto.setEstatePosition(organization.getPosition());
            }else{
                residentialDto.setOrgPosition(organization.getPosition());
            }
        }
        return this.residentialFeign.findListByPosition(residentialDto);
    }

    /**
     * 功能描述:根据条件查询有区域权限的小区列表(不用加token)
     * @param dto 区域权限对象
     * @param pageBean 分页条件
     * @return List<Residential>
     *                
     *                      
     */
    @GetMapping(value = "/pagingQueryAuthorizeOrg")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<List<Residential>> pagingQueryAuthorizeOrg(RegionAuthorizeDto dto, PageBean<RegionAuthorize, RegionAuthorizeDto> pageBean){
        List<Residential> xqList= Collections.emptyList();
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setUserOrgPosition(onLineUser.getOrgPosition());
        pageBean.setDto(dto);
        //  获取授权小区的列表
        Page<RegionAuthorize> orgPage = this.regionAuthorizeFeign.pagingQuery(pageBean);
        if (orgPage.getTotal() > OperationConstant.ZERO){
            //  获取详细信息
            List<Long> idList = orgPage.getRecords().stream().map(RegionAuthorize::getXqId).collect(Collectors.toList());
            xqList = this.residentialFeign.getByOrgIdList(idList);
        }
        return new ResultBean<List<Residential>>(ResultEnum.SUCCESS,xqList);
    }

    /**
     * 功能描述: 新增页面初始化
     * @return ModelAndView
     *             
     *                      
     */
    @GetMapping(value = "/add")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_ADD,format = DataFormatEnum.VIEW)
    public ModelAndView add(String selectTreeId,Integer selectTreeType){
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        ModelAndView modelAndView = new ModelAndView("estate/residential-add");
        modelAndView.addObject("userOrg",userOrg);
        modelAndView.addObject("selectTreeId",selectTreeId);
        modelAndView.addObject("selectTreeType",selectTreeType);

        return modelAndView;
    }

    @GetMapping(value = "/findResidentialById/{id}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Residential> findResidentialById(@PathVariable(value = "id") Long id){
        Residential residential = this.residentialFeign.findResidentialById(id);
        Assert.notNull(residential,"小区不存在");
        return new ResultBean<>(ResultEnum.SUCCESS,residential);
    }

    @GetMapping(value = "/registerQinLinResidential/{id}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<String> registerQinlinResidential(@PathVariable(value = "id") Long id){
        Residential residential = this.residentialFeign.findResidentialById(id);
        Long residentialId = residential.getId();
        String communityName = residential.getName();
        QLinCommunityDevices qLinCommunityDevices = new QLinCommunityDevices();
        qLinCommunityDevices.setResidentialId(residentialId);
        qLinCommunityDevices.setCommunityName(communityName);
        ResultBean<String> resultBean = this.qLinFeign.addCommunity(qLinCommunityDevices);
        return resultBean;
    }

    @PostMapping(value = "/registerQinLinDevices")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<String> registerQinLinDevice(QLinCommunityDevices qLinCommunityDevices){

        List<String> macList = new ArrayList<>();

        String[] split = qLinCommunityDevices.getMacs().split(",");
        for (int i = 0; i < split.length; i++) {
            macList.add(split[i]);
        }
        qLinCommunityDevices.setMac(macList);
        qLinCommunityDevices.setMacs(null);

        ResultBean<String> resultBean = this.qLinFeign.addDevices(qLinCommunityDevices);
        return resultBean;
    }

    /**
     * 注册该小区的设备
     * @param residentialId
     * @return
     */
    @GetMapping(value = "/registerQinLinDevices/{residentialId}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Map> registerQinLinDevice(@PathVariable(value = "residentialId") Long residentialId){
        Residential residential = this.residentialFeign.findResidentialById(residentialId);

        // 先注册小区
        if (residential.getQinLinResidentialId() == null) {
            ResultBean<String> resultBean = this.registerQinlinResidential(residentialId);
            if (resultBean.getCode().equals("200")){
                residential = this.residentialFeign.findResidentialById(residentialId);
            }
        }

        Map<String, Object> map = new HashMap<>();
        String successMacs = "";
        String exitMacs = "";
        String errorMacs = "";
        // 确保qinLinResidentialId有值，即已经注册小区
        if (residential.getQinLinResidentialId() != null) {
            List<Device> deviceList = this.deviceFeign.getListByXqId(residentialId);
            for (int i = 0; i < deviceList.size(); i++) {
                Device item = deviceList.get(i);
                if (item.getHadRegister() != null && item.getHadRegister().equals(1)){
                    continue;
                }
                String serialNumber = item.getSerialNumber();
                List<String> macList = new ArrayList<>();
                macList.add(serialNumber);
                QLinCommunityDevices qLinCommunityDevices = new QLinCommunityDevices();
                qLinCommunityDevices.setCommunityId(residential.getQinLinResidentialId());
                qLinCommunityDevices.setMac(macList);
                ResultBean<String> resultBean = this.qLinFeign.addDevices(qLinCommunityDevices);
                if (resultBean.getCode().equals("200")){
                    // 设备注册成功
                    successMacs += serialNumber + ",";
                }else if (resultBean.getCode().equals("402")){
                    // 设备已注册
                    exitMacs += serialNumber + ",";
                }else{
                    // 异常
                    errorMacs += serialNumber + ",";
                }
            }
            map.put("successMacs", successMacs.length() == 0 ? "" : successMacs.substring(0, successMacs.length() - 1));
            map.put("exitMacs", exitMacs.length() == 0 ? "" : exitMacs.substring(0, exitMacs.length() - 1));
            map.put("errorMacs", errorMacs.length() == 0 ? "" : errorMacs.substring(0, errorMacs.length() - 1));
        }

        return new ResultBean(ResultEnum.SUCCESS, map);
    }

    /**
     * 功能描述:批量注册小区设备
     * @param ids 选中的id集合
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/batchRegisterDevice")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_REGISTER_BATCHDEVICE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> batchRegisterDevice(@RequestBody List<String> ids){
        if (null == ids || ids.size() <=0){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }

        Map<String, Object> map = new HashMap<>();
        String successMacs = "";
        String exitMacs = "";
        String errorMacs = "";

        for (int j = 0; j < ids.size(); j++) {
            Long residentialId = Long.valueOf(ids.get(j));
            Residential residential = this.residentialFeign.findResidentialById(residentialId);
            // 先注册小区
            if (residential.getQinLinResidentialId() == null) {
                ResultBean<String> resultBean = this.registerQinlinResidential(residentialId);
                if (resultBean.getCode().equals("200")){
                    residential = this.residentialFeign.findResidentialById(residentialId);
                }
            }

            // 确保qinLinResidentialId有值，即已经注册小区
            if (residential.getQinLinResidentialId() != null) {
                List<Device> deviceList = this.deviceFeign.getListByXqId(residentialId);
                for (int i = 0; i < deviceList.size(); i++) {
                    Device item = deviceList.get(i);
                    // 若设备已注册，则跳过
                    if (item.getHadRegister() != null && item.getHadRegister().equals(1)){
                        continue;
                    }
                    String serialNumber = item.getSerialNumber();
                    List<String> macList = new ArrayList<>();
                    macList.add(serialNumber);
                    QLinCommunityDevices qLinCommunityDevices = new QLinCommunityDevices();
                    qLinCommunityDevices.setCommunityId(residential.getQinLinResidentialId());
                    qLinCommunityDevices.setMac(macList);
                    ResultBean<String> resultBean = this.qLinFeign.addDevices(qLinCommunityDevices);
                    if (resultBean.getCode().equals("200")){
                        // 设备注册成功
                        successMacs += "【" + residential.getName() + "】-" + serialNumber + ",";
                        item.setHadRegister(1);
                        boolean b = this.deviceFeign.updateEntity(item);
                    }else if (resultBean.getCode().equals("402")){
                        // 设备已注册
                        exitMacs += "【" + residential.getName() + "】-" + serialNumber + ",";
                        item.setHadRegister(1);
                        boolean b = this.deviceFeign.updateEntity(item);
                    }else{
                        // 异常
                        errorMacs += "【" + residential.getName() + "】-" + serialNumber + ",";
                    }
                }
                map.put("successMacs", successMacs.length() == 0 ? "" : successMacs.substring(0, successMacs.length() - 1));
                map.put("exitMacs", exitMacs.length() == 0 ? "" : exitMacs.substring(0, exitMacs.length() - 1));
                map.put("errorMacs", errorMacs.length() == 0 ? "" : errorMacs.substring(0, errorMacs.length() - 1));
            }
        }

        return new ResultBean(ResultEnum.SUCCESS, map);
    }

    /**
     * 功能描述:新增小区
     * @param residentialDto 小区业务对象
     * @return ResultBean<Boolean>
     *             
     *                      
     */
    @PostMapping(value = "/addResidential")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_ADD,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addResidential(ResidentialDto residentialDto){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        residentialDto.setCreateAccountId(onLineUser.getId());
        residentialDto.setOnLineUser(onLineUser);
//        residentialDto.setCreatorType(userOrg.getOrgType());
        //获取所属社区信息
        Agency agency = this.agencyFeign.findAgencyById(residentialDto.getAgencyId());
        if(agency == null){
            return new ResultBean<>(ResultEnum.ERROR);
        }
        residentialDto.setAgencyName(agency.getAgencyName());
        //获取所属社区的所属机构
        Organization orgOfAgency = this.orgFeign.getOrgById(agency.getOrgPid());
        if(orgOfAgency == null){
            return new ResultBean<>(ResultEnum.ERROR);
        }
        residentialDto.setOrgPosition(orgOfAgency.getPosition());
        residentialDto.setRegionProvince(agency.getRegionProvince());
        residentialDto.setRegionCity(agency.getRegionCity());
        residentialDto.setRegionArea(agency.getRegionArea());
        residentialDto.setRegionStreet(agency.getRegionStreet());
        residentialDto.setRootOrgId(orgOfAgency.getId());
        residentialDto.setParentNameOfResidentialOrg(orgOfAgency.getName());
        residentialDto.setParentIdOfResidentialOrg(orgOfAgency.getId());
        ResultBean<Residential> resultBean=this.residentialFeign.addResidential(residentialDto);
        if(null != resultBean.getData() && resultBean.getData().getId()!= null){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            //登陆用户
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser,residentialDto);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/

            /*---------------------------------------------------推送数据到网格--------------------------------------------------------*/

            ResultBean<String> stringResultBean = this.gridEstateFeign.gridResidentialPush(resultBean.getData());
            if(stringResultBean != null&&stringResultBean.getData()!=null&&stringResultBean.getData().equals("操作成功")){
                SysOperationLog sysOperationLog1=new SysOperationLog("推送小区数据到网格成功", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),resultBean.getData(),onLineUser,resultBean.getData());
                sysOperationLogFeign.info(sysOperationLog1);
            }else{
                SysOperationLog sysOperationLog1=new SysOperationLog("推送小区数据到网格失败", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),resultBean.getData(),onLineUser,resultBean.getData());
                sysOperationLogFeign.info(sysOperationLog1);
            }

            /*------------------------------------------------------------------------------------------------------------------*/
            return new ResultBean<>(ResultEnum.SUCCESS);
        }
        return new ResultBean<>(ResultEnum.ERROR);
    }

    /**
     * 功能描述: 编辑页面初始化
     * @param id 必填
     * @return ModelAndView
     *             
     *                      
     */
    @GetMapping(value = "/edit/{id}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_UPDATE,format = DataFormatEnum.VIEW)
    public ModelAndView edit(@PathVariable(value = "id")Long id){
        Residential residential =  this.residentialFeign.findResidentialById(id);
        if (null == residential){
            //  没有找到要修改的小区
            return new ModelAndView("common/404");
        }
        ModelAndView  modelAndView = new ModelAndView("estate/residential-edit");
        modelAndView.addObject("residential",residential);
        return modelAndView;
    }

    /**
     * 小区分配-针对物业创建的小区，分配合作公司机构，作关联
     * @return
     */
    @GetMapping(value = "/assign/{id}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView assign(@PathVariable(value = "id")Long id){
        Residential residential =  this.residentialFeign.findResidentialById(id);
        if (null == residential){
            //  没有找到要分配的小区
            return new ModelAndView("common/404");
        }
        ModelAndView  modelAndView = new ModelAndView("estate/residential-assign");
        modelAndView.addObject("residential",residential);
        return modelAndView;
    }

    /**
     * 小区分配-针对物业创建的小区，分配合作公司机构，作关联
     * @param residentialDto
     * @return
     */
    @PostMapping(value = "/assignResidential")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> assignResidential(ResidentialDto residentialDto){
        if ( null == residentialDto || null == residentialDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential residential = this.residentialFeign.findResidentialById(residentialDto.getId());
        Organization assignOrg = this.orgFeign.getOrgById(residentialDto.getOrgPid());
        residential.setOrgPid(residentialDto.getOrgPid());
        residential.setIsAssign(OperationConstant.ONE);
        residential.setOrgPosition(assignOrg.getPosition() + residential.getId() + SymbolConstant.BACK_SLASH);
        residential.setOrgPidName(residentialDto.getOrgPidName());
        ResultBean<Boolean> resultBean = this.residentialFeign.updateResidentialEntity(residential);
        //同步机构表的小区信息
        Organization org = this.orgFeign.getOrgById(residentialDto.getId());
        org.setPid(residential.getOrgPid());
        org.setPosition(residential.getOrgPosition());
        boolean result = this.orgFeign.updateEntity(org);
        if(null != resultBean.getData() && resultBean.getData() && result){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            //登陆用户
            Residential newObj = this.residentialFeign.findResidentialById(residentialDto.getId());
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser,residential,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:编辑小区
     * @param residentialDto 小区业务对象
     * @return ResultBean<Boolean>
     *             
     *                      
     */
    @PostMapping(value = "/updateResidential")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateResidential(ResidentialDto residentialDto){
        if ( null == residentialDto || null == residentialDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential oldObj = this.residentialFeign.findResidentialById(residentialDto.getId());
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        residentialDto.setOnLineUser(onLineUser);
//        residentialDto.setCreateAccountId(onLineUser.getId());

//        Long agencyId = residentialDto.getAgencyId();
//        Agency agency = this.agencyFeign.findAgencyById(agencyId);
//        residentialDto.setAgencyName(agency.getAgencyName());
//        residentialDto.setResidentialNumber("A"+residentialDto.getId());
//        residentialDto.setOrgPosition(agency.getOrgPosition()+residentialDto.getId()+"/");
//        ResultBean<Boolean> resultBean=this.residentialFeign.updateResidential(residentialDto);
        ResultBean<Boolean> resultBean = this.updateResidentialAndRelationData(residentialDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Residential newObj = this.residentialFeign.findResidentialById(residentialDto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:编辑小区
     * @param residentialDto 小区业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/updateResidentialName")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateResidentialName(ResidentialDto residentialDto){
        if ( null == residentialDto || null == residentialDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential residential = this.residentialFeign.findResidentialById(residentialDto.getId());

        residential.setName(residentialDto.getName());
        boolean updateResult = this.residentialFeign.updateEntity(residential);

        if(updateResult){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            Residential newObj = this.residentialFeign.findResidentialById(residentialDto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(), residentialDto, onLineUser, residential, newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return new ResultBean<>(ResultEnum.SUCCESS);
    }

    /**
     * 更新小区以及相关的单元、房间、住户等信息（暂时只支持更改物业，不支持更改机构）
     * @param residentialDto
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> updateResidentialAndRelationData(ResidentialDto residentialDto){
        Residential oldResidential = this.residentialFeign.findResidentialById(residentialDto.getId());
        Long oldAgencyId = oldResidential.getAgencyId();
        Long newAgencyId = residentialDto.getAgencyId();

        boolean flag = true;

        if (newAgencyId != null && !oldAgencyId.equals(newAgencyId)) {
            Agency oldAgency = this.agencyFeign.findAgencyById(oldAgencyId);
            Agency newAgency = this.agencyFeign.findAgencyById(newAgencyId);

            Organization oldOrgAgen = this.orgFeign.getOrgById(oldAgency.getOrgPid());
            Organization newOrgAgen = this.orgFeign.getOrgById(newAgency.getOrgPid());

            Organization orgResidential = this.orgFeign.getOrgById(oldResidential.getOrgPid());
            String oldPosition = oldOrgAgen.getPosition() + orgResidential.getId() + SymbolConstant.BACK_SLASH;
            String newPosition = newOrgAgen.getPosition() + orgResidential.getId() + SymbolConstant.BACK_SLASH;

            //1.1、更改小区机构
            orgResidential.setPid(newOrgAgen.getId());
            orgResidential.setParentName(newOrgAgen.getName());
            orgResidential.setPosition(newPosition);

            //1.2 小区账号（挂靠的机构）
            Account accountResidential = this.accountFeign.getByOrgId(orgResidential.getId().toString());
            accountResidential.setOrgPosition(newPosition);

            /*//2、更改小区信息
            residentialDto.setOrgPosition(newPosition);
            residentialDto.setAgencyId(newAgency.getId());
            residentialDto.setAgencyName(newAgency.getAgencyName());*/

            //3、楼栋
            BuildingDto buildingDto = new BuildingDto();
            buildingDto.setOrgPosition(oldPosition);
            buildingDto.setResidentialId(residentialDto.getId());
            List<Building> buildingList = this.buildingFeign.getListByCondition(buildingDto);
            buildingList.forEach(building -> {
                building.setOrgPosition(building.getOrgPosition().replace(oldPosition, newPosition));
            });

            //4、单元
            UnitDto unitDto = new UnitDto();
            unitDto.setOrgPosition(oldPosition);
            unitDto.setResidentialId(residentialDto.getId());
            List<Unit> unitList = this.unitFeign.getListByCondition(unitDto);
            unitList.forEach(unit -> {
                unit.setOrgPosition(unit.getOrgPosition().replace(oldPosition, newPosition));
            });

            //5、楼层
            FloorDto floorDto = new FloorDto();
            floorDto.setResidentialId(residentialDto.getId());
            floorDto.setOrgPosition(oldPosition);
            List<Floor> floorList = this.floorFeign.getListByCondition(floorDto);
            floorList.forEach(floor -> {
                floor.setOrgPosition(floor.getOrgPosition().replace(oldPosition, newPosition));
            });

            //6、房屋
            RoomDto roomDto = new RoomDto();
            roomDto.setResidentialId(residentialDto.getId());
            roomDto.setOrgPosition(oldPosition);
            List<Room> roomList = this.roomFeign.getListByCondition(roomDto);
            roomList.forEach(room -> {
                room.setOrgPosition(room.getOrgPosition().replace(oldPosition, newPosition));
            });

            //7、住户
            UserDto userDto = new UserDto();
            userDto.setResidentialId(residentialDto.getId());
            userDto.setOrgPosition(oldPosition);
            List<User> userList = this.userFeign.getListByCondition(userDto);
            userList.forEach(user -> {
                user.setOrgPosition(user.getOrgPosition().replace(oldPosition, newPosition));
            });

            //8、设备
            List<Device> deviceList = this.deviceFeign.getListByXqId(residentialDto.getId());
            deviceList.forEach(device -> {
                device.setOrgPosition(device.getOrgPosition().replace(oldPosition, newPosition));
            });

            //9、开门记录
            AccessRecordsDto accessRecordsDto = new AccessRecordsDto();
            accessRecordsDto.setResidentialId(residentialDto.getId());
            accessRecordsDto.setOrgPosition(oldPosition);
            List<AccessRecords> accessRecordList = this.accessRecordsFeign.getListByCondition(accessRecordsDto);
            accessRecordList.forEach(record -> {
                record.setOrgPosition(record.getOrgPosition().replace(oldPosition, newPosition));
            });

            //10、认证记录
            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setResidentialId(residentialDto.getId());
            applyUserDto.setOrgPosition(oldPosition);
            List<ApplyUser> applyUserList = this.applyUserFeign.getApplyUserByCondition(applyUserDto);
            applyUserList.forEach(applyUser -> {
                applyUser.setOrgPosition(applyUser.getOrgPosition().replace(oldPosition, newPosition));
            });

            //11、服务人员
            ServerUserDto serverUserDto = new ServerUserDto();
            serverUserDto.setResidentialId(residentialDto.getId());
            serverUserDto.setOrgPosition(oldPosition);
            List<ServerUser> serverUserList = this.serverUserFeign.getServerUserByCondition(serverUserDto);
            serverUserList.forEach(serverUser -> {
                serverUser.setOrgPosition(serverUser.getOrgPosition().replace(oldPosition, newPosition));
            });

            //12、公告
            NoticeDto noticeDto = new NoticeDto();
            noticeDto.setResidentialId(residentialDto.getId());
            noticeDto.setOrgPosition(oldPosition);
            ResultBean<List<Notice>> noticeResultBean = this.noticeFeign.getList(noticeDto);
            List<Notice> noticeList = noticeResultBean.getData();
            noticeList.forEach(notice -> {
                notice.setOrgPosition(notice.getOrgPosition().replace(oldPosition, newPosition));
            });


            //更新开门记录
            boolean b1 = accessRecordList.size() == 0 ? true : this.accessRecordsFeign.updateBatchList(accessRecordList);
            //更新设备信息
            boolean b2 = deviceList.size() == 0 ? true : this.deviceFeign.updateDeviceList(deviceList);
            //更新住户信息
            boolean b3 = userList.size() == 0 ? true : this.userFeign.updateUserList(userList);
            //更新房屋信息
            boolean b4 = roomList.size() == 0 ? true : this.roomFeign.updateRoomList(roomList);
            //更新楼层信息
            boolean b5 = floorList.size() == 0 ? true : this.floorFeign.updateFloorList(floorList);
            //更新单元信息
            boolean b6 = unitList.size() == 0 ? true : this.unitFeign.updateUnitList(unitList);
            //更新楼栋信息
            boolean b7 = buildingList.size() == 0 ? true : this.buildingFeign.updateBuildingList(buildingList);
            //更新小区账号
            ResultBean<Boolean> resultBean = this.accountFeign.updateById(accountResidential);
            boolean b8 = resultBean.getData();
            //更新小区机构所属社区机构
            boolean b9 = accessRecordList.size() == 0 ? true : this.orgFeign.updateEntity(orgResidential);
            //更新认证记录
            boolean b10 = applyUserList.size() == 0 ? true : this.applyUserFeign.updateApplyUserList(applyUserList);
            //服务人员
            boolean b11 = serverUserList.size() == 0 ? true : this.serverUserFeign.updateServerUserList(serverUserList);
            //公告
            boolean b12 = noticeList.size() == 0 ? true : this.noticeFeign.updateNoticeList(noticeList);

            flag = b1 & b2 & b3 & b4 & b5 & b6 & b7 & b8 & b9 & b10 & b11 & b12;
            if (flag){
                //2、更改小区信息
                residentialDto.setOrgPosition(newPosition);
                residentialDto.setAgencyId(newAgency.getId());
                residentialDto.setAgencyName(newAgency.getAgencyName());
            }

        }

        //更新小区
        if (!flag){
            return new ResultBean(ResultEnum.ERROR);
        }
        return this.residentialFeign.updateResidential(residentialDto);
    }

    /**
     * 功能描述:删除小区
     * @param residentialDto 小区业务对象
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/deleteResidential")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteResidential(ResidentialDto residentialDto){
        if ( null == residentialDto || null == residentialDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential oldObj = this.residentialFeign.findResidentialById(residentialDto.getId());
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        residentialDto.setCreateAccountId(onLineUser.getId());
        residentialDto.setOrgPosition(onLineUser.getOrgPosition());
        residentialDto.setStatus(OperationConstant.MINUS_ONE);
        ResultBean<Boolean> resultBean=this.residentialFeign.deleteResidential(residentialDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------   -----------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:批量删除小区
     * @param ids 选中的id集合
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/deleteResidentialList")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteResidentialList(@RequestBody List<String> ids){
        if (null == ids || ids.size() <=0){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        ResidentialDto residentialDto = new ResidentialDto();
        residentialDto.setCreateAccountId(onLineUser.getId());
        residentialDto.setOrgPosition(onLineUser.getOrgPosition());
        residentialDto.setIds(ids);
        ResultBean<Boolean> resultBean = this.residentialFeign.deleteResidentialList(residentialDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:导入小区
     * @param flag 1 小区
     * @return ModelAndView
     */
    @RequestMapping(value = "/indexImportExcel/{flag}")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_IMPORT,format = DataFormatEnum.VIEW)
    public ModelAndView indexImportExcel(@PathVariable(value = "flag")String flag) {
        if (null == flag){
            return new ModelAndView("common/404");
        }
        ModelAndView modelAndView = new ModelAndView("common/import-excel");
        modelAndView.addObject("flag",flag);
        return modelAndView;
    }
    
    /**
     * 功能描述:导出小区
     * @param response
     */
    @RequestMapping(value = "/exportResidential")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_EXPORT)
    public void exportResidential(HttpServletResponse response) {
        try {
            response.sendRedirect("/common/excel/exportExcel/1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 功能描述: 根据名称模糊查询
     * @param dto
     * @return ResultBean<Organization>
     */
    @GetMapping(value = "/getListByLikeName")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Residential> getListByLikeName(ResidentialDto dto){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        if(null == dto.getSelectTreeId()) {
//            if (userOrg.getOrgType() == OperationConstant.THREE){
//                dto.setEstatePosition(onLineUser.getOrgPosition());
//            }else{
                dto.setOrgPosition(onLineUser.getOrgPosition());
//            }
        }else{
            Organization organization = this.orgFeign.getOrgById(dto.getSelectTreeId());
            if (organization.getOrgType() == OperationConstant.THREE){
                dto.setEstatePosition(organization.getPosition());
            }else{
                dto.setOrgPosition(organization.getPosition());
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS,this.residentialFeign.getListByLikeName(dto));
    }

    /**
     * 功能描述:放入垃圾箱
     * @param residentialDto 小区业务对象
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/trashOrRecover")
    @Security(token = EstateSecurityToken.ESTATE_RESIDENTIAL_TRASHORRECOVER,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> trashOrRecover(ResidentialDto residentialDto){
        if ( null == residentialDto || null == residentialDto.getId() || residentialDto.getOrder() == null){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Residential oldObj = this.residentialFeign.findResidentialById(residentialDto.getId());
        Residential residential = this.residentialFeign.findResidentialById(residentialDto.getId());
        if (residential == null){
            return new ResultBean<>(ResultEnum.ERROR);
        }
        BeanUtils.copyProperties(residential,residentialDto);
        residentialDto.setStatus(OperationConstant.MINUS_TWO);
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        switch (residentialDto.getOrder()){
            case 0:
                residentialDto.setStatus(OperationConstant.ZERO);
                break;
            case -2:
                residentialDto.setStatus(OperationConstant.MINUS_TWO);
                break;
            default:
                return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //放入垃圾桶
        ResultBean<Boolean> resultBean = null;
        //住户
        if (residential.getUserNumber() > 0){
            UserDto userDto = new UserDto();
            userDto.setResidentialId(residential.getId());
            userDto.setOrgPosition(residential.getOrgPosition());
            ResultBean<User> userResultBean = this.userFeign.findListByPosition(userDto);
            List<User> userList = userResultBean.getList();
            if (userList.size() > 0){
                for (User user : userList){
                    if (!user.getStatus().equals(residentialDto.getStatus())){
                        UserDto deleteUser = new UserDto();
                        BeanUtils.copyProperties(user,deleteUser);
                        deleteUser.setStatus(residentialDto.getStatus());
                        resultBean = this.userFeign.trashOrRecover(deleteUser);
                        if (!resultBean.getData()){
                            return resultBean;
                        }
                    }
                }
            }
        }
        //房间
        if (residential.getRoomNumber() > 0){
            RoomDto roomDto = new RoomDto();
            roomDto.setResidentialId(residential.getId());
            roomDto.setOrgPosition(residential.getOrgPosition());
            ResultBean<Room> roomResultBean = this.roomFeign.findListByPosition(roomDto);
            List<Room> roomList = roomResultBean.getList();
            if (roomList.size() > 0){
                for(Room room : roomList){
                    if (!room.getStatus().equals(residentialDto.getStatus())){
                        RoomDto deleteRoom = new RoomDto();
                        BeanUtils.copyProperties(room,deleteRoom);
                        deleteRoom.setStatus(residentialDto.getStatus());
                        resultBean = this.roomFeign.trashOrRecover(deleteRoom);
                        if (!resultBean.getData()){
                            return resultBean;
                        }
                    }
                }
            }
        }
        //单元
        if (residential.getUnitNumber() > 0){
            UnitDto unitDto = new UnitDto();
            unitDto.setResidentialId(residential.getId());
            ResultBean<Unit> unitResultBean = this.unitFeign.findListByPosition(unitDto);
            List<Unit> unitList = unitResultBean.getList();
            if (unitList.size() > 0){
                for (Unit unit : unitList){
                    if (!unit.getStatus().equals(residentialDto.getStatus())){
                        UnitDto deleteUnit = new UnitDto();
                        BeanUtils.copyProperties(unit,deleteUnit);
                        deleteUnit.setStatus(residentialDto.getStatus());
                        resultBean = this.unitFeign.trashOrRecover(deleteUnit);
                        if (!resultBean.getData()){
                            return resultBean;
                        }
                    }
                }
            }
        }
        //设备位置
        DevicePathDto devicePathDto = new DevicePathDto();
        devicePathDto.setXqId(residential.getId());
        List<DevicePath> devicePathList = this.devicePathFeign.getList(devicePathDto);
        if (devicePathList.size() > 0){
            for (DevicePath devicePath : devicePathList){
                devicePath.setStatus(residentialDto.getStatus());
            }
            if (!this.devicePathFeign.updateBatchById(devicePathList)){
                return new ResultBean<>(ResultEnum.ERROR,false);
            };
        }
        //设备
        List<Device> deviceList = this.deviceFeign.getListByXqId(residential.getId());
        if (deviceList.size() > 0){
            for(Device device : deviceList){
                DeviceDto deleteDevice = new DeviceDto();
                BeanUtils.copyProperties(device,deleteDevice);
                deleteDevice.setStatus(residentialDto.getStatus());
                resultBean = this.deviceFeign.editEntity(deleteDevice);
                if (!resultBean.getData()){
                    return resultBean;
                }
            }
        }
        //人脸套餐
        List<FaceChargeProject> faceChargeProjectList = this.faceChargeProjectFeign.getListByResidentialId(residential.getId());
        if (faceChargeProjectList.size() > 0){
            for (FaceChargeProject faceChargeProject : faceChargeProjectList){
                faceChargeProject.setStatus(residentialDto.getStatus());
            }
            if (!this.faceChargeProjectFeign.updateBathFaceChargeProject(faceChargeProjectList)){
                return new ResultBean<>(ResultEnum.ERROR,false);
            };
        }
        //小区
        resultBean = this.residentialFeign.trashOrRecover(residentialDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_RESIDENTIAL_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),residentialDto,onLineUser,oldObj,residential);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 同步亲邻楼栋数据
     * @param id
     * @return
     */
    @PostMapping(value = "/syncBuilding/{id}")
    @Security(token = "estate:residential:sync")
    public ResultBean sync(@PathVariable(value = "id")Long id){

        Residential residential = this.residentialFeign.findResidentialById(id);
        if(null == residential) {
            return new ResultBean(ResultEnum.ERROR);
        }
       getBuildingListByResidentialId(residential);

        return new ResultBean(ResultEnum.SUCCESS);
    }

    //通过亲邻的小区id亲邻楼栋
    private List<BuildingDto> getBuildingListByResidentialId(Residential residential){
        List<BuildingDto> buildingDtos = new ArrayList<>();
        String sessionId = this.qLinAuthFeign.qLinAuth();
        int addBuildingResult = 0;
        int updateBuildingResult = 0;
        RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
        ResponseEntity responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
        headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
        headers.add("Cookie", "acw_tc=2760822c16041156819701506e1f0df2b6797f5010bb8a47e5c8d932fa360e");
        Map<String, Object> map = new HashMap<>();


        HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(map), headers);
        ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
        };

        String url = "https://qiotapi.qinlinkeji.com/admin/community/findBuildingList?sessionId="+sessionId+"&communityId="+residential.getOldId();
        URI uri = URI.create(url);
        responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


        Map map1 = (Map) responseEntity.getBody();
        List<Map> list = (List<Map>) map1.get("data");
        for (int i = 0; i < list.size(); i++) {
            BuildingDto building = new BuildingDto();
            Integer integer = (Integer) list.get(i).get("id");
            building.setOldId(Long.valueOf(integer.toString()));
            building.setName((String)list.get(i).get("buildingFullName"));
            building.setResidentialId(residential.getId());
            building.setResidentialName(residential.getName());
            Building building1 = this.buildingFeign.getByOldId(building.getOldId().toString());

            if (building1 != null) {
                building.setId(building1.getId());
                boolean result1 = this.buildingFeign.updateBuilding(building).getData();
                if(result1) {
                    updateBuildingResult = 1+ updateBuildingResult;
                }
            } else {
                Building result1= this.buildingFeign.addBuilding(building).getData();
                if(null != result1) {
                        addBuildingResult = 1+ addBuildingResult;

                    residential.setBuildingNumber(residential.getBuildingNumber()+1);
                    this.residentialFeign.updateResidentialEntity(residential);
                }

            }
            buildingDtos.add(building);

        }
        System.out.println("updateBuildingResult:"+updateBuildingResult+"   "+"addBuilding:"+addBuildingResult);
        return buildingDtos;

    }

    @PostMapping("/clearBuilding/{residentialId}")
    @Security(token = "estate:residential:delete")
    public ResultBean clearBuilding(@PathVariable("residentialId") Long residentialId) {
        boolean b = false;

        //进行删除房屋信息处理
        RoomDto roomDto = new RoomDto();
        roomDto.setResidentialId(residentialId);
        List<Room> rooms = roomFeign.getListByCondition(roomDto);
        if (rooms.size() > 0) {
            List<Room> roomList = new ArrayList<>();
            rooms.forEach(room -> {
                Room room1 = new Room();
                BeanUtils.copyProperties(room, room1);
                room1.setStatus(OperationConstant.MINUS_ONE);
                roomList.add(room1);
            });
            b = roomFeign.updateRoomList(roomList);
        }

        //进行删除楼层信息处理
        FloorDto floorDto = new FloorDto();
        floorDto.setResidentialId(residentialId);
        List<Floor> floors = floorFeign.getListByCondition(floorDto);
        if (floors.size() > 0) {
            List<Floor> floorList = new ArrayList<>();
            floors.forEach(floor -> {
                Floor floor1 = new Floor();
                BeanUtils.copyProperties(floor, floor1);
                floor1.setStatus(OperationConstant.MINUS_ONE);
                floorList.add(floor1);
            });
            b = floorFeign.updateFloorList(floorList);
        }

        //进行删除单元信息处理
        UnitDto unitDto = new UnitDto();
        unitDto.setResidentialId(residentialId);
        List<Unit> units = unitFeign.getListByCondition(unitDto);
        if (units.size() > 0) {
            List<Unit> unitList = new ArrayList<>();
            units.forEach(unit -> {
                Unit unit1 = new Unit();
                BeanUtils.copyProperties(unit, unit1);
                unit1.setStatus(OperationConstant.MINUS_ONE);
                unitList.add(unit1);
            });
            b = unitFeign.updateUnitList(unitList);
        }

        //进行删除楼栋信息处理
        BuildingDto buildingDto = new BuildingDto();
        buildingDto.setResidentialId(residentialId);
        List<Building> buildings = buildingFeign.getListByCondition(buildingDto);
        if (buildings.size() > 0) {
            List<Building> buildingList = new ArrayList<>();
            buildings.forEach(building -> {
                Building building1 = new Building();
                BeanUtils.copyProperties(building, building1);
                building1.setStatus(OperationConstant.MINUS_ONE);
                buildingList.add(building1);
            });
            b = buildingFeign.updateBuildingList(buildingList);
            //删除楼栋，小区的已录入楼栋数要改为0
            if (b) {
                Residential residential1 = new Residential();
                residential1.setId(residentialId);
                residential1.setBuildingNumber(0);
                residential1.setUnitNumber(0);
                residential1.setFloorNumber(0);
                residential1.setRoomNumber(0);
                residentialFeign.updateEntity(residential1);
            }
        }
        return new ResultBean(ResultEnum.SUCCESS, b);
    }

}
