package com.yuchen.saas.park.service.service.property;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkunion.park.service.common.utils.PingYinUtil;
import com.thinkunion.park.service.common.utils.StringGenerator;
import com.yuchen.saas.park.api.dto.property.PropertyHousesAutoDeductionDto;
import com.yuchen.saas.park.api.dto.property.PropertyHousesBindingQueryDto;
import com.yuchen.saas.park.api.dto.property.PropertyHousesQryDto;
import com.yuchen.saas.park.api.entity.park.PeoplePropertyRelation;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatParkPeople;
import com.yuchen.saas.park.api.entity.property.*;
import com.yuchen.saas.park.api.vo.property.*;
import com.yuchen.saas.park.service.mapper.property.PropertyHousesMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.constant.NestConstant;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.nest.springwrap.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 洪铭铭
 * @time: 2024/10/31 14:57
 */
@Service
public class SaasParkMoveInHouseService extends BaseServiceImpl<PropertyHousesMapper, PropertyHouses> {

    @Autowired
    private PropertyBuildingsService propertyBuildingsService;
    @Autowired
    private PropertyBuildingUnitService propertyBuildingUnitService;
    @Autowired
    private PropertyBuildingsLevelService propertyBuildingsLevelServiceService;

    @Autowired
    private PropertySearchParkInfoService propertySearchParkInfoService;
    @Lazy
    @Autowired
    private PmgBatParkInfoService parkInfoService;
    @Lazy
    @Resource
    private IPropertyEnterpriseAddressService iPropertyEnterpriseAddressService;
    @Lazy
    @Resource
    private IPropertyUserHouseService iPropertyUserHouseService;
    @Lazy
    @Resource
    private IPropertyHouseResidentService propertyHouseResidentService;

    @Autowired
    private IPeoplePropertyRelationService peoplePropertyRelationService;
    @Autowired
    private IParkingPropertyRelationService parkingPropertyRelationService;
    @Autowired
    private ICarPropertyRelationService carPropertyRelationService;


    /**
     * 房源信息保存
     * @param propertyHouses
     * @return
     */
    public boolean saveMoveInHouse(PropertyHouses propertyHouses) {
        this.verifySaveHouse(propertyHouses);
        this.assemblePropertyHouses(propertyHouses);
        List<PmgBatParkPeople> residents = propertyHouses.getResidents();
        for (PmgBatParkPeople p : residents) {
            PeoplePropertyRelation r = BeanUtil.copyProperties(p, PeoplePropertyRelation.class);
            r.setPeopleId(p.getId());
            r = BeanUtil.copyProperties(propertyHouses, PeoplePropertyRelation.class);
            peoplePropertyRelationService.save(r);
        }

        List<PropertyHouses.ParkingPlace> parking = propertyHouses.getParkingSpace();
        for (PropertyHouses.ParkingPlace p : parking) {

            ParkingPropertyRelation r = BeanUtil.copyProperties(p, ParkingPropertyRelation.class);
            r.setParkingId(p.getId());
            r = BeanUtil.copyProperties(propertyHouses, ParkingPropertyRelation.class);
            parkingPropertyRelationService.save(r);
        }

        List<PropertyHouses.PmgBatParkCar> cars = propertyHouses.getCars();
        for (PropertyHouses.PmgBatParkCar c : cars) {

            CarPropertyRelation r = BeanUtil.copyProperties(c, CarPropertyRelation.class);
            r.setCarId(c.getId());
            r = BeanUtil.copyProperties(propertyHouses, CarPropertyRelation.class);
            carPropertyRelationService.save(r);
        }

        return this.saveOrUpdate(propertyHouses);
    }

