package fcb.project.manager.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fcb.project.manager.base.dao.TmHouseDao;
import fcb.project.manager.base.entity.*;
import fcb.project.manager.base.enums.DeleteStatus;
import fcb.project.manager.base.enums.HouseStatus;
import fcb.project.manager.base.enums.SysUserRoleEnums;
import fcb.project.manager.base.enums.UuidPreEnum;
import fcb.project.manager.base.service.ITmHouseService;
import fcb.project.manager.base.service.custom.PanoService;
import fcb.project.manager.core.feignInterfaces.SceneFeign;
import fcb.project.manager.core.feignInterfaces.UserFeign;
import fdage.back.sdk.base.enums.ResultCodeEnum;
import fdage.back.sdk.base.exception.CommonBaseException;
import fdage.back.sdk.base.uuid.SnowFlakeUUidUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author abner
 * @since 2021-01-07
 */
@Service
@Log4j2
public class TmHouseServiceImpl extends ServiceImpl<TmHouseDao, TmHouse> implements ITmHouseService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private PanoService panoService;

    @Autowired
    private SceneFeign sceneFeign;

    @Autowired
    private TmEstateServiceImpl tmEstateService;

    @Autowired
    private TmAuditServiceImpl tmAuditService;

    @Value("${inner.vr.scene.host}")
    private String innerSceneVrHost;

    @Value("${outer.vr.scene.host}")
    private String outerSceneVrHost;




    public List<TmHouse> getListByEstate(String estateId){
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TmHouse::getEstateId, estateId);
        lambdaQueryWrapper.eq(TmHouse::getIsDelete, 0);
        return getBaseMapper().selectList(lambdaQueryWrapper);
    }


    public IPage<TmHouse> getAuditHouseList(String houseTitle, Integer status, Integer type,
                                            String belongCompany, String estateName, String token,
                                            String startTime, String endTime,
                                            Long pageNum, Long pageSize, ContextTokenBean tokenMap) {
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TmHouse::getIsShow, 1);
        if (StringUtils.isNotBlank(houseTitle)) {
            lambdaQueryWrapper.like(TmHouse::getHouseTitle, houseTitle);
        }
        lambdaQueryWrapper.orderByDesc(TmHouse::getSubmitAuditTime);
        if (null != status) {
            if (HouseStatus.ALL.getCode().compareTo(status) != 0) {
                //当获取的是未通过的数据时，获取所有<=-1的数据
                if(HouseStatus.REJECT.getCode().compareTo(status) == 0){
                    lambdaQueryWrapper.le(TmHouse::getStatus, status);
                }else {
                    //其余根据状态获取
                    lambdaQueryWrapper.eq(TmHouse::getStatus, status);
                }
            } else {
                lambdaQueryWrapper.ne(TmHouse::getStatus, HouseStatus.DRAFT.getCode());
            }
            //捞取所有状态，默认不设置status的过滤条件
        } else {
            lambdaQueryWrapper.eq(TmHouse::getStatus, HouseStatus.WAITING_AUDIT.getCode());
        }
        if (StringUtils.isNotBlank(estateName)) {
            lambdaQueryWrapper.like(TmHouse::getEstateName, estateName);
        }

        if("region".equals(tokenMap.getRoleKey())){
            lambdaQueryWrapper.eq(TmHouse::getBelongCompanyId, tokenMap.getDepartmentId());
        }else {
            if (StringUtils.isNotBlank(belongCompany)) {
                lambdaQueryWrapper.eq(TmHouse::getBelongCompanyId, belongCompany);
            }
        }
        if (null != type) {
            lambdaQueryWrapper.eq(TmHouse::getType, type);
        }
        if(StringUtils.isNotBlank(startTime)){
            lambdaQueryWrapper.ge(TmHouse::getSubmitAuditTime, startTime);
        }
        if(StringUtils.isNotBlank(startTime)){
            lambdaQueryWrapper.le(TmHouse::getSubmitAuditTime, endTime);
        }
        IPage<TmHouse> page = new Page<>(pageNum, pageSize, true);
        IPage<TmHouse> resultPage = getBaseMapper().selectPage(page, lambdaQueryWrapper);

        if(null != resultPage && resultPage.getTotal() > 0){
            List<String> getAllHouseIds = new ArrayList<>();
            for (int i = 0; i < resultPage.getRecords().size(); i++) {
                getAllHouseIds.add(resultPage.getRecords().get(i).getId());
            }

            LambdaQueryWrapper<TmAudit> auditLambdaQueryWrapper = new LambdaQueryWrapper<>();
            TmAudit tmAudit = null;
            //从720获取最新的预览路径，重新封装给前端展示
            TreeMap<String , Object> treeMap =  panoService.getHouseVrlinks(getAllHouseIds , token);
            for (int i = 0; i < resultPage.getRecords().size(); i++) {
                String vrId = resultPage.getRecords().get(i).getId();
                resultPage.getRecords().get(i).setCountNum(tmAuditService.countAuditNum(vrId));

                if(!CollectionUtils.isEmpty(treeMap)){
                    String path = (String) treeMap.get(vrId);
                    if(StringUtils.isNotBlank(path)){
                        String outerHost = outerSceneVrHost.substring(0 , outerSceneVrHost.length() - 1);
                        String innerHost = innerSceneVrHost.substring(0 , innerSceneVrHost.length() - 1);
                        resultPage.getRecords().get(i).setInnerVrLink(innerHost + path);
                        resultPage.getRecords().get(i).setVrLink(outerHost + path);
                    }
                }

//                //查出所有审核详细状态
//                auditLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                auditLambdaQueryWrapper.eq(TmAudit::getId, resultPage.getRecords().get(i).getAuditId());
//                auditLambdaQueryWrapper.eq(TmAudit::getIsDelete, DeleteStatus.NOT_DELETE.getCode());
//                auditLambdaQueryWrapper.last("limit 1");
//                tmAudit = tmAuditService.getBaseMapper().selectOne(auditLambdaQueryWrapper);
//                if(tmAudit != null){
//                    resultPage.getRecords().get(i).setAuditStatus(tmAudit.getAuditStatus());
//                }
            }
        }
        return resultPage;
    }

    public List<TmHouse> getAuditHouseListAll(String houseTitle, Integer status, Integer type,
                                            String belongCompany, String estateName,
                                            String startTime, String endTime, ContextTokenBean tokenMap) {
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TmHouse::getIsShow, 1);
        if (StringUtils.isNotBlank(houseTitle)) {
            lambdaQueryWrapper.like(TmHouse::getHouseTitle, houseTitle);
        }
        lambdaQueryWrapper.orderByDesc(TmHouse::getSubmitAuditTime);
        if (null != status) {
            if (HouseStatus.ALL.getCode().compareTo(status) != 0) {
                //当获取的是未通过的数据时，获取所有<=-1的数据
                if(HouseStatus.REJECT.getCode().compareTo(status) == 0){
                    lambdaQueryWrapper.le(TmHouse::getStatus, status);
                }else {
                    //其余根据状态获取
                    lambdaQueryWrapper.eq(TmHouse::getStatus, status);
                }
            } else {
                lambdaQueryWrapper.ne(TmHouse::getStatus, HouseStatus.DRAFT.getCode());
            }
            //捞取所有状态，默认不设置status的过滤条件
        } else {
            lambdaQueryWrapper.eq(TmHouse::getStatus, HouseStatus.WAITING_AUDIT.getCode());
        }
        if (StringUtils.isNotBlank(estateName)) {
            lambdaQueryWrapper.like(TmHouse::getEstateName, estateName);
        }
        if("region".equals(tokenMap.getRoleKey())){
            lambdaQueryWrapper.eq(TmHouse::getBelongCompanyId, tokenMap.getDepartmentId());
        }else {
            if (StringUtils.isNotBlank(belongCompany)) {
                lambdaQueryWrapper.eq(TmHouse::getBelongCompanyId, belongCompany);
            }
        }
        if (null != type) {
            lambdaQueryWrapper.eq(TmHouse::getType, type);
        }
        if(StringUtils.isNotBlank(startTime)){
            lambdaQueryWrapper.ge(TmHouse::getSubmitAuditTime, startTime);
        }
        if(StringUtils.isNotBlank(startTime)){
            lambdaQueryWrapper.le(TmHouse::getSubmitAuditTime, endTime);
        }
        List<TmHouse> tmHouseList = getBaseMapper().selectList(lambdaQueryWrapper);

        return tmHouseList;
    }

    @Transactional(rollbackFor = Exception.class)
    public int deleteHouseById(String houseId) {
        if (StringUtils.isBlank(houseId)) {
            return -1;
        }
        return getBaseMapper().deleteById(houseId);
    }


    public TmHouse getOneByNameAndEstate(String houseTitle, String estateId, int type) {
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(houseTitle)) {
            lambdaQueryWrapper.eq(TmHouse::getHouseTitle, houseTitle);
        }
        if (StringUtils.isNotBlank(estateId)) {
            lambdaQueryWrapper.eq(TmHouse::getEstateId, estateId);
        }
        lambdaQueryWrapper.eq(TmHouse::getType, type);
        lambdaQueryWrapper.eq(TmHouse::getIsDelete, DeleteStatus.NOT_DELETE.getCode());
        lambdaQueryWrapper.last("limit 1");
        return getBaseMapper().selectOne(lambdaQueryWrapper);
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean updateHouse(TmHouse tmHouse) {
        if (null == tmHouse) {
            return false;
        }
        if (null == tmHouse.getId()) {
            log.info("主键ID为空，无法更房源信息");
            return false;
        }
        tmHouse.setUpdateTime(LocalDateTime.now());
        return 1 == getBaseMapper().updateById(tmHouse);
    }

    public TmHouse selectForUpdate(String id) {
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TmHouse::getId, id);
        lambdaQueryWrapper.last("for update");
        return getBaseMapper().selectOne(lambdaQueryWrapper);
    }


    public boolean insertNew(TmHouse tmHouse) {
        if (StringUtils.isBlank(tmHouse.getId())) {
            tmHouse.setId(SnowFlakeUUidUtils.generaUUid(null, null, UuidPreEnum.HOUSE_ID_PRE.getPre()));
        }
        tmHouse.setCreateTime(LocalDateTime.now());
        tmHouse.setUpdateTime(LocalDateTime.now());
        tmHouse.setIsDelete(DeleteStatus.NOT_DELETE.getCode());
        return 1 == getBaseMapper().insert(tmHouse);
    }


    public TmHouse insertNewWithRsp(TmHouse tmHouse) {
        if (StringUtils.isBlank(tmHouse.getId())) {
            tmHouse.setId(SnowFlakeUUidUtils.generaUUid(null, null, UuidPreEnum.HOUSE_ID_PRE.getPre()));
        }
        tmHouse.setCreateTime(LocalDateTime.now());
        tmHouse.setUpdateTime(LocalDateTime.now());
        tmHouse.setIsDelete(DeleteStatus.NOT_DELETE.getCode());
        getBaseMapper().insert(tmHouse);
        return tmHouse;
    }

    public TmHouse getBySceneNumAndHouseId(String sceneNum, String projectId, String houseId) {
        if (!StringUtils.isNoneBlank(sceneNum, projectId, houseId)) {
            return null;
        }
        LambdaQueryWrapper<TmHouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TmHouse::getSceneNum, sceneNum);
        lambdaQueryWrapper.eq(TmHouse::getEstateId, projectId);
        lambdaQueryWrapper.eq(TmHouse::getFcbHouseId, houseId);
        return getBaseMapper().selectOne(lambdaQueryWrapper);
    }

}
