package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.service.impl.TaUserServiceImpl;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.po.BuildingImgPO;
import com.huiju.estateagents.po.TaHousingResourcesPO;
import com.huiju.estateagents.service.ITaHousingResourcesService;
import com.huiju.estateagents.service.ITaRaiseInviteService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 房源表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-02-10
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class TaHousingResourcesServiceImpl extends ServiceImpl<TaHousingResourcesMapper, TaHousingResources> implements ITaHousingResourcesService {

    private Logger logger = LoggerFactory.getLogger(TaHousingResourcesServiceImpl.class);

    @Autowired
    private TaHousingResourcesMapper taHousingResourcesMapper;

    @Autowired
    private TaBuildingTermMapper taBuildingTermMapper;

    @Autowired
    private TaBuildingBlockMapper taBuildingBlockMapper;

    @Autowired
    private TaBuildingUnitMapper taBuildingUnitMapper;

    @Autowired
    private TaBuildingFloorMapper taBuildingFloorMapper;

    @Autowired
    private TaBuildingRoomMapper taBuildingRoomMapper;

    @Autowired
    private TaBuildingMapper taBuildingMapper;

    @Autowired
    private TaPreselectionRecordMapper taPreselectionRecordMapper;

    @Autowired
    TaBuildingImgMapper taBuildingImgMapper;

    @Autowired
    TaApartmentImgMapper taApartmentImgMapper;

    @Autowired
    private TaBuildingPanoramaMapper taBuildingPanoramaMapper;

    @Autowired
    private TaSalesBatchMapper taSalesBatchMapper;

    @Autowired
    private TaPersonServiceImpl taPersonService;

    @Autowired
    private TaRaiseHouseServiceImpl taRaiseHouseService;

    @Autowired
    private TaPreselectionMapper taPreselectionMapper;

    @Autowired
    private TaRaiseMapper taRaiseMapper;

    @Autowired
    private TaRaiseRecordMapper taRaiseRecordMapper;

    @Autowired
    private TaUserServiceImpl taUserService;

    @Autowired
    private ITaRaiseInviteService iTaRaiseInviteService;

    /**
     * 分页获取房源列表
     *
     * @param salesBatchId 销售批次ID
     * @param startPrice
     * @param endPrice
     * @param apartmentId
     * @return
     */
    @Override
    public List<TaHousingResourcesPO> listHousingResources(Integer orgId, String salesBatchId, String startPrice, String endPrice, String apartmentId,
                                                           String personId, String source) {
        logger.info("listHousingResources 接收参数：orgId：{},salesBatchId：{},startPrice：{},endPrice：{},apartmentId：{},source:{}",
                orgId, salesBatchId, startPrice, endPrice, apartmentId, source);

        startPrice = StringUtils.isEmpty(startPrice) ? null : startPrice;
        endPrice = StringUtils.isEmpty(endPrice) ? null : endPrice;

        List<TaHousingResourcesPO> resourcesPOList =
                taHousingResourcesMapper.listHousingResources(orgId, salesBatchId, startPrice, endPrice, apartmentId, personId, source);

        return resourcesPOList;
    }

    /**
     * 分页获取房源列表-后台管理端
     *
     * @param salesBatchId 销售批次ID
     * @param startPrice
     * @param endPrice
     * @param apartmentId
     * @param type
     * @return
     */
    @Override
    public List<TaHousingResourcesPO> listHousingResourcesForCms(Integer orgId, String salesBatchId, String startPrice, String endPrice, String apartmentId, Integer type) {
        logger.info("listHousingResourcesForCms 接收参数：orgId：{},salesBatchId：{},startPrice：{},endPrice：{},apartmentId：{}，type：{}",
                orgId, salesBatchId, startPrice, endPrice, apartmentId, type);

        startPrice = StringUtils.isEmpty(startPrice) ? null : startPrice;
        endPrice = StringUtils.isEmpty(endPrice) ? null : endPrice;

        List<TaHousingResourcesPO> resourcesPOList =
                taHousingResourcesMapper.listHousingResourcesForCms(orgId, salesBatchId, startPrice, endPrice, apartmentId, type);

        return resourcesPOList;
    }

    /**
     * 获取某销售批次下所有房源户型
     *
     * @param salesBatchId
     * @return
     */
    @Override
    public List<TaBuildingApartment> listBuildApartmentBySalesBatchId(String salesBatchId) {
        logger.info("listBuildApartmentBySalesBatchId 接收参数：salesBatchId：{}", salesBatchId);

        // 获取户型列表
        List<TaBuildingApartment> apartmentList = taHousingResourcesMapper.listBuildApartmentBySalesBatchId(salesBatchId);
        if (CollectionUtils.isEmpty(apartmentList)) {
            return null;
        }

        // 组装户型图片
        List<TaBuildingApartment> resultList = new ArrayList<>();
        List<TaBuildingImg> taBuildingImgList;
        List<TaApartmentImg> buildingImg;
        QueryWrapper<TaApartmentImg> apartmentImgQueryWrapper;
        QueryWrapper<TaBuildingImg> buildingImgQueryWrapper;
        for (TaBuildingApartment apartment : apartmentList) {
            apartmentImgQueryWrapper = new QueryWrapper<>();
            apartmentImgQueryWrapper.eq("apartment_id", apartment.getApartmentId());
            buildingImg = taApartmentImgMapper.selectList(apartmentImgQueryWrapper);
            for (TaApartmentImg apartmentImg : buildingImg) {
                buildingImgQueryWrapper = new QueryWrapper<>();
                buildingImgQueryWrapper.eq("img_id", apartmentImg.getImgId());
                buildingImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_APARMENT);
                buildingImgQueryWrapper.orderByAsc("order_no");
                taBuildingImgList = taBuildingImgMapper.selectList(buildingImgQueryWrapper);
                apartment.setBuildingImgList(taBuildingImgList);
                resultList.add(apartment);
            }
        }
        return resultList;
    }

    /**
     * 根据房源ID获取房源详情
     *
     * @param personId
     * @param houseId
     * @return
     */
    @Override
    public TaHousingResourcesPO getHousingDetailById(String personId, Integer houseId) throws Exception {
        logger.info("getHousingDetailById 接收参数：personId：{}，houseId：{}", personId, houseId);

        // 查询房源详情
        TaHousingResourcesPO resourcesPO = taHousingResourcesMapper.getHousingDetailById(houseId, "1");
        if (resourcesPO == null) {
            return null;
        }

        // 获取该用户是否预选房源信息
        TaPreselectionRecord taPreselectionRecord = taPreselectionRecordMapper.getRecordByPersonIdAndHouseId(personId, houseId);
        if (taPreselectionRecord != null) {
            resourcesPO.setIsPreselect(true);
        } else {
            resourcesPO.setIsPreselect(false);
        }

        List<BuildingImgPO> buildingImgPOList = new ArrayList<>();
        BuildingImgPO buildingImgPO;
        if (!StringUtils.isEmpty(resourcesPO.getApartmentId())) {
            // 获取全景图
            QueryWrapper<TaBuildingPanorama> buildingPanoramaQueryWrapper = new QueryWrapper<>();
            buildingPanoramaQueryWrapper.eq("org_id", resourcesPO.getOrgId());
            buildingPanoramaQueryWrapper.eq("building_id", resourcesPO.getBuildingId());
            buildingPanoramaQueryWrapper.eq("apartment_id", resourcesPO.getApartmentId());
            buildingPanoramaQueryWrapper.eq("panorama_type", "apartment");
            buildingPanoramaQueryWrapper.eq("status", "1");
            List<TaBuildingPanorama> panoramaList = taBuildingPanoramaMapper.selectList(buildingPanoramaQueryWrapper);
            if (CollectionUtils.isNotEmpty(panoramaList)) {
                for (TaBuildingPanorama panorama : panoramaList) {
                    buildingImgPO = new BuildingImgPO();
                    buildingImgPO.setUrl(panorama.getCoverImg());
                    buildingImgPO.setType(1);
                    buildingImgPO.setPanoramaLink(panorama.getPanoramaLink());
                    buildingImgPOList.add(buildingImgPO);
                }
            }

            // 获取户型图片列表
            List<TaBuildingImg> taBuildingImgList = new ArrayList<>();
            List<TaApartmentImg> buildingImg;
            QueryWrapper<TaBuildingImg> buildingImgQueryWrapper;
            QueryWrapper<TaApartmentImg> apartmentImgQueryWrapper = new QueryWrapper<>();
            apartmentImgQueryWrapper.eq("apartment_id", resourcesPO.getApartmentId());
            buildingImg = taApartmentImgMapper.selectList(apartmentImgQueryWrapper);
            for (TaApartmentImg apartmentImg : buildingImg) {
                buildingImgQueryWrapper = new QueryWrapper<>();
                buildingImgQueryWrapper.eq("img_id", apartmentImg.getImgId());
                buildingImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_APARMENT);
                buildingImgQueryWrapper.orderByAsc("order_no");
                taBuildingImgList = taBuildingImgMapper.selectList(buildingImgQueryWrapper);
            }
            if (CollectionUtils.isNotEmpty(taBuildingImgList)) {
                for (TaBuildingImg img : taBuildingImgList) {
                    buildingImgPO = new BuildingImgPO();
                    buildingImgPO.setType(0);
                    buildingImgPO.setUrl(img.getUrl());
                    buildingImgPOList.add(buildingImgPO);
                }
            }
        }

        resourcesPO.setBuildingImgList(buildingImgPOList);

        //是否展示预选按钮
        Integer salesBatchId = resourcesPO.getSalesBatchId();
        Integer orgId = resourcesPO.getOrgId();
        resourcesPO.setPreselectionBtn(true);
        resourcesPO.setRaiseBtn(true);
        QueryWrapper<TaPreselection> taPreselectionQueryWrapper = new QueryWrapper<>();
        taPreselectionQueryWrapper.eq("sales_batch_id", salesBatchId);
        taPreselectionQueryWrapper.eq("org_id", orgId);
        taPreselectionQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TaPreselection taPreselection = taPreselectionMapper.selectOne(taPreselectionQueryWrapper);
        if (null == taPreselection) {
            resourcesPO.setPreselectionBtn(false);
        }

        //是否展示认筹按钮
        QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
        taRaiseQueryWrapper.eq("sales_batch_id", salesBatchId);
        taRaiseQueryWrapper.eq("org_id", orgId);
        taRaiseQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TaRaise taRaise = taRaiseMapper.selectOne(taRaiseQueryWrapper);
        if (null == taRaise) {
            resourcesPO.setRaiseBtn(false);
        } else {
            resourcesPO.setTaRaise(taRaise);
        }

        // 查询批次下认筹是否开启邀请制
        TaPerson person = taPersonService.getById(personId);
        if (null != taRaise && CommConstant.STATUS_NORMAL == taRaise.getInvite()) {
            // 若开启邀请制，校验该用户是否在邀请列表中
            QueryWrapper<TaRaiseInvite> taRaiseInviteQueryWrapper = new QueryWrapper<>();
            taRaiseInviteQueryWrapper.eq("org_id", orgId);
            taRaiseInviteQueryWrapper.eq("invite_tel", person.getPhone());
            taRaiseInviteQueryWrapper.eq("sales_batch_id", salesBatchId);
            TaRaiseInvite taRaiseInvite = iTaRaiseInviteService.getOne(taRaiseInviteQueryWrapper);
            if (null == taRaiseInvite) {
                throw new Exception("仅限被邀请用户查看房源");
            }
        }

        return resourcesPO;
    }

    /**
     * 校验楼栋信息存不存在
     *
     * @param taHousingResources
     * @return
     */
    @Override
    public StringBuffer checked(TaHousingResources taHousingResources) {
        StringBuffer result = new StringBuffer();
        //校验期
        String termResult = checckedTerm(taHousingResources);
        result.append(termResult.equals("notExist") ? "期名" + taHousingResources.getTermName() + "不存在,会直接新建。" : termResult);
        //校验栋
        String blockResult = checkedBlock(taHousingResources);
        result.append(blockResult.equals("notExist") ? "楼栋名" + taHousingResources.getBlockName() + "不存在,会直接新建。" : blockResult);
        //校验单元
        String unitResult = checkedUnit(taHousingResources);
        result.append(unitResult.equals("notExist") ? "单元名" + taHousingResources.getUnitName() + "不存在,会直接新建。" : unitResult);
        //校验楼层
        String floorResult = checkedFloor(taHousingResources);
        result.append(floorResult.equals("notExist") ? "楼层名" + taHousingResources.getFloorName() + "不存在,会直接新建。" : floorResult);
        //校验房号
        String roomResult = checkedRoom(taHousingResources);
        result.append(roomResult.equals("notExist") ? "房号" + taHousingResources.getRoomName() + "不存在,会直接新建。" : roomResult);
        return result;
    }

    /**
     * 添加楼栋信息
     *
     * @param taHousingResources
     * @return
     */
    @Override
    public ResponseBean addHouseResources(TaHousingResources taHousingResources) {
        //校验期
        String termResult = checckedTerm(taHousingResources);
        //校验栋
        String blockResult = checkedBlock(taHousingResources);
        //校验单元
        String unitResult = checkedUnit(taHousingResources);
        //校验楼层
        String floorResult = checkedFloor(taHousingResources);
        //校验房号
        String roomResult = checkedRoom(taHousingResources);

        //创建期
        if (!roomResult.equals("notExist")) {
            return ResponseBean.error("房间名" + taHousingResources.getRoomName() + "存在。请修改房间名！", ResponseBean.ERROR_UNAVAILABLE);
        }

        //期不存在就添加
        if (termResult.equals("notExist")) {
            addTerm(taHousingResources);
        }

        //楼栋不存在就添加
        if (blockResult.equals("notExist")) {
            addBlock(taHousingResources);
        }

        //单元不存在就添加
        if (unitResult.equals("notExist")) {
            addUnit(taHousingResources);
        }

        //楼层不存在就添加
        if (floorResult.equals("notExist")) {
            addFloor(taHousingResources);
        }

        //房间号不存在就添加
        if (roomResult.equals("notExist")) {
            addRoom(taHousingResources);
        }

        // 更新销售批次里的房源数
        taSalesBatchMapper.addSalesNumberById(taHousingResources.getSalesBatchId(), taHousingResources.getOrgId());

        // 获取楼盘名称
        TaBuilding taBuilding = taBuildingMapper.selectById(taHousingResources.getBuildingId());
        taHousingResources.setBuildingName(taBuilding.getBuildingName());
        //添加房源信息
        taHousingResources.setCreateDate(LocalDateTime.now());
        taHousingResourcesMapper.insert(taHousingResources);
        return ResponseBean.success(taHousingResources);
    }

    /**
     * 分页获取房源信息
     *
     * @param salesBatchId
     * @param buildingId
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @param termName
     * @param blockName
     * @param unitName
     * @param floorName
     * @param roomName
     * @param apartmentId
     * @param status
     * @param houseId
     * @return
     */
    @Override
    public ResponseBean selectPageList(Integer salesBatchId, String buildingId, Integer pageNumber, Integer pageSize, Integer orgId, String termName, String blockName,
                                       String unitName, String floorName, String roomName, String apartmentId, Integer status, String houseId, String lockingStatus,
                                       String actulStartHot, String actulEndHot) {
        IPage<TaHousingResources> pg = new Page<>(pageNumber, pageSize);
        IPage<TaHousingResources> pageData = taHousingResourcesMapper.getHouseResourceList(pg, salesBatchId, buildingId, orgId, termName, blockName, unitName,
                floorName, roomName, apartmentId, status, houseId, lockingStatus, actulStartHot, actulEndHot);
        return ResponseBean.success(pageData);
    }

    /**
     * 更新房源信息
     *
     * @param taHousingResources
     * @return
     */
    @Override
    public ResponseBean updateHouseResources(TaHousingResources taHousingResources) {
        TaHousingResources oldTaHousingResources = taHousingResourcesMapper.selectById(taHousingResources.getHouseId());
        taHousingResources.setTermId(oldTaHousingResources.getTermId());
        taHousingResources.setBlockId(oldTaHousingResources.getBlockId());
        taHousingResources.setUnitId(oldTaHousingResources.getUnitId());
        taHousingResources.setFloorId(oldTaHousingResources.getFloorId());
        taHousingResources.setRoomId(oldTaHousingResources.getRoomId());
        //只允许编辑房间名
        if (!oldTaHousingResources.getRoomName().equals(taHousingResources.getRoomName())) {
            //校验房号
            String roomResult = checkedRoom(taHousingResources);

            //房间号不存在就更新
            if (roomResult.equals("notExist")) {
                updateRoom(taHousingResources);
            } else {
                return ResponseBean.error("房间名" + taHousingResources.getRoomName() + "存在。请修改房间名！", ResponseBean.ERROR_UNAVAILABLE);
            }

        }

        //添加房源信息
        taHousingResources.setUpdateDate(LocalDateTime.now());
        taHousingResourcesMapper.updateById(taHousingResources);
        return ResponseBean.success(taHousingResources);
    }

    /**
     * 获取表格中的数据
     *
     * @param file
     * @param salesBatchId
     * @param buildingId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean getExcelData(MultipartFile file, Integer salesBatchId, String buildingId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        List<TaHousingResources> list = new ArrayList<>();
        if (file == null) {
            responseBean.addError("对象不能为空");
            return responseBean;
        }
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        Workbook workbook = null;
        try {
            if (originalFilename.endsWith(CommConstant.SUFFIX_2003)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFilename.endsWith(CommConstant.SUFFIX_2007)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (Exception e) {
            logger.info(originalFilename);
            e.printStackTrace();
            responseBean.addError("格式错误");
            return responseBean;
        }
        if (workbook == null) {
            logger.info(originalFilename);
            responseBean.addError("格式错误");
            return responseBean;
        } else {
            List<String> temHousingList = new ArrayList<String>();
            //获取一个sheet也就是一个工作簿
            Sheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            //从第一行开始第一行一般是标题
            for (int j = 3; j <= lastRowNum; j++) {
                Row row = sheet.getRow(j);
                TaHousingResources taHousingResources = new TaHousingResources();
                String termName = row.getCell(0).getStringCellValue().trim();
                String blockName = row.getCell(1).getStringCellValue().trim();
                String unitName = row.getCell(2).getStringCellValue().trim();
                String floorName = row.getCell(3).getStringCellValue().trim();

                String roomName = "";
                try {
                    roomName = row.getCell(4).getStringCellValue().trim();
                } catch (Exception e) {
                    String roomNameString = String.valueOf(row.getCell(4).getNumericCellValue());
                    roomName = roomNameString.substring(0, roomNameString.indexOf("."));
                }

                BigDecimal price;
                try {
                    price = BigDecimal.valueOf(row.getCell(5).getNumericCellValue());
                } catch (Exception e) {
                    price = new BigDecimal(row.getCell(5).getStringCellValue());
                }

//                Integer heat = 0;
//                try {
//                    String heatString = String.valueOf(row.getCell(6).getNumericCellValue());
//                    String split = heatString.substring(0, heatString.indexOf("."));
//                    heat = Integer.valueOf(split);
//                } catch (Exception e) {
//                    String heatString = row.getCell(6).getStringCellValue();
//                    heat = Integer.valueOf(heatString);
//                }


                Integer status = row.getCell(6).getStringCellValue().trim().equals("是") ? 1 : 0;

                int currentRow = j + 1;
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(termName)) {
                    responseBean.addError("第" + currentRow + "行" + "期/区不能为空!");
                    return responseBean;
                }
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(blockName)) {
                    responseBean.addError("第" + currentRow + "行" + "楼栋不能为空!");
                    return responseBean;
                }
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(unitName)) {
                    responseBean.addError("第" + currentRow + "行" + "单元不能为空!");
                    return responseBean;
                }
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(floorName)) {
                    responseBean.addError("第" + currentRow + "行" + "层不能为空!");
                    return responseBean;
                }
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(roomName)) {
                    responseBean.addError("第" + currentRow + "行" + "房号不能为空!");
                    return responseBean;
                }

                String houseInfo = termName + blockName + unitName + floorName + roomName;
                if (temHousingList.contains(houseInfo)) {
                    logger.info("存在重复房源:{}", houseInfo);
                    responseBean.addError("第" + currentRow + "行存在重复房源,请删除重复房源后再次上传文件。");
                    return responseBean;
                }

                QueryWrapper<TaHousingResources> taHousingResourcesQueryWrapper = new QueryWrapper<>();
//                taHousingResourcesQueryWrapper.eq("sales_batch_id",salesBatchId);
                taHousingResourcesQueryWrapper.eq("building_id", buildingId);
                taHousingResourcesQueryWrapper.eq("org_id", orgId);
                taHousingResourcesQueryWrapper.gt("status", CommConstant.STATUS_DELETE);
                taHousingResourcesQueryWrapper.eq("term_name", termName);
                taHousingResourcesQueryWrapper.eq("block_name", blockName);
                taHousingResourcesQueryWrapper.eq("unit_name", unitName);
                taHousingResourcesQueryWrapper.eq("floor_name", floorName);
                taHousingResourcesQueryWrapper.eq("room_name", roomName);
                TaHousingResources oldTaHouseingResources = taHousingResourcesMapper.selectOne(taHousingResourcesQueryWrapper);
                if (null != oldTaHouseingResources) {
                    logger.info("数据库存在重复房源:{}", houseInfo);
                    responseBean.addError("第" + currentRow + "行与系统已录入房源" + oldTaHouseingResources.getHouseId() + "重复，请删除重复房源后再次上传文件。（注意，要检查本楼盘下所有批次的房源）。");
                    return responseBean;
                }

                //把数据塞入temList校验是否有重复的数据
                temHousingList.add(houseInfo);
                //构建数据
                taHousingResources.setTermName(termName);
                taHousingResources.setBlockName(blockName);
                taHousingResources.setUnitName(unitName);
                taHousingResources.setFloorName(floorName);
                taHousingResources.setRoomName(roomName);
                taHousingResources.setPrice(price);
//                taHousingResources.setHeat(heat);
                taHousingResources.setStatus(status);
                list.add(taHousingResources);
            }
        }
        //构建分页
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", list);
        data.put("total", list.size());

        responseBean.addSuccess(data);
        return responseBean;
    }

    /**
     * 保存文件
     *
     * @param file
     * @param salesBatchId
     * @param buildingId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean saveExcelValue(MultipartFile file, Integer salesBatchId, String buildingId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = getExcelData(file, salesBatchId, buildingId, orgId);
        if (responseBean.getCode() != ResponseBean.CODE_SUCCESS) {
            return responseBean;
        }

        //获取校验成功的数据
        Map<String, Object> data = (Map<String, Object>) responseBean.getData();
        List<TaHousingResources> list = (List<TaHousingResources>) data.get("list");
        list.forEach(e -> {
            e.setOrgId(orgId);
            e.setSalesBatchId(salesBatchId);
            e.setBuildingId(buildingId);
            addHouseResources(e);
        });
        TaSalesBatch taSalesBatch = new TaSalesBatch();
        taSalesBatch.setSalesNumber(list.size());
        taSalesBatch.setSalesBatchId(salesBatchId);
        taSalesBatchMapper.updateById(taSalesBatch);
        return ResponseBean.success(list);
    }

    @Override
    public ResponseBean batchUpdateRaiseHeat(List<TaHousingResources> housingResourcesList, Integer raiseHeat,
                                             Integer salesBatchId, Integer orgId, Integer updateUser) {
        ResponseBean responseBean = new ResponseBean();
        if (taHousingResourcesMapper.batchUpdateRaiseHeat(housingResourcesList, raiseHeat, updateUser, salesBatchId, orgId) > 0) {
            responseBean.addSuccess("success");
        } else {
            responseBean.addError("fail");
        }
        return responseBean;
    }

    @Override
    public ResponseBean batchUpdateHeat(List<TaHousingResources> housingResourcesList, Integer heat, Integer salesBatchId, Integer orgId, Integer updateUser) {
        ResponseBean responseBean = new ResponseBean();
        if (taHousingResourcesMapper.batchUpdateHeat(housingResourcesList, heat, updateUser, salesBatchId, orgId) > 0) {
            responseBean.addSuccess("success");
        } else {
            responseBean.addError("fail");
        }
        return responseBean;
    }

    @Override
    public ResponseBean listHouseByRaiseRecordId(Integer raiseRecordId, Integer orgId, Integer pageNumber, Integer pageSize) {
        logger.info("listHouseByRaiseRecordId 接收参数：raiseRecordId:{},orgId:{},pageNumber:{},pageSize:{}",
                raiseRecordId, orgId, pageNumber, pageSize);

        ResponseBean responseBean = new ResponseBean();
        IPage<TaHousingResourcesPO> pg = new Page<>(pageNumber, pageSize);
        responseBean.addSuccess(taHousingResourcesMapper.listHouseByRaiseRecordId(pg, raiseRecordId, orgId));
        return responseBean;
    }

    @Override
    public ResponseBean updateLockingStatus(Integer houseId, String type, Integer orgId, Integer raiseHouseId, String personId, Integer raiseRecordId, Integer userId) {
        logger.info("updateLockingStatus 接收参数：houseId:{},type:{},orgId:{},raiseHouseId:{},personId:{},userId:{}",
                houseId, type, orgId, raiseHouseId, personId, userId);
        ResponseBean responseBean = new ResponseBean();

        // 获取房源信息
        TaHousingResourcesPO po = taHousingResourcesMapper.getHouseByRaiseHouseId(orgId, raiseHouseId);
        if (po == null) {
            responseBean.addError("未找到该房源");
            return responseBean;
        }

//        QueryWrapper<TaRaiseHouse> taRaiseHouseQueryWrapper = new QueryWrapper<>();
//        taRaiseHouseQueryWrapper.eq("raise_record_id", raiseRecordId);
//        taRaiseHouseQueryWrapper.eq("raise_house_id", raiseHouseId);
//        TaRaiseHouse taRaiseHouse = taRaiseHouseService.getOne(taRaiseHouseQueryWrapper);

        QueryWrapper<TaRaiseRecord> taRaiseRecordQueryWrapper = new QueryWrapper<>();
        taRaiseRecordQueryWrapper.eq("raise_record_id", raiseRecordId);
        TaRaiseRecord raiseRecord = taRaiseRecordMapper.selectOne(taRaiseRecordQueryWrapper);

        TaUser taUser = taUserService.getUserInfoById(userId, orgId);
        // 更新为锁定状态
        if ("locked".equals(type)) {
            // 校验当前房源状态
            if ("locked".equals(po.getHouseLockingStatus())) {
                responseBean.addError("房源已被锁定");
                return responseBean;
            }

            TaHousingResources housingResources = new TaHousingResources();
            housingResources.setHouseId(po.getHouseId());
            housingResources.setHouseLockingStatus("locked");
            housingResources.setHouseLockingPerson(personId);
            housingResources.setUpdateDate(LocalDateTime.now());
            housingResources.setHouseLockingPerson(raiseRecord.getPersonId());
            housingResources.setUpdateUser(userId);
            updateById(housingResources);

            //更新认筹单房源锁定状态
            TaRaiseRecord taRaiseRecord = new TaRaiseRecord();
            taRaiseRecord.setRaiseRecordId(raiseRecordId);
            taRaiseRecord.setHouseLockingStatus("locked");
            if(taUser != null){
                taRaiseRecord.setUpdateUserName(taUser.getUserName());
            }
            taRaiseRecord.setUpdateDate(LocalDateTime.now());
            taRaiseRecordMapper.updateById(taRaiseRecord);

            // 更新关联表状态
//                TaRaiseHouse raiseHouse = new TaRaiseHouse();
//                raiseHouse.setRaiseHouseId(raiseHouseId);
//                raiseHouse.setHouseLockingStatus("locked");
//            taRaiseHouseService.updateById(raiseHouse);
            responseBean.addSuccess(taRaiseRecordMapper.updateById(taRaiseRecord));
            return responseBean;
        }

        // 更新为解锁状态
        if ("unlocked".equals(type)) {
            // 校验当前房源状态
            if ("unlocked".equals(po.getHouseLockingStatus())) {
                responseBean.addError("房源已被解锁");
                return responseBean;
            }

            TaHousingResources housingResources = new TaHousingResources();
            housingResources.setHouseId(po.getHouseId());
            housingResources.setHouseLockingStatus("unlocked");
            housingResources.setHouseLockingPerson("");
            housingResources.setUpdateDate(LocalDateTime.now());
            housingResources.setUpdateUser(userId);
            updateById(housingResources);

            //更新认筹单房源锁定状态
            TaRaiseRecord taRaiseRecord = new TaRaiseRecord();
            taRaiseRecord.setRaiseRecordId(raiseRecordId);
            taRaiseRecord.setHouseLockingStatus("unlocked");
            if(taUser != null){
                taRaiseRecord.setUpdateUserName(taUser.getUserName());
            }
            taRaiseRecord.setUpdateDate(LocalDateTime.now());
            taRaiseRecordMapper.updateById(taRaiseRecord);

            // 更新关联表状态
//                TaRaiseHouse raiseHouse = new TaRaiseHouse();
//                raiseHouse.setRaiseHouseId(raiseHouseId);
////                raiseHouse.setHouseLockingStatus("unlocked");
////                raiseHouse.setPersonId("");
////                raiseHouse.setPersonName("");
//                responseBean.addSuccess(taRaiseHouseService.updateById(raiseHouse));
            return responseBean;
        }
        responseBean.addError("fail");
        return responseBean;
    }

    /**
     * 校验房源的认筹状态
     *
     * @param houseIds
     * @param personId
     * @param orgId
     * @return
     */
    @Override
    public boolean checkRaiseState(String houseIds, String personId, Integer orgId) throws Exception {
        String[] houseIdArr = houseIds.split(",");
        //房源信息
        TaHousingResources taHousingResources = taHousingResourcesMapper.selectById(houseIdArr[0]);
        //通过销售批次信息获取认筹信息
        QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
        taRaiseQueryWrapper.eq("org_id", orgId);
        taRaiseQueryWrapper.eq("sales_batch_id", taHousingResources.getSalesBatchId());
        taRaiseQueryWrapper.eq("building_id", taHousingResources.getBuildingId());
        taRaiseQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TaRaise taRaise = taRaiseMapper.selectOne(taRaiseQueryWrapper);
        if (null == taRaise) {
            throw new Exception("认筹单已经作废");
        }
        //校验房源是否同一批次
        for (String houseId : houseIdArr) {
            TaHousingResources taHousingResourcesChecked = taHousingResourcesMapper.selectById(houseId);
            if (!taHousingResources.getSalesBatchId().equals(taHousingResourcesChecked.getSalesBatchId())) {
                throw new Exception("非同一批次房源");
            }
            if (taHousingResourcesChecked.getStatus() != CommConstant.STATUS_NORMAL) {
                throw new Exception("其中有房源已被取消发布");
            }
            if (taRaise.getHouseLockingType().equals(CommConstant.HOUSE_LOCKING_TYPE_AUTO) && CommConstant.HOUSE_LOCKING_STATUS_LOCKED.equals(taHousingResourcesChecked.getHouseLockingStatus())) {
                throw new Exception("房源已被其他客户锁定");
            }
            if (taRaise.getNeedPreselection()) {
                //查看是否有当前房源的预选记录
                QueryWrapper<TaPreselectionRecord> preselectionRecordQueryWrapper = new QueryWrapper<>();
                preselectionRecordQueryWrapper.eq("sales_batch_id", taRaise.getSalesBatchId());
                preselectionRecordQueryWrapper.eq("org_id", orgId);
                preselectionRecordQueryWrapper.eq("house_id", houseId);
                preselectionRecordQueryWrapper.eq("person_id", personId);
                preselectionRecordQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
                TaPreselectionRecord taPreselectionRecord = taPreselectionRecordMapper.selectOne(preselectionRecordQueryWrapper);
                if (null == taPreselectionRecord) {
                    throw new Exception("需要先预选才能认筹");
                }
            }
            //查询我的认筹记录表
//            QueryWrapper<TaRaiseHouse> taRaiseHouseQueryWrapper = new QueryWrapper<>();
//            taRaiseHouseQueryWrapper.eq("org_id", orgId);
//            taRaiseHouseQueryWrapper.eq("house_id", houseId);
//            taRaiseHouseQueryWrapper.eq("person_id", personId);
//            List<TaRaiseHouse> list = taRaiseHouseService.list(taRaiseHouseQueryWrapper);
//            if (list.size() > 0) {
//                throw new Exception("您已有认筹单包含当前房源");
//            }

        }
        //销售批次信息
        TaSalesBatch taSalesBatch = taSalesBatchMapper.selectById(taHousingResources.getSalesBatchId());
        //销售批次校验
        if (null == taSalesBatch) {
            throw new Exception("无销售批次无法认筹");
        }
        if (taSalesBatch.getStatus() != CommConstant.STATUS_NORMAL) {
            throw new Exception("销售批次已被取消发布");
        }

        //判断是否在时间之内
        LocalDateTime raiseStartTime = taRaise.getRaiseStartTime();
        LocalDateTime raiseEndTime = taRaise.getRaiseEndTime();
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(raiseStartTime) || now.isAfter(raiseEndTime)) {
            throw new Exception("不在认筹时间内");
        }

        return true;
    }

    //更新房号
    private void updateRoom(TaHousingResources taHousingResources) {
        TaBuildingRoom taBuildingRoom = new TaBuildingRoom();
        taBuildingRoom.setUpdateDate(LocalDateTime.now());
        taBuildingRoom.setTermId(taHousingResources.getTermId());
        taBuildingRoom.setBlockId(taHousingResources.getBlockId());
        taBuildingRoom.setUnitId(taHousingResources.getUnitId());
        taBuildingRoom.setFloorId(taHousingResources.getFloorId());
        taBuildingRoom.setRoomName(taHousingResources.getRoomName());
        taBuildingRoom.setRoomId(taHousingResources.getRoomId());
        taBuildingRoomMapper.updateById(taBuildingRoom);
    }

    //更新楼层
    private void updateFloor(TaHousingResources taHousingResources) {
        TaBuildingFloor taBuildingFloor = new TaBuildingFloor();
        taBuildingFloor.setUpdateDate(LocalDateTime.now());
        taBuildingFloor.setTermId(taHousingResources.getTermId());
        taBuildingFloor.setBlockId(taHousingResources.getBlockId());
        taBuildingFloor.setUnitId(taHousingResources.getUnitId());
        taBuildingFloor.setFloorName(taHousingResources.getFloorName());
        taBuildingFloorMapper.updateById(taBuildingFloor);
    }

    //更新单元
    private void updateUnit(TaHousingResources taHousingResources) {
        TaBuildingUnit taBuildingUnit = new TaBuildingUnit();
        taBuildingUnit.setUpdateDate(LocalDateTime.now());
        taBuildingUnit.setTermId(taHousingResources.getTermId());
        taBuildingUnit.setBlockId(taHousingResources.getBlockId());
        taBuildingUnit.setUnitName(taHousingResources.getUnitName());
        taBuildingUnit.setUnitId(taHousingResources.getUnitId());
        taBuildingUnitMapper.updateById(taBuildingUnit);
    }

    //更新栋
    private void updataBlock(TaHousingResources taHousingResources) {
        TaBuildingBlock taBuildingBlock = new TaBuildingBlock();
        taBuildingBlock.setUpdateDate(LocalDateTime.now());
        taBuildingBlock.setTermId(taHousingResources.getTermId());
        taBuildingBlock.setBlockName(taHousingResources.getBlockName());
        taBuildingBlock.setBlockId(taHousingResources.getBlockId());
        taBuildingBlockMapper.updateById(taBuildingBlock);
    }

    //添加房间号
    private void addRoom(TaHousingResources taHousingResources) {
        TaBuildingRoom taBuildingRoom = new TaBuildingRoom();
        taBuildingRoom.setBuildingId(taHousingResources.getBuildingId());
        taBuildingRoom.setCreateDate(LocalDateTime.now());
        taBuildingRoom.setOrgId(taHousingResources.getOrgId());
        taBuildingRoom.setStatus(CommConstant.STATUS_NORMAL);
        taBuildingRoom.setTermId(taHousingResources.getTermId());
        taBuildingRoom.setBlockId(taHousingResources.getBlockId());
        taBuildingRoom.setUnitId(taHousingResources.getUnitId());
        taBuildingRoom.setFloorId(taHousingResources.getFloorId());
        taBuildingRoom.setRoomName(taHousingResources.getRoomName());
        taBuildingRoomMapper.insert(taBuildingRoom);
        taHousingResources.setRoomId(taBuildingRoom.getRoomId());
    }

    //添加楼层
    private void addFloor(TaHousingResources taHousingResources) {
        TaBuildingFloor taBuildingFloor = new TaBuildingFloor();
        taBuildingFloor.setBuildingId(taHousingResources.getBuildingId());
        taBuildingFloor.setCreateDate(LocalDateTime.now());
        taBuildingFloor.setOrgId(taHousingResources.getOrgId());
        taBuildingFloor.setStatus(CommConstant.STATUS_NORMAL);
        taBuildingFloor.setTermId(taHousingResources.getTermId());
        taBuildingFloor.setBlockId(taHousingResources.getBlockId());
        taBuildingFloor.setUnitId(taHousingResources.getUnitId());
        taBuildingFloor.setFloorName(taHousingResources.getFloorName());
        taBuildingFloorMapper.insert(taBuildingFloor);
        taHousingResources.setFloorId(taBuildingFloor.getFloorId());
    }

    //添加单元
    private void addUnit(TaHousingResources taHousingResources) {
        TaBuildingUnit taBuildingUnit = new TaBuildingUnit();
        taBuildingUnit.setBuildingId(taHousingResources.getBuildingId());
        taBuildingUnit.setCreateDate(LocalDateTime.now());
        taBuildingUnit.setOrgId(taHousingResources.getOrgId());
        taBuildingUnit.setStatus(CommConstant.STATUS_NORMAL);
        taBuildingUnit.setTermId(taHousingResources.getTermId());
        taBuildingUnit.setBlockId(taHousingResources.getBlockId());
        taBuildingUnit.setUnitName(taHousingResources.getUnitName());
        taBuildingUnitMapper.insert(taBuildingUnit);
        taHousingResources.setUnitId(taBuildingUnit.getUnitId());
    }

    //添加楼栋
    private void addBlock(TaHousingResources taHousingResources) {
        TaBuildingBlock taBuildingBlock = new TaBuildingBlock();
        taBuildingBlock.setBuildingId(taHousingResources.getBuildingId());
        taBuildingBlock.setCreateDate(LocalDateTime.now());
        taBuildingBlock.setOrgId(taHousingResources.getOrgId());
        taBuildingBlock.setStatus(CommConstant.STATUS_NORMAL);
        taBuildingBlock.setTermId(taHousingResources.getTermId());
        taBuildingBlock.setBlockName(taHousingResources.getBlockName());
        taBuildingBlockMapper.insert(taBuildingBlock);
        taHousingResources.setBlockId(taBuildingBlock.getBlockId());
    }

    //添加期
    private void addTerm(TaHousingResources taHousingResources) {
        TaBuildingTerm taBuildingTerm = new TaBuildingTerm();
        taBuildingTerm.setBuildingId(taHousingResources.getBuildingId());
        taBuildingTerm.setCreateDate(LocalDateTime.now());
        taBuildingTerm.setOrgId(taHousingResources.getOrgId());
        taBuildingTerm.setStatus(CommConstant.STATUS_NORMAL);
        taBuildingTerm.setTermName(taHousingResources.getTermName());
        taBuildingTermMapper.insert(taBuildingTerm);
        taHousingResources.setTermId(taBuildingTerm.getTermId());
    }

    //校验房号
    private String checkedRoom(TaHousingResources taHousingResources) {
        if (StringUtils.isEmpty(taHousingResources.getRoomName())) {
            return "请输入房号。";
        } else {
            //查询房号
            TaBuildingRoom taBuildingRoom = selectRoom(taHousingResources);
            if (null != taBuildingRoom) {
                taHousingResources.setRoomId(taBuildingRoom.getRoomId());
                return "房间名" + taHousingResources.getRoomName() + "存在。不允许保存，请修改！";
            } else {
                return "notExist";
            }
        }
    }

    //查询房间号
    private TaBuildingRoom selectRoom(TaHousingResources taHousingResources) {
        QueryWrapper<TaBuildingRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", taHousingResources.getOrgId());
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        queryWrapper.eq("building_id", taHousingResources.getBuildingId());
        queryWrapper.eq("term_id", taHousingResources.getTermId());
        queryWrapper.eq("block_id", taHousingResources.getBlockId());
        queryWrapper.eq("unit_id", taHousingResources.getUnitId());
        queryWrapper.eq("floor_id", taHousingResources.getFloorId());
        queryWrapper.eq("room_name", taHousingResources.getRoomName());
        return taBuildingRoomMapper.selectOne(queryWrapper);
    }

    //校验楼层
    private String checkedFloor(TaHousingResources taHousingResources) {
        if (StringUtils.isEmpty(taHousingResources.getFloorName())) {
            return "请输入楼层名。";
        } else {
            QueryWrapper<TaBuildingFloor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", taHousingResources.getOrgId());
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.eq("building_id", taHousingResources.getBuildingId());
            queryWrapper.eq("term_id", taHousingResources.getTermId());
            queryWrapper.eq("block_id", taHousingResources.getBlockId());
            queryWrapper.eq("unit_id", taHousingResources.getUnitId());
            queryWrapper.eq("floor_name", taHousingResources.getFloorName());
            TaBuildingFloor taBuildingFloor = taBuildingFloorMapper.selectOne(queryWrapper);
            if (null != taBuildingFloor) {
                taHousingResources.setFloorId(taBuildingFloor.getFloorId());
                return "楼层名" + taHousingResources.getFloorName() + "存在。";
            } else {
                return "notExist";
            }
        }
    }

    //校验单元
    private String checkedUnit(TaHousingResources taHousingResources) {
        if (StringUtils.isEmpty(taHousingResources.getUnitName())) {
            return "请输入单元名。";
        } else {
            QueryWrapper<TaBuildingUnit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", taHousingResources.getOrgId());
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.eq("building_id", taHousingResources.getBuildingId());
            queryWrapper.eq("term_id", taHousingResources.getTermId());
            queryWrapper.eq("block_id", taHousingResources.getBlockId());
            queryWrapper.eq("unit_name", taHousingResources.getUnitName());
            TaBuildingUnit taBuildingUnit = taBuildingUnitMapper.selectOne(queryWrapper);
            if (null != taBuildingUnit) {
                taHousingResources.setUnitId(taBuildingUnit.getUnitId());
                return "单元名" + taHousingResources.getUnitName() + "存在。";
            } else {
                return "notExist";
            }
        }
    }

    //校验楼盘
    private String checkedBlock(TaHousingResources taHousingResources) {
        if (StringUtils.isEmpty(taHousingResources.getBlockName())) {
            return "请输入楼栋名。";
        } else {
            QueryWrapper<TaBuildingBlock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", taHousingResources.getOrgId());
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.eq("building_id", taHousingResources.getBuildingId());
            queryWrapper.eq("term_id", taHousingResources.getTermId());
            queryWrapper.eq("block_name", taHousingResources.getBlockName());
            TaBuildingBlock taBuildingBlock = taBuildingBlockMapper.selectOne(queryWrapper);
            if (null != taBuildingBlock) {
                taHousingResources.setBlockId(taBuildingBlock.getBlockId());
                return "楼栋名" + taHousingResources.getBlockName() + "存在。";
            } else {
                return "notExist";
            }
        }
    }

    //校验期
    private String checckedTerm(TaHousingResources taHousingResources) {
        if (StringUtils.isEmpty(taHousingResources.getTermName())) {
            return "请输入期名。";
        } else {
            QueryWrapper<TaBuildingTerm> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", taHousingResources.getOrgId());
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.eq("building_id", taHousingResources.getBuildingId());
            queryWrapper.eq("term_name", taHousingResources.getTermName());
            TaBuildingTerm taBuildingTerm = taBuildingTermMapper.selectOne(queryWrapper);
            if (null != taBuildingTerm) {
                taHousingResources.setTermId(taBuildingTerm.getTermId());
                return "期名" + taHousingResources.getTermName() + "存在。";
            } else {
                return "notExist";
            }
        }
    }
}