    /**
     * 组装保存对象
     * @param propertyHouses
     */
    private void assemblePropertyHouses(PropertyHouses propertyHouses) {
        PropertyBuildings building = propertyBuildingsService.getById(propertyHouses.getBuildingId());
        String unitNum = propertyHouses.getUnitNum() == null ? "" : propertyHouses.getUnitNum();
        // 房源资源编码 = 楼栋资源编码 + 单元号 + 房间号
        String resourceCode = building.getResourceCode() + "-" + unitNum + PingYinUtil.getPinYinHeadCharUpper(propertyHouses.getHouseName());

        LambdaQueryWrapper<PropertyHouses> qw = new LambdaQueryWrapper<>();
        qw.eq(PropertyHouses::getBuildingId, propertyHouses.getBuildingId());
        qw.eq(PropertyHouses::getResourceCode, resourceCode);
        PropertyHouses houses = this.getOne(qw);
        if (houses != null) { // 如果已存在拼两位随机数
            resourceCode += StringGenerator.GetRandomString(2);
        }

        propertyHouses.setResourceCode(resourceCode);

    }


    /**
     * 房源信息保存校验
     * @param propertyHouses
     */
    private void verifySaveHouse(PropertyHouses propertyHouses) {
        LambdaQueryWrapper<PropertyHouses> qw = new LambdaQueryWrapper<>();
        qw.eq(PropertyHouses::getBuildingId, propertyHouses.getBuildingId());
        qw.eq(PropertyHouses::getIsDeleted, NestConstant.DB_NOT_DELETED);
        qw.eq(PropertyHouses::getResourceCode, propertyHouses.getResourceCode());
        PropertyHouses houses1 = this.getOne(qw);
        if (houses1 != null) {
            if (StringUtil.isEmpty(propertyHouses.getId())
                    || !houses1.getResourceCode().equals(propertyHouses.getResourceCode())) {
                throw new ServiceException("资源代码已存在");
            }
        }

        LambdaQueryWrapper<PropertyHouses> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(PropertyHouses::getBuildingId, propertyHouses.getBuildingId());
        qw2.eq(PropertyHouses::getIsDeleted,NestConstant.DB_NOT_DELETED);
        qw2.eq(PropertyHouses::getHouseName, propertyHouses.getHouseName());
        PropertyHouses houses2 = this.getOne(qw2);
        if (houses2 != null) {
            if (StringUtil.isEmpty(propertyHouses.getId())
                    || !houses2.getId().equals(propertyHouses.getId())) {
                throw new ServiceException("房间名称已存在");
            }
        }

    }


    /**
     * 根据房源houseIdLists查询房源信息
     * @param houseIdList
     * @return
     */
    public List<PropertyHousesListVo> queryHouseInfoByHouseIdList(List<Long> houseIdList) {
        if (houseIdList == null || houseIdList.size() == 0) {
            return new ArrayList<>();
        }
        PropertyHousesQryDto qryDto = new PropertyHousesQryDto();
        qryDto.setCurrent(-1);
        qryDto.setSize(-1);
        qryDto.setHouseIdList(houseIdList);
        List<PropertyHousesListVo> result = this.selectPage(qryDto).getRecords();
        return result;
    }


    /**
     * 楼栋分页查询
     * @param qryDto
     * @return
     */
    public Page<PropertyHousesListVo> selectPage(PropertyHousesQryDto qryDto) {
        Page<PropertyHousesListVo> page = new Page<>(qryDto.getCurrent(), qryDto.getSize());
        baseMapper.propertyHousesPage(page, this.getPageQueryParam(qryDto));
        page.getRecords().forEach(record -> {
            // TODO tucq 查询优化？
            PropertyTenantOwnerVo vo = propertyHouseResidentService.getTenantOrOwnerInfo(record.getId());
            if (vo != null) {
                record.setCustomerName(vo.getCustomerName());
                record.setPhone(vo.getPhone());
                record.setIdentification(vo.getIdNo());
            }
        });

        return page;
    }


