package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONObject;
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.common.CommConstant;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.TaHousingResourcesMapper;
import com.huiju.estateagents.mapper.TaPosterMapper;
import com.huiju.estateagents.mapper.TaSalesBatchMapper;
import com.huiju.estateagents.service.ITaBuildingRoomService;
import com.huiju.estateagents.service.ITaBuildingService;
import com.huiju.estateagents.service.ITaHousingResourcesService;
import com.huiju.estateagents.service.ITaSalesBatchService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 销售批次表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-02-10
 */
@Service
public class TaSalesBatchServiceImpl extends ServiceImpl<TaSalesBatchMapper, TaSalesBatch> implements ITaSalesBatchService {

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

    @Autowired
    private TaSalesBatchMapper taSalesBatchMapper;

    @Autowired
    TaPosterMapper taPosterMapper;

    @Autowired
    private ShareContentServiceImpl shareContentService;

    @Autowired
    private TdPosterTemplateServiceImpl tdPosterTemplateService;

    @Autowired
    private TaPosterServiceImpl taPosterService;

    @Autowired
    private TaHousingResourcesMapper taHousingResourcesMapper;

    @Autowired
    private ITaHousingResourcesService taHousingResourcesService;

    @Autowired
    private ITaBuildingRoomService taBuildingRoomService;

    @Autowired
    private ITaBuildingService taBuildingService;

    @Autowired
    private TaRaiseServiceImpl taRaiseService;

    @Override
    public IPage<TaSalesBatch> selectByCondition(IPage<TaSalesBatch> page, String salesBatchName, String buildingId, Integer status, Integer orgId, List<TaPersonBuilding> taPersonBuildingListByUserId) {
        return taSalesBatchMapper.selectByCondition(page, salesBatchName, buildingId, status, orgId, taPersonBuildingListByUserId);
    }

    @Override
    public ResponseBean delSalesBatchList(Integer orgId, List<TaSalesBatch> taSalesBatchList) {
        ResponseBean responseBean = new ResponseBean();
        Integer count = taSalesBatchMapper.countPreSelectRecord(orgId, taSalesBatchList);
        if (count > 0) {
            responseBean.addError("已有用户预选，请先删除预选记录。");
            return responseBean;
        }
        //无预选状态下删除销售批次的同时删除房源信息
        List<TaHousingResources> housingList = taHousingResourcesMapper.selectHousingList(orgId, taSalesBatchList);
        List<TaBuildingRoom> taBuildingRoomList = new ArrayList<>();
        housingList.forEach(e -> {
            e.setStatus(CommConstant.STATUS_DELETE);
            TaBuildingRoom taBuildingRoom = new TaBuildingRoom();
            taBuildingRoom.setRoomId(e.getRoomId());
            taBuildingRoom.setStatus(CommConstant.STATUS_DELETE);
            taBuildingRoomList.add(taBuildingRoom);
        });

        //房源改为无效
        if (CollectionUtils.isNotEmpty(housingList)) {
            taHousingResourcesService.updateBatchById(housingList);
        }

        if (CollectionUtils.isNotEmpty(taBuildingRoomList)) {
            taBuildingRoomService.updateBatchById(taBuildingRoomList);
        }

        //删除销售批次
        taSalesBatchMapper.updateSalesBatchStatus(orgId, taSalesBatchList);
        return responseBean;
    }

    /**
     * 获取通知信息
     *
     * @param salesBatchId 销售批次ID
     * @return
     */
    @Override
    public ResponseBean getNoticeInfo(Integer salesBatchId) {
        logger.info("getNoticeInfo 接收参数：saleBatchId：{}", salesBatchId);

        ResponseBean responseBean = new ResponseBean();

        TaSalesBatch salesBatch = getById(salesBatchId);
        if (salesBatch == null) {
            responseBean.addError("未查询到数据");
            return responseBean;
        }

        Long totalHouses = null;
        BigDecimal totalRealHeat = null;
        BigDecimal totalHeat = null;
        BigDecimal raiseRealNumber = null;
        BigDecimal raiseNumber = null;

        // 获取房源预选数量
        Map<String, Object> result = taSalesBatchMapper.getTotalHousesAndHeat(salesBatchId);
        if (result != null) {
            totalHouses = (Long) result.get("totalHouses");
            totalRealHeat = (BigDecimal) result.get("totalRealHeat");
            totalHeat = (BigDecimal) result.get("totalHeat");
            raiseRealNumber = (BigDecimal) result.get("totalRaiseRealHeat");
            raiseNumber = (BigDecimal) result.get("totalRaiseHeat");
        }

        // 获取认筹信息
        QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
        taRaiseQueryWrapper.eq("sales_batch_id", salesBatch.getSalesBatchId());
        taRaiseQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TaRaise taRaise = taRaiseService.getOne(taRaiseQueryWrapper);

        JSONObject obj = new JSONObject();
        obj.put("preselectionStartTime", salesBatch.getPreselectionStartTime());
        obj.put("preselectionEndTime", salesBatch.getPreselectionEndTime());
        obj.put("raiseRealNumber", raiseRealNumber == null ? 0 : raiseRealNumber);
        obj.put("raiseNumber", raiseNumber == null ? 0 : raiseNumber);
        if(taRaise != null){
            obj.put("raiseStartTime", taRaise.getRaiseStartTime());
            obj.put("raiseEndTime", taRaise.getRaiseEndTime());
        }else{
            obj.put("raiseStartTime", "");
            obj.put("raiseEndTime", "");
        }
        obj.put("salesNumber", totalHouses == null ? 0 : totalHouses);
        obj.put("preselectionNumber", totalRealHeat == null ? 0 : totalRealHeat);
        obj.put("heatNumber", totalHeat == null ? 0 : totalHeat);

        responseBean.addSuccess(obj);
        return responseBean;
    }

    /**
     * 获取销售批次详情
     *
     * @param salesBatchId
     * @return
     */
    @Override
    public ResponseBean getSalesBatchById(Integer salesBatchId) {
        logger.info("getSalesBatchById 接收参数：saleBatchId：{}", salesBatchId);

        ResponseBean responseBean = new ResponseBean();
        TaSalesBatch result = getById(salesBatchId);
        if (result == null) {
            responseBean.addSuccess(null);
            return responseBean;
        }

        // 获取楼盘名称
        TaBuilding taBuilding = taBuildingService.getById(result.getBuildingId());
        if (taBuilding != null) {
            result.setBuildingName(taBuilding.getBuildingName());
        }

        // 获取海报信息
        QueryWrapper<TaPoster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("target_id", salesBatchId + "");
        queryWrapper.eq("target_type", "house");
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        List<TaPoster> posterList = taPosterService.list(queryWrapper);

        // 获取分享内容信息
        List<TaShareContent> shareContentList = shareContentService.getPostersForTarget(salesBatchId + "", "house");

        List<TaPoster> resultPosterList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(posterList)) {
            for (TaPoster poster : posterList) {
                QueryWrapper<TdPosterTemplate> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.eq("status", "1");
                templateQueryWrapper.eq("type ", "HousingChoice ");
                List<TdPosterTemplate> posterTemplate = tdPosterTemplateService.list(templateQueryWrapper);

                poster.setTemplates(posterTemplate);
                resultPosterList.add(poster);
            }
        }

        result.setPosters(resultPosterList);
        result.setShareContents(shareContentList);
        responseBean.addSuccess(result);
        return responseBean;
    }

    @Override
    public ResponseBean getBuildingById(String salesBatchId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.addSuccess(taSalesBatchMapper.getBuildingById(salesBatchId, orgId));
        return responseBean;
    }
}
