package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.sptg.common.core.beans.ExcelResultEnum;
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.util.CommonUtil;
import com.sptg.common.core.util.WebUtils;
import com.sptg.estate.api.dto.ResidentialDto;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.enums.EstateEnum;
import com.sptg.estate.biz.mapper.ResidentialMapper;
import com.sptg.estate.biz.service.AccessCardServiceInterface;
import com.sptg.estate.biz.service.ResidentialServiceInterface;
import com.sptg.permissions.api.dto.AccountDto;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.AccountFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * title: ResidentialServiceImpl
 * package: com.sptg.estate.biz.security.impl
 * description: 小区 服务层实现层
 */
@Service
@RequiredArgsConstructor
public class ResidentialServiceImpl extends ServiceImpl<ResidentialMapper, Residential> implements ResidentialServiceInterface {

    private final OrgFeign orgFeign;

    private final RedisTemplate<String, String> redisTemplate;

    private final AccountFeign accountFeign;

    @Autowired
    @Lazy
    private AccessCardServiceInterface accessCardServiceInterface;

    private final static String IMPORT_CACHE_RESIDENTIAL_CODE = "sptg:import:residential:code";

    @Override
    public ResultBean<Page<Residential>> showResidentialList(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        //过滤删除
//        if (residentialDto.getStatus() != null){
//            wrapper.eq("u.i_status", residentialDto.getStatus());
//        }else {
        wrapper.eq("u.i_status", OperationConstant.ZERO);
//        }
        //根据分配标识
        if (null != residentialDto.getIsAssign()) {
            wrapper.eq("u.i_is_assign", residentialDto.getIsAssign());
        }
        //根据社区id
        if (null != residentialDto.getAgencyId()) {
            wrapper.eq("u.l_agency_id", residentialDto.getAgencyId());
        }
        //根据机构
        if (StringUtils.isNotBlank(residentialDto.getOrgPosition())) {
            wrapper.like("u.s_org_position", residentialDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //根据机构id
        if (residentialDto.getOrgPid() != null) {
            wrapper.eq("u.l_org_pid", residentialDto.getOrgPid());
        }
        //根据物业id
        if (residentialDto.getEstatePid() != null) {
            wrapper.eq("u.l_estate_pid", residentialDto.getEstatePid());
        }
        //根据物业名称
        if (StringUtils.isNotBlank(residentialDto.getEstatePidName())) {
            wrapper.like("u.s_estate_pid_name", residentialDto.getEstatePidName(), SqlLike.DEFAULT);
        }
        //根据物业
        if (StringUtils.isNotBlank(residentialDto.getEstatePosition())) {
            wrapper.like("u.s_estate_position", residentialDto.getEstatePosition(), SqlLike.RIGHT);
            System.out.println("s_estate_position" + residentialDto.getEstatePosition());
        }
        //根据区域Id查询
        if (StringUtils.isNotBlank(residentialDto.getRegionArea())) {
            wrapper.eq("u.s_region_area", residentialDto.getRegionArea());
        } else {
            if (StringUtils.isNotBlank(residentialDto.getRegionCity())) {
                wrapper.eq("u.s_region_city", residentialDto.getRegionCity());
            } else {
                if (StringUtils.isNotBlank(residentialDto.getRegionProvince())) {
                    wrapper.eq("u.s_region_province", residentialDto.getRegionProvince());
                }
            }
        }
        //根据编号查询
        if (StringUtils.isNotBlank(residentialDto.getResidentialNumber())) {
            wrapper.like("u.s_residential_number", residentialDto.getResidentialNumber());
        }
        //根据名字查询
        if (StringUtils.isNotBlank(residentialDto.getName())) {
            wrapper.like("u.s_name", residentialDto.getName(),SqlLike.DEFAULT);
        }
        //排序
        if (residentialDto.getSortField() != null && residentialDto.getSortOrder() != null) {
            //时间排序
            if (residentialDto.getSortField().equals("createDate")) {
                wrapper.orderBy("u.t_create_date", residentialDto.getSortOrder().equals("asc"));
            } else {
                //其他排序
                wrapper.orderBy(residentialDto.getSortField(), residentialDto.getSortOrder().equals("asc"));
            }
        } else {
            //默认排序
            wrapper.orderBy("u.t_create_date", false);
        }
        wrapper.groupBy("u.l_id");
        Page<Residential> page = residentialDto.getPage();
        page.setRecords(this.baseMapper.showResidentialList(page, wrapper));
        return new ResultBean<>(ResultEnum.SUCCESS, page);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Residential> addResidential(ResidentialDto residentialDto) {
        //先创建小区机构
        residentialDto.setUnitNumber(OperationConstant.ZERO);
        residentialDto.setRoomNumber(OperationConstant.ZERO);
        residentialDto.setUserNumber(OperationConstant.ZERO);
        residentialDto.setUserFaceNumber(OperationConstant.ZERO);
        residentialDto.setCreateDate(new Date());
        residentialDto.setStatus(OperationConstant.ZERO);
        residentialDto.setResidentialNumber(SymbolConstant.A_NO);
        OrgDto organization = this.buildResidentialOrg(residentialDto);
        ResultBean<Organization> organizationResultBean = this.orgFeign.addEntity(organization);
        if (null != organizationResultBean && organizationResultBean.getData() != null) {
            Organization data = organizationResultBean.getData();
            residentialDto.setOrgPid(data.getId());
            residentialDto.setOrgPidName(data.getName());
            residentialDto.setOrgPosition(data.getPosition());
            //新建小区账号
            Account onlineUser = new Account();
            onlineUser.setId(residentialDto.getCreateAccountId());
            Account account = new Account();
            account.setIsEnable(2);// 暂未禁用状态，需手动启用
            String personTel = residentialDto.getPersonTel();
            String loginPwd = CommonUtil.getPinYinHeadChar(residentialDto.getName()) + personTel.substring(personTel.length() - 4, personTel.length());
            account.setLoginPwd(loginPwd);
            account.setStatus(0);
            account.setUserPortraitUri("group1/M00/00/01/iwlnq1-2gWOAQZzsAAEaGqu-xVw734.jpg");
            account.setOrgId(data.getId());
            account.setRootOrgId(1L);
            account.setUserName(residentialDto.getName());
            account.setLoginName(residentialDto.getName());
            account.setOrgPosition(data.getPosition());

            account.setCreateAccountId(residentialDto.getOnLineUser().getId());
            account.setCreateIp(WebUtils.getIp());
//          这个会报错，导致账号创建失败
//            account.setCreateDate(new Date());

            Boolean accountResultBean = this.accountFeign.addEntityByResidential(account);
            System.out.println(accountResultBean);


            if (this.getResidentialByNameAndRegion(residentialDto) > 0) {
                return new ResultBean<>(EstateEnum.RESIDENTIAL_DATA_EXISTES);
            }

            boolean insert = this.insert(residentialDto);

            if (insert) {
                return new ResultBean<>(ResultEnum.SUCCESS, residentialDto);
            }
        }


        return new ResultBean<>(ResultEnum.ERROR);
    }

    @Override
    public Residential findResidentialById(Long id) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.eq("l_id", id);
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.selectOne(wrapper);
    }

    @Override
    public Residential findResidentialByNumber(String residentialNumber) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //小区编号
        wrapper.eq("s_residential_number", residentialNumber);
        return this.selectOne(wrapper);
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> updateResidential(ResidentialDto dto) {
        return new ResultBean<>(ResultEnum.SUCCESS, this.updateById(dto));
//        if (dto.isUpdateOrg()){
//            ResultBean<Boolean> resultBeanOrg = this.updateOrganization(dto);
//            if(resultBeanOrg.getCode().equals(ResultEnum.SUCCESS.getCode())){
//                dto.setOrgPosition(null);
//                return new ResultBean<>(ResultEnum.SUCCESS,this.updateById(dto));
//            }else{
//                return resultBeanOrg;
//            }
//        }else {
//            dto.setOrgPosition(null);
//            return new ResultBean<>(ResultEnum.SUCCESS,this.updateById(dto));
//        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> updateResidentialEntity(Residential residential) {
        return new ResultBean<>(ResultEnum.SUCCESS, this.updateById(residential));
    }

    @Override
    public ResultBean<Residential> getListByCondition(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        if (null != residentialDto.getOrgPid()) {
            wrapper.eq("l_org_pid", residentialDto.getOrgPid());
        }
        //根据物业pid
        if (null != residentialDto.getEstatePid()) {
            wrapper.eq("l_estate_pid", residentialDto.getEstatePid());
        }
        //根据机构
        if (StringUtils.isNotBlank(residentialDto.getOrgPosition())) {
            wrapper.like("s_org_position", residentialDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //根据物业
        if (StringUtils.isNotBlank(residentialDto.getEstatePosition())) {
            wrapper.like("s_estate_position", residentialDto.getEstatePosition(), SqlLike.RIGHT);
        }

        //小区名称
        if(StringUtils.isNotBlank(residentialDto.getName())) {
            wrapper.like("s_name", residentialDto.getName());
        }
        //小区名称
        if(StringUtils.isNotBlank(residentialDto.getRegionProvince())) {
            wrapper.like("s_region_province", residentialDto.getRegionProvince());
        }
        //小区名称
        if(StringUtils.isNotBlank(residentialDto.getRegionCity())) {
            wrapper.like("s_region_city", residentialDto.getRegionCity());
        }
        //小区名称
        if(StringUtils.isNotBlank(residentialDto.getRegionArea())) {
            wrapper.like("s_region_area", residentialDto.getRegionArea());
        }

        System.out.println("getListByCondition");
        return new ResultBean<>(ResultEnum.SUCCESS, this.baseMapper.selectList(wrapper));
    }

    @Override
    public List<Residential> getListByLikeName(ResidentialDto dto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.eq("i_status", OperationConstant.ZERO);
        if (StringUtils.isNotBlank(dto.getOrgPosition())) {
            wrapper.like("s_org_position", dto.getOrgPosition(), SqlLike.RIGHT);
        }
        if (StringUtils.isNotBlank(dto.getEstatePosition())) {
            wrapper.like("s_estate_position", dto.getEstatePosition(), SqlLike.DEFAULT);
        }
        //名称
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like("s_name", dto.getName(), SqlLike.DEFAULT);
        }
        //根据区域Id查询
        if (StringUtils.isNotBlank(dto.getRegionArea())) {
            wrapper.eq("s_region_area", dto.getRegionArea());
        } else if (StringUtils.isNotBlank(dto.getRegionCity())) {
            wrapper.eq("s_region_city", dto.getRegionCity());
        } else if (StringUtils.isNotBlank(dto.getRegionProvince())) {
            wrapper.eq("s_region_province", dto.getRegionProvince());
        }
        if (dto.getIsSelect()) {
            wrapper.last("limit 10");
        }
        return this.selectList(wrapper);
    }

    @Override
    public Residential getResidentialByOldId(String oldId) {
        Residential residential = new Residential();
        residential.setStatus(OperationConstant.ZERO);
        residential.setOldId(oldId);
        return this.baseMapper.selectOne(residential);
    }

    @Override
    public int addResidentialBySync(Residential residential) {
        return this.baseMapper.insert(residential);
    }

    @Override
    public List<Residential> getList() {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.eq("i_status", OperationConstant.ZERO);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> deleteResidential(ResidentialDto residentialDto) {
        Residential residential = this.findResidentialById(residentialDto.getId());
        if (null == residential) {
            return new ResultBean<>(ResultEnum.ERROR);
        }
        if (residential.getUnitNumber() > 0 || residential.getRoomNumber() > 0 || residential.getUserNumber() > 0) {
            return new ResultBean<>(EstateEnum.HAVE_CHILDREN);
        }
        residential.setStatus(residentialDto.getStatus());
        ResultBean<Boolean> resultBeanOrg = this.deleteOrganization(residentialDto);
        if (resultBeanOrg.getCode().equals(ResultEnum.SUCCESS.getCode())) {
            if (this.updateById(residential)) {
                //删除关联卡及下发的卡号
                if (this.accessCardServiceInterface.deleteAccessCardByIdAndType(residential.getId(), OperationConstant.THREE)) {
                    this.deleteCache(residential);
                    return new ResultBean<>(ResultEnum.SUCCESS, true);
                }
            }
        } else {
            return resultBeanOrg;
        }
        return new ResultBean<>(ResultEnum.ERROR);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    @LcnTransaction
    public ResultBean<Boolean> trashOrRecover(ResidentialDto residentialDto) {
        Residential residential = this.findResidentialById(residentialDto.getId());
        if (null == residential) {
            return new ResultBean<>(ResultEnum.ERROR);
        }
        residential.setStatus(residentialDto.getStatus());
        ResultBean<Boolean> resultBeanOrg = this.deleteOrganization(residentialDto);
        if (resultBeanOrg.getCode().equals(ResultEnum.SUCCESS.getCode())) {
            if (this.updateById(residential)) {
                //删除关联卡及下发的卡号
                if (this.accessCardServiceInterface.deleteAccessCardByIdAndType(residential.getId(), OperationConstant.THREE)) {
                    this.deleteCache(residential);
                    return new ResultBean<>(ResultEnum.SUCCESS, true);
                }
            }
        } else {
            return resultBeanOrg;
        }
        return new ResultBean<>(ResultEnum.ERROR);
    }

    @Override
    @LcnTransaction

    public ResultBean<Boolean> deleteResidentialList(ResidentialDto residentialDto) throws Exception {
        List<String> ids = residentialDto.getIds();
        String msg;
        for (String id : ids) {
            Residential residential = this.findResidentialById(Long.valueOf(id));
            if (null == residential) {
                msg = "小区不存在，请核实后重新操作";
                throw new Exception(msg);
            }
            if (residential.getUnitNumber() > 0 || residential.getRoomNumber() > 0 || residential.getUserNumber() > 0) {
                msg = residential.getName() + "小区含有下级数据，请核实后重新操作";
                throw new Exception(msg);
            }
            residential.setStatus(OperationConstant.MINUS_ONE);
            residentialDto.setId(Long.valueOf(id));
            ResultBean<Boolean> resultBeanOrg = this.deleteOrganization(residentialDto);
            if (resultBeanOrg.getCode().equals(ResultEnum.SUCCESS.getCode())) {
                if (this.updateById(residential)) {
                    //删除关联卡及下发的卡号
                    if (this.accessCardServiceInterface.deleteAccessCardByIdAndType(residential.getId(), OperationConstant.THREE)) {
                        this.deleteCache(residential);
                    } else {
                        msg = residential.getName() + "小区关联卡删除失败，请核实后重新操作";
                        throw new Exception(msg);
                    }
                }
            } else {
                throw new Exception(resultBeanOrg.getMsg());
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS, true);
    }

    @Override
    public ResultBean<Residential> findListByPosition(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        //过滤删除
        wrapper.notIn("u.i_status", OperationConstant.MINUS_ONE);
        if (null != residentialDto.getOrgPid()) {
            wrapper.eq("u.l_org_pid", residentialDto.getOrgPid());
        }
        //根据机构
        if (StringUtils.isNotBlank(residentialDto.getOrgPosition())) {
            wrapper.like("u.s_org_position", residentialDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //根据机构
        if (StringUtils.isNotBlank(residentialDto.getEstatePosition())) {
            wrapper.like("u.s_estate_position", residentialDto.getEstatePosition(), SqlLike.RIGHT);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, this.baseMapper.findListByPosition(wrapper));
    }

    @Override
    public Page<Residential> statisticsUserCountList(ResidentialDto residentialDto) {
        Page page = residentialDto.getPage();
        Wrapper<Residential> wrapper = new EntityWrapper<Residential>();
        //分页条件
        Wrapper<Residential> wrapperPage = new EntityWrapper<Residential>();
        //按地区查询
        //省
        String province = residentialDto.getRegionProvince();
        if (StringUtils.isNotBlank(province)) {
            wrapper.eq("re.s_region_province", province);
            wrapperPage.eq("s_region_province", province);
        }
        //市
        String city = residentialDto.getRegionCity();
        if (StringUtils.isNotBlank(city)) {
            wrapper.eq("re.s_region_city", city);
            wrapperPage.eq("s_region_city", city);
        }
        //区
        String area = residentialDto.getRegionArea();
        if (StringUtils.isNotBlank(area)) {
            wrapper.eq("re.s_region_area", area);
            wrapperPage.eq("s_region_area", area);
        }
        //小区id
        Long residentialId = residentialDto.getId();
        if (residentialId != null) {
            wrapper.eq("re.l_id", residentialId);
            wrapperPage.eq("l_id", residentialId);
        }
        //物业
        Long orgPid = residentialDto.getOrgPid();
        if (orgPid != null) {
            wrapper.eq("re.l_org_pid", orgPid);
            wrapperPage.eq("l_org_pid", orgPid);
        }

        //机构位置
        String orgPosition = residentialDto.getOrgPosition();
        if (StringUtils.isNotBlank(orgPosition)) {
            wrapper.like("re.s_org_position", orgPosition, SqlLike.RIGHT);
            wrapperPage.like("s_org_position", orgPosition, SqlLike.RIGHT);
        }
        List<Residential> resultList = this.baseMapper.statisticsUserCountList((page.getCurrent() - 1) * page.getSize(), page.getSize(), wrapper);
        page.setRecords(resultList);
        wrapperPage.eq("i_status", OperationConstant.ZERO);
        page.setTotal(this.selectCount(wrapperPage));
        return page;
    }

    @Override
    public List<Residential> getStatisticsUserCountList(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<Residential>();
        //按地区查询
        //省
        String province = residentialDto.getRegionProvince();
        if (StringUtils.isNotBlank(province)) {
            wrapper.eq("re.s_region_province", province);
        }
        //市
        String city = residentialDto.getRegionCity();
        if (StringUtils.isNotBlank(city)) {
            wrapper.eq("re.s_region_city", city);
        }
        //区
        String area = residentialDto.getRegionArea();
        if (StringUtils.isNotBlank(area)) {
            wrapper.eq("re.s_region_area", area);
        }
        //小区id
        Long residentialId = residentialDto.getId();
        if (residentialId != null) {
            wrapper.eq("re.l_id", residentialId);
        }
        //物业
        Long orgPid = residentialDto.getOrgPid();
        if (orgPid != null) {
            wrapper.eq("re.l_org_pid", orgPid);
        }
        //状态
        wrapper.eq("re.i_status", OperationConstant.ZERO);
        //统计新增时间
        Date statisticsDate = residentialDto.getStatisticsDate();
        if (statisticsDate != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
            String statisticsDateStr = simpleDateFormat.format(statisticsDate);
            wrapper.eq("DATE_FORMAT(u.t_create_date,'%Y%m')", statisticsDateStr);
        }
        //机构位置
        String orgPosition = residentialDto.getOrgPosition();
        if (StringUtils.isNotBlank(orgPosition)) {
            wrapper.like("re.s_org_position", orgPosition, SqlLike.RIGHT);
        }
        List<Residential> resultList = this.baseMapper.statisticsUserCountList(null, null, wrapper);
        return resultList;
    }

    @Override
    public long statisticsUserCount(String orgPosition) {
        Wrapper<Residential> wrapper = new EntityWrapper<Residential>();
        wrapper.setSqlSelect("sum(i_user_number)");
        //根据机构
        if (StringUtils.isNotBlank(orgPosition)) {
            wrapper.like("s_org_position", orgPosition, SqlLike.RIGHT);
        }
        //状态
        wrapper.eq("i_status", OperationConstant.ZERO);
        BigDecimal countB = (BigDecimal) this.selectObj(wrapper);
        return countB == null ? 0 : countB.longValue();
    }

    @Override
    @LcnTransaction
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Boolean> importResidentialList(List<ResidentialDto> list) throws Exception {
        int size = list.size();
        ResidentialDto residentialDto;
        for (int i = 0; i < size; i++) {
            residentialDto = list.get(i);
            residentialDto.setUnitNumber(OperationConstant.ZERO);
            residentialDto.setRoomNumber(OperationConstant.ZERO);
            residentialDto.setUserNumber(OperationConstant.ZERO);
            residentialDto.setUserFaceNumber(OperationConstant.ZERO);
            residentialDto.setCreateDate(new Date());
            residentialDto.setStatus(OperationConstant.ZERO);
            residentialDto.setResidentialNumber(SymbolConstant.A_NO);
            ResultBean<Organization> resultBeanOrg = this.addOrganization(residentialDto);
            if (ResultEnum.SUCCESS.getCode().equals(resultBeanOrg.getCode())) {
                Organization org = resultBeanOrg.getData();
                residentialDto.setId(org.getId());
                residentialDto.setResidentialNumber(org.getCode());
                residentialDto.setRootOrgId(org.getRootOrgId());
                residentialDto.setOrgPosition(org.getPosition());
                this.insert(residentialDto);
            } else {
                throw new Exception(resultBeanOrg.getMsg());
            }
        }
        return new ResultBean<>(ExcelResultEnum.SUCCESS, true);
    }

    @Override
    public int getResidentialAccount(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(residentialDto.getOrgPosition())) {
            wrapper.like("s_org_position", residentialDto.getOrgPosition(), SqlLike.RIGHT);
        }
        if (StringUtils.isNotBlank(residentialDto.getEstatePosition())) {
            wrapper.like("s_estate_position", residentialDto.getEstatePosition(), SqlLike.RIGHT);
        }

        //当月新增
        if (OperationConstant.TWO == residentialDto.getIsAllType()) {
            wrapper.and("DATE_FORMAT(t_create_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m')");
        }
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.selectCount(wrapper);
    }

    @Override
    public ResultBean<Residential> getByRegionArea(Residential residential) {
        //构建查询条件
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        //根据区编号查询
        wrapper.eq("s_region_area", residential.getRegionArea());
        wrapper.like("s_org_position", residential.getOrgPosition());
        //过滤状态--  -1：已删除，0：正常
        wrapper.eq("i_status", OperationConstant.ZERO);
        if (StringUtils.isNotBlank(residential.getName())) {
            wrapper.like("s_name", residential.getName());
        }
        return new ResultBean<>(ResultEnum.SUCCESS, this.selectList(wrapper));
    }

    @Override
    public long getUnitCount(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("sum(i_unit_number)");
        wrapper.like("s_org_position", residentialDto.getOrgPosition(), SqlLike.RIGHT);
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        BigDecimal bigDecimalUnit = (BigDecimal) this.selectObj(wrapper);
        return bigDecimalUnit == null ? 0L : bigDecimalUnit.longValue();
    }

    @Override
    public List<Map<String, Object>> statisticsCityCountList(String regionProvince, String orgPosition) {
        return this.baseMapper.statisticsCityCountList(regionProvince, orgPosition);
    }

    @Override
    public int getResidentialByNameAndRegion(ResidentialDto residentialDto) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.eq("s_name", residentialDto.getName());
        wrapper.eq("s_region_province", residentialDto.getRegionProvince());
        wrapper.eq("s_region_city", residentialDto.getRegionCity());
        wrapper.eq("s_region_area", residentialDto.getRegionArea());
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.selectCount(wrapper);
    }

    @Override
    public long getUserCountForRegionAuthorize(String orgPosition) {
        Long userCountForRegionAuthorize = this.baseMapper.getUserCountForRegionAuthorize(orgPosition);
        return userCountForRegionAuthorize == null ? 0L : userCountForRegionAuthorize;
    }

    /* -------------------------------------------------- 外部方法 -------------------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------- */

    /**
     * 功能描述:保存到机构
     *
     * @param residentialDto 小区传输对象
     * @return ResultBean<Organization>
     */
    private ResultBean<Organization> addOrganization(ResidentialDto residentialDto) {
        OrgDto organizationDto = this.copyOrganizationDto(residentialDto);
        return this.orgFeign.addEntity(organizationDto);
    }

    /**
     * 功能描述:更新到机构
     *
     * @param residentialDto 小区传输对象
     * @return ResultBean<Boolean>
     */
    private ResultBean<Boolean> updateOrganization(ResidentialDto residentialDto) {
        OrgDto organizationDto = this.copyOrganizationDto(residentialDto);
        return this.orgFeign.editEntity(organizationDto);
    }

    /**
     * 功能描述:删除到机构
     *
     * @param residentialDto 小区传输对象
     * @return ResultBean<Boolean>
     */
    private ResultBean<Boolean> deleteOrganization(ResidentialDto residentialDto) {
        OrgDto organizationDto = this.copyOrganizationDto(residentialDto);
        return this.orgFeign.deleteEntity(organizationDto);
    }

    /**
     * 功能描述:组装机构对象
     *
     * @param residentialDto 小区业务对象
     * @return ResultBean<Organization>
     */
    private OrgDto copyOrganizationDto(ResidentialDto residentialDto) {
        OrgDto dto = new OrgDto();
        //编辑删除
        if (residentialDto.getId() != null) {
            dto.setId(residentialDto.getId());
        }
        dto.setPid(residentialDto.getOrgPid());
        dto.setName(residentialDto.getName());
        dto.setCode(residentialDto.getResidentialNumber());
        dto.setPersonName(residentialDto.getPersonName());
        dto.setPersonTel(residentialDto.getPersonTel());
        dto.setRegionProvince(residentialDto.getRegionProvince());
        dto.setRegionCity(residentialDto.getRegionCity());
        dto.setRegionArea(residentialDto.getRegionArea());
        dto.setRegion(residentialDto.getRegion());
        dto.setAddress(residentialDto.getAddress());
        dto.setRemark(residentialDto.getRemark());
        dto.setFlag(OperationConstant.TWO);
        dto.setIsEnable(OperationConstant.ONE);
        dto.setPosition(residentialDto.getOrgPosition());
        dto.setCreateAccountId(residentialDto.getCreateAccountId());
        dto.setStatus(residentialDto.getStatus());
        return dto;
    }

    /* -------------------------------------------------- 内部方法 -------------------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------- */

    /**
     * 功能描述:删除缓存
     *
     * @param residential
     */
    private void deleteCache(Residential residential) {
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        String hashKey = residential.getResidentialNumber();
        String json = hashOperations.get(IMPORT_CACHE_RESIDENTIAL_CODE, hashKey);
        if (!StringUtils.isEmpty(json)) {
            hashOperations.delete(IMPORT_CACHE_RESIDENTIAL_CODE, hashKey);
        }
    }


    private OrgDto buildResidentialOrg(ResidentialDto residentialDto) {
        //新增小区实体对应的小区机构
        OrgDto organization = new OrgDto();
        organization.setPosition(residentialDto.getOrgPositionOfResidentialOrg());
        organization.setStatus(0);
        organization.setFlag(1);
        organization.setRootOrgId(1L);
        organization.setPosition(residentialDto.getOrgPosition());
        organization.setCreateDate(residentialDto.getCreateDate());
        organization.setRegionStreet(residentialDto.getRegionStreet());
        organization.setRegionProvince(residentialDto.getRegionProvince());
        organization.setRegionCity(residentialDto.getRegionCity());
        organization.setRegionArea(residentialDto.getRegionArea());
        organization.setPersonTel(residentialDto.getPersonTel());
        organization.setPersonName(residentialDto.getPersonName());
        organization.setName(residentialDto.getName());
        organization.setPid(residentialDto.getParentIdOfResidentialOrg());
        organization.setOrgType(6);
        organization.setLayerNumber(3);
        organization.setAddress(residentialDto.getAddress());
        organization.setIsEnable(1);
        organization.setCode("A");
        organization.setParentName(residentialDto.getParentNameOfResidentialOrg());
        return organization;
    }

}