    /**
     * 分页查询条件
     * @param qryDto
     * @return
     */
    private QueryWrapper<String> getPageQueryParam(PropertyHousesQryDto qryDto) {
        QueryWrapper<String> qw = new QueryWrapper<>();
        if (StringUtil.isNotBlank(qryDto.getHouseName())) {
            qw.like("h.house_name", qryDto.getHouseName());
        }
        if (StringUtil.isNotBlank(qryDto.getBuildingName())) {
            qw.like("b.building_name", qryDto.getBuildingName());
        }
        if (Func.isNotEmpty(qryDto.getParkId())) {
            qw.eq("h.park_id",qryDto.getParkId());
        } else {
            qw.in("h.park_id",propertySearchParkInfoService.getParkIdsByCurrUser());
        }
        if (Func.isNotEmpty(qryDto.getBuildingId())) {
            qw.eq("h.building_id",qryDto.getBuildingId());
        }
        if (Func.isNotEmpty(qryDto.getHouseStatus())) {
            String[] list = qryDto.getHouseStatus().split(",");
            for (int i = 0; i < list.length; i++) {
                qw.eq("h.house_status",list[i]);
                if (i != list.length - 1 ) {
                    qw.or();
                }
            }
        }
        if (Func.isNotEmpty(qryDto.getRenovateStatus())) {
            String[] list = qryDto.getRenovateStatus().split(",");
            for (int i = 0; i < list.length; i++) {
                qw.eq("h.renovate_status",list[i]);
                if (i != list.length - 1 ) {
                    qw.or();
                }
            }
        }
        if (Func.isNotEmpty(qryDto.getUseType())) {
            qw.eq("h.use_type",qryDto.getUseType());
        }
        if (Func.isNotEmpty(qryDto.getIsRentOut())) {
            qw.eq("h.is_rent_out",qryDto.getIsRentOut());
        }
        if (Func.isNotEmpty(qryDto.getTowardType())) {
            qw.eq("h.toward_type",qryDto.getTowardType());
        }
        if (Func.isNotEmpty(qryDto.getHeightType())) {
            qw.eq("h.height_type",qryDto.getHeightType());
        }
        if (Func.isNotEmpty(qryDto.getUnitNum())) {
            qw.eq("h.unit_num",qryDto.getUnitNum());
        }
        if (Func.isNotEmpty(qryDto.getResourceCode())) {
            qw.like("h.resource_code",qryDto.getResourceCode());
        }
        if (qryDto.getHouseIdList() != null && qryDto.getHouseIdList().size() > 0) {
            qw.in("h.id",qryDto.getHouseIdList());
        }
        if (Func.isNotEmpty(qryDto.getLevelName())) {
            qw.like("h.level_name",qryDto.getLevelName());
        }
        if (Func.isNotEmpty(qryDto.getUnitName())) {
            qw.like("h.unit_name",qryDto.getUnitName());
        }
        qw.eq("h.is_deleted", NestConstant.DB_NOT_DELETED);
        return qw;
    }

    /**
     * 房源明细
     * @param houseId
     * @return
     */
    public PropertyHousesVo getPropertyHousesDetail(Long houseId) {
        PropertyHousesVo vo = new PropertyHousesVo();
        PropertyHouses house = this.getById(houseId);
        if (house != null) {
            PropertyBuildings building = propertyBuildingsService.getById(house.getBuildingId());
            vo.setBuildingName(building.getBuildingName());
            BeanUtil.copyProperties(house,vo);
        }
        return vo;
    }

    /**
     *
     * @param buildingId
     * @return
     */
    public List<PropertyHouses> listByBuildingId(Long buildingId) {
        return this.lambdaQuery().eq(PropertyHouses::getBuildingId, buildingId).list();
    }

    public List<PropertyHouses> listByParkId(Long parkId) {
        return this.lambdaQuery().eq(PropertyHouses::getParkId, parkId).list();
    }

    public List<PropertyHouses> listByFoolNum(Integer floorNum) {
        return this.lambdaQuery().eq(PropertyHouses::getFloorNum, floorNum).list();
    }

    public List<PropertyHouses> listByUnitNum(String unitNum) {
        return this.lambdaQuery().eq(PropertyHouses::getUnitNum, unitNum).list();
    }

    /**
     * 根据房源id查询园区楼栋信息
     * @param houseIdList
     * @return
     */
    public List<PropertyHouseParentInfoVo> listHouseParentInfo(List<Long> houseIdList) {
        if (houseIdList == null || houseIdList.size() == 0) {
            return new ArrayList<>();
        }
        List<String> ids = new ArrayList<>();
        houseIdList.forEach(id -> ids.add(String.valueOf(id)));
        return baseMapper.searchHouseParentInfoList(String.join(",",ids));
    }


    /**
     * 房源树形结构
     * @param parkId
     * @return
     */
    public PropertyHousesTreeVo getHousesTree(Long parkId) {
        //某个园区房源树结构返回信息
        PropertyHousesTreeVo result = new PropertyHousesTreeVo();
        //楼栋信息集合
        List<PropertyHousesTreeVo> buildingList = new ArrayList<>();
        //获取园区信息
        PmgBatParkInfo pmgBatParkInfo = parkInfoService.getById(parkId);

        result.setId(pmgBatParkInfo.getId());
        result.setType(1);
        result.setName(pmgBatParkInfo.getParkName());
        result.setParentId(0L);

        //园区下所以楼栋信息
        List<PropertyBuildings> allBuilding = propertyBuildingsService.lambdaQuery().eq(PropertyBuildings::getParkId, parkId).list();
        //循环根据楼栋id获取楼层信息
        allBuilding.forEach(building -> {
            PropertyHousesTreeVo buildingTree = new PropertyHousesTreeVo();
            buildingTree.setId(building.getId());
            buildingTree.setName(building.getBuildingName());
            buildingTree.setType(2);
            buildingTree.setParentId(pmgBatParkInfo.getId());
            List<PropertyBuildingUnit> units = propertyBuildingUnitService.lambdaQuery().eq(PropertyBuildingUnit::getBuildingId, building.getId()).list();
            if (Func.isNotEmpty(units)) {
                //单元信息集合
                List<PropertyHousesTreeVo> unitList = new ArrayList<>();
                units.forEach(unit -> {
                    PropertyHousesTreeVo unitsTree = new PropertyHousesTreeVo();
                    unitsTree.setId(unit.getId());
                    unitsTree.setName(unit.getUnitNum() + "单元");
                    unitsTree.setType(3);
                    unitsTree.setParentId(building.getId());
                    //楼层信息信息集合
                    List<PropertyHousesTreeVo> foorList = new ArrayList<>();
                    Integer floorNum = building.getFloorNum();
                    for (Integer i = 1; i <= floorNum; i++) {
                        PropertyHousesTreeVo floorTree = new PropertyHousesTreeVo();
                        Long floorId = Long.valueOf(generateOrderNumber().substring(0, 19));
                        floorTree.setId(floorId);
                        floorTree.setName(i + "层");
                        floorTree.setType(4);
                        floorTree.setParentId(unit.getId());
                        //房源信息集合
                        List<PropertyHousesTreeVo> housesList = new ArrayList<>();
                        List<PropertyHouses> propertyHousesList = lambdaQuery().eq(PropertyHouses::getFloorNum, i).eq(PropertyHouses::getBuildingId, building.getId()).eq(PropertyHouses::getUnitNum, unit.getUnitNum()).list();
                        if (Func.isEmpty(propertyHousesList)) {
                            continue;
                        }
                        propertyHousesList.forEach(house -> {
                            PropertyHousesTreeVo houseTree = new PropertyHousesTreeVo();
                            houseTree.setId(house.getId());
                            houseTree.setName(house.getHouseName());
                            houseTree.setType(5);
                            houseTree.setParentId(floorId);
                            housesList.add(houseTree);
                        });
                        floorTree.setChildrenVoList(housesList);
                        foorList.add(floorTree);
                    }
                    if (Func.isNotEmpty(foorList)) {
                        unitsTree.setChildrenVoList(foorList);
                        unitList.add(unitsTree);
                    }
                });
                if (Func.isNotEmpty(unitList)) {
                    buildingTree.setChildrenVoList(unitList);
                    buildingList.add(buildingTree);
                }

            } else {
                //楼层信息信息集合
                List<PropertyHousesTreeVo> foorList = new ArrayList<>();
                Integer floorNum = building.getFloorNum();
                for (Integer i = 1; i <= floorNum; i++) {
                    PropertyHousesTreeVo floorTree = new PropertyHousesTreeVo();
                    Long floorId = Long.valueOf(generateOrderNumber().substring(0, 19));
                    floorTree.setId(floorId);
                    floorTree.setName(i + "层");
                    floorTree.setType(4);
                    floorTree.setParentId(building.getId());
                    //房源信息集合
                    List<PropertyHousesTreeVo> housesList = new ArrayList<>();
                    List<PropertyHouses> propertyHousesList = lambdaQuery().eq(PropertyHouses::getFloorNum, i).eq(PropertyHouses::getBuildingId, building.getId()).list();
                    if (Func.isEmpty(propertyHousesList)) {
                        continue;
                    }
                    propertyHousesList.forEach(house -> {
                        PropertyHousesTreeVo houseTree = new PropertyHousesTreeVo();
                        houseTree.setId(house.getId());
                        houseTree.setName(house.getHouseName());
                        houseTree.setType(5);
                        houseTree.setParentId(floorId);
                        housesList.add(houseTree);
                    });
                    floorTree.setChildrenVoList(housesList);
                    foorList.add(floorTree);
                }
                if (Func.isNotEmpty(foorList)) {
                    buildingTree.setChildrenVoList(foorList);
                    buildingList.add(buildingTree);
                }

            }
        });
        //楼栋信息
        result.setChildrenVoList(buildingList);
        return result;
    }

    /**
     * 房源树形结构
     * @param parkId
     * @return
     */
    public PropertyHousesTreeVo getHousesTreePoly(Long parkId) {
        //某个园区房源树结构返回信息
        PropertyHousesTreeVo result = new PropertyHousesTreeVo();
        //楼栋信息集合
        List<PropertyHousesTreeVo> buildingList = new ArrayList<>();
        //获取园区信息
        PmgBatParkInfo pmgBatParkInfo = parkInfoService.getById(parkId);

        result.setId(pmgBatParkInfo.getId());
        result.setType(1);
        result.setName(pmgBatParkInfo.getParkName());
        result.setParentId(0L);

        //园区下所以楼栋信息
        List<PropertyBuildings> allBuilding = propertyBuildingsService.lambdaQuery().eq(PropertyBuildings::getParkId, parkId).list();
        //循环根据楼栋id获取楼层信息
        allBuilding.forEach(building -> {
            PropertyHousesTreeVo buildingTree = new PropertyHousesTreeVo();
            buildingTree.setId(building.getId());
            buildingTree.setName(building.getBuildingName());
            buildingTree.setType(2);
            buildingTree.setParentId(pmgBatParkInfo.getId());
            List<PropertyBuildingUnit> units = propertyBuildingUnitService.lambdaQuery().eq(PropertyBuildingUnit::getBuildingId, building.getId()).list();

            //单元信息集合
            List<PropertyHousesTreeVo> unitList = new ArrayList<>();

            units.forEach(unit -> {
                PropertyHousesTreeVo unitsTree = new PropertyHousesTreeVo();
                unitsTree.setId(unit.getId());
                unitsTree.setName(unit.getUnitName());
                unitsTree.setType(3);
                unitsTree.setParentId(building.getId());
                //楼层信息信息集合
                List<PropertyHousesTreeVo> foorList = new ArrayList<>();
                List<PropertyBuildingsLevel> propertyBuildingsLevelList = propertyBuildingsLevelServiceService.lambdaQuery().eq(PropertyBuildingsLevel::getBuildingUnitId, unit.getId()).list();
                propertyBuildingsLevelList.forEach(level -> {
                    PropertyHousesTreeVo floorTree = new PropertyHousesTreeVo();
                    floorTree.setId(level.getId());
                    floorTree.setName(level.getLevelName());
                    floorTree.setType(4);
                    floorTree.setParentId(unit.getId());

                    List<PropertyHousesTreeVo> housesList = new ArrayList<>();
                    List<PropertyHouses> propertyHousesList = lambdaQuery().eq(PropertyHouses::getLevelId, level.getId()).list();
                    propertyHousesList.forEach(house -> {
                        PropertyHousesTreeVo houseTree = new PropertyHousesTreeVo();
                        houseTree.setId(house.getId());
                        houseTree.setName(house.getHouseName());
                        houseTree.setType(5);
                        houseTree.setParentId(level.getId());
                        housesList.add(houseTree);
                    });
                    floorTree.setChildrenVoList(housesList);
                    foorList.add(floorTree);

                });
                unitsTree.setChildrenVoList(foorList);
                unitList.add(unitsTree);
            });
            buildingTree.setChildrenVoList(unitList);
            //楼层信息信息集合

            List<PropertyBuildingsLevel> propertyBuildingsLevelList = propertyBuildingsLevelServiceService.lambdaQuery().eq(PropertyBuildingsLevel::getBuildingId, building.getId()).list();
            propertyBuildingsLevelList.forEach(level -> {
                PropertyHousesTreeVo floorTree = new PropertyHousesTreeVo();
                floorTree.setId(level.getId());
                floorTree.setName(level.getLevelName());
                floorTree.setType(4);
                floorTree.setParentId(building.getId());

                List<PropertyHousesTreeVo> housesList = new ArrayList<>();
                List<PropertyHouses> propertyHousesList = lambdaQuery().eq(PropertyHouses::getLevelId, level.getId()).list();
                propertyHousesList.forEach(house -> {
                    PropertyHousesTreeVo houseTree = new PropertyHousesTreeVo();
                    houseTree.setId(house.getId());
                    houseTree.setName(house.getHouseName());
                    houseTree.setType(5);
                    houseTree.setParentId(level.getId());
                    housesList.add(houseTree);
                });
                floorTree.setChildrenVoList(housesList);
                buildingTree.getChildrenVoList().add(floorTree);

            });
            buildingList.add(buildingTree);
        });
        //楼栋信息
        result.setChildrenVoList(buildingList);
        return result;
    }


    public String generateOrderNumber() {
        StringBuffer value = new StringBuffer();
        value.append(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));
        Random random = new Random();
        int[] intStream = random.ints(10, 0, 8).toArray();
        for (int i : intStream) {
            value.append(i);
        }
        return value.toString();
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean  autoDeduction(PropertyHousesAutoDeductionDto param){
        LambdaQueryWrapper<PropertyHouses> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(PropertyHouses::getId,param.getHousesList());
        List<PropertyHouses> list = list(queryWrapper);
        if(Func.isEmpty(list)||list.size()!=param.getHousesList().size()){
            throw new ServiceException("所选数据不存在请重新刷新!");
        }
        if(param.getIsAutoDeduction()==1){
            if(Func.isEmpty(param.getAutoDeductionType())){
                throw new ServiceException("自动扣款方式参数错误!");
            }
            ContextUser user = AuthUtil.getUser();
            for (PropertyHouses item:list) {
                if(item.getIsAutoDeduction().equals(param.getIsAutoDeduction())){
                    throw new ServiceException(String.format("房%s已经开通过自动扣款,请重新刷新",item.getHouseName()));
                }
                item.setIsAutoDeduction(param.getIsAutoDeduction());
                item.setAutoDeductionType(param.getAutoDeductionType());
                item.setAutoDeductionSourceType(param.getAutoDeductionSourceType());
                if(Func.isNotEmpty(user)){
                    if(param.getAutoDeductionSourceType()==1){
                        PropertyUserHouse userHouse = iPropertyUserHouseService.getByUserDetailIdAndHouseId(user.getUserDetailId(), item.getId());
                        if(Func.isEmpty(userHouse)){
                            throw new ServiceException(String.format("房源%s已解除关联请重新刷新数据!",item.getHouseName()));
                        }
                        item.setAutoDeductionUserId(user.getUserId());
                    }

                    if(param.getAutoDeductionSourceType()==2){
                        PropertyEnterpriseAddress enterpriseAddress = iPropertyEnterpriseAddressService.getByDeptAndHouseId(Func.toLong(user.getDeptId()), item.getId());
                        if(Func.isEmpty(enterpriseAddress)){
                            throw new ServiceException(String.format("房源%s已解除关联请重新刷新数据!",item.getHouseName()));
                        }

                        item.setAutoDeductionDeptId(Func.toLong(user.getDeptId()));
                    }
                }
            }
        }
        if(param.getIsAutoDeduction()==0){
            for (PropertyHouses item:list) {
                item.setIsAutoDeduction(param.getIsAutoDeduction());
                item.setAutoDeductionSourceType(null);
                item.setAutoDeductionType(null);
                item.setAutoDeductionUserId(null);
                item.setAutoDeductionDeptId(null);
            }
        }
        return updateBatchById(list);
    }

    /**
     * 解绑后把自动扣款的设置恢复成不自动扣款
     * @param houseId
     * @param autoDeductionSourceType
     * @param userId
     * @param deptId
     */
    public void initIsAutoDeduction(Long houseId,Integer autoDeductionSourceType,Long userId,Long deptId){
        LambdaQueryWrapper<PropertyHouses> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PropertyHouses::getId,houseId)
                .eq(PropertyHouses::getIsAutoDeduction,1)
                .eq(PropertyHouses::getAutoDeductionSourceType,autoDeductionSourceType);
        if(autoDeductionSourceType==1){
            queryWrapper.eq(PropertyHouses::getAutoDeductionUserId,userId);
        }else if(autoDeductionSourceType==2){
            queryWrapper.eq(PropertyHouses::getAutoDeductionDeptId,deptId);
        }
        queryWrapper.last("limit 1");
        PropertyHouses houses=getOne(queryWrapper);
        houses.setIsAutoDeduction(0);
        houses.setAutoDeductionSourceType(null);
        houses.setAutoDeductionType(null);
        houses.setAutoDeductionUserId(null);
        houses.setAutoDeductionDeptId(null);
        updateById(houses);
    }

    public Page<PropertyHousesBindingVo> listByBinding(PropertyHousesBindingQueryDto param){
        // 分页获取数据
        Page<PropertyHouses> page = new Page<>(param.getCurrent(), param.getSize());
        ContextUser user = AuthUtil.getUser();
        if(Func.isEmpty(user)){
            throw new ServiceException("请先登录");
        }
        if(param.getBindingType()==1){
            page = baseMapper.listByBindingUser(page, user.getUserDetailId(), param.getIsAutoDeduction());
        }
        if(param.getBindingType()==2){
            page = baseMapper.listByBindingEnterprise(page, Func.toLong(user.getDeptId()), param.getIsAutoDeduction());
        }
        Page<PropertyHousesBindingVo> result=new Page();
        Func.copy(page,result);
        if(Func.isEmpty(page.getRecords())){
            return result;
        }
        result.setRecords(page.getRecords().stream().map(a->{
            PropertyHousesBindingVo vo=Func.copy(a,PropertyHousesBindingVo.class);
            PmgBatParkInfo parkInfo = parkInfoService.getById(a.getParkId());
            if(Func.isNotEmpty(parkInfo)){
                vo.setParkName(parkInfo.getParkName());
            }
            PropertyBuildings buildings = propertyBuildingsService.getById(a.getBuildingId());
            if(Func.isNotEmpty(buildings)){
                vo.setBuildingName(buildings.getBuildingName());
            }
            return vo;
        }).collect(Collectors.toList()));
        return result;
    }

    public List<PropertyHouses> getRoomsByBuildingAndLevelId(Long buildingId, Long levelId) {

        LambdaQueryWrapper<PropertyHouses> qw = new LambdaQueryWrapper<>();
        qw.eq(PropertyHouses::getBuildingId, buildingId);
        qw.eq(PropertyHouses::getLevelId, levelId);
        List<PropertyHouses> propertyHousesList = baseMapper.selectList(qw);

        return propertyHousesList;
    }



}
