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

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.TmUsedEstateDao;
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.param.house.QueryHouseParam;
import fcb.project.manager.base.param.usedEstate.QueryUsedEstate;
import fcb.project.manager.base.service.ITmUsedEstateService;
import fcb.project.manager.base.vo.house.HouseVO;
import fdage.back.sdk.base.enums.ResultCodeEnum;
import fdage.back.sdk.base.exception.CommonBaseException;
import fdage.back.sdk.base.uuid.SnowFlakeUUidUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author by su
 * @since 2021-01-07
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class TmUsedEstateServiceImpl extends ServiceImpl<TmUsedEstateDao, TmUsedEstate> implements ITmUsedEstateService {

    private final TmOperationServiceImpl tmOperationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addProject(TmUsedEstate tmUsedEstate , ContextTokenBean tokenMap) {
        TmUsedEstate dbEstate = getOneByNameAndBelong(tmUsedEstate.getGardenName(), tokenMap.getDepartmentName());
        if (null != dbEstate) {
            log.info("{}公司下面的楼盘{}已经存在", tmUsedEstate.getBelongCompanyName(), tmUsedEstate.getGardenName());
            throw new CommonBaseException(ResultCodeEnum.D101, "楼盘已经存在，无需再添加");
        }

        if (null != tokenMap) {
            tmUsedEstate.setId(SnowFlakeUUidUtils.generaUUid(null , null , UuidPreEnum.USEESTATE_ID_PRE.getPre()));
            tmUsedEstate.setBelongCompanyId(tokenMap.getDepartmentId());
            tmUsedEstate.setBelongCompanyName(tokenMap.getDepartmentName());
            tmUsedEstate.setCreateById(tokenMap.getId());
            tmUsedEstate.setCreateByName(tokenMap.getNickName());
        }

        if (insertNew(tmUsedEstate)) {
            int ins = tmOperationService.addNewWithTypeAndContent(tokenMap , "VR楼盘项目-二手房小区" , "创建楼盘/" + tmUsedEstate.getGardenName());
            if(ins != 1){
                log.error("插入操作记录失败");
            }
        }
        Map<String , Object> resultMap = new HashMap<>(1);
        resultMap.put("usedEstateId" , tmUsedEstate.getId());
        return resultMap;
    }

    @Override
    public IPage<TmUsedEstate> listProject(QueryUsedEstate queryUsedEstate, ContextTokenBean contextUserInfo, String token) {
        produceQuery(queryUsedEstate, contextUserInfo);

        LambdaQueryWrapper<TmUsedEstate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.equals(contextUserInfo.getRoleKey(), SysUserRoleEnums.ADMIN.getRoleKey())
                && !StringUtils.equals(contextUserInfo.getRoleKey(), SysUserRoleEnums.GROUP.getRoleKey())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getBelongCompanyId,queryUsedEstate.getDepartmentId());
        }

        if (queryUsedEstate.getStatues() != null && HouseStatus.REJECT.getCode().equals(queryUsedEstate.getStatues())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getStatus,queryUsedEstate.getStatues());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getNumber())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getNumber,queryUsedEstate.getNumber());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getGardenName())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getGardenName,queryUsedEstate.getGardenName());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getCityName())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getCityName,queryUsedEstate.getCityName());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getAreaName())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getAreaName,queryUsedEstate.getAreaName());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getPropertyTypeName())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getPropertyTypeName,queryUsedEstate.getPropertyTypeName());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getBuildYear())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getBuildYear,queryUsedEstate.getBuildYear());
        }

        if (StringUtils.isNotEmpty(queryUsedEstate.getUpdateByName())) {
            lambdaQueryWrapper.eq(TmUsedEstate::getBuildYear,queryUsedEstate.getBuildYear());
        }

        if (queryUsedEstate.getAuditTimeStartTime()!=null && queryUsedEstate.getAuditTimeEndTime()!=null) {
            lambdaQueryWrapper.between(TmUsedEstate::getAuditTime,queryUsedEstate.getAuditTimeStartTime(),queryUsedEstate.getAuditTimeEndTime());
        }

        Page<TmUsedEstate> page = new Page().setCurrent(queryUsedEstate.getPageNum()).setSize(queryUsedEstate.getPageSize());
        IPage<TmUsedEstate> vos = getBaseMapper().selectPage(page, lambdaQueryWrapper);
        return vos;
    }

    @Override
    public int online(TmUsedEstate tmUsedEstate) {
        return  getBaseMapper().updateById(tmUsedEstate);
    }

    private void produceQuery(QueryUsedEstate queryUsedEstate, ContextTokenBean contextUserInfo) {
        if (!StringUtils.equals(contextUserInfo.getRoleKey(), SysUserRoleEnums.ADMIN.getRoleKey())
                && !StringUtils.equals(contextUserInfo.getRoleKey(), SysUserRoleEnums.GROUP.getRoleKey())) {
            queryUsedEstate.setDepartmentId(contextUserInfo.getDepartmentId());
        }

    }


    public TmUsedEstate getOneByNameAndBelong(String estateName , String belongCompany){
        LambdaQueryWrapper<TmUsedEstate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(estateName)){
            lambdaQueryWrapper.eq(TmUsedEstate::getBelongCompanyName , belongCompany);
        }
        if(StringUtils.isNotBlank(estateName)){
            lambdaQueryWrapper.eq(TmUsedEstate::getGardenName , estateName);
        }
        lambdaQueryWrapper.eq(TmUsedEstate::getIsDelete , DeleteStatus.NOT_DELETE.getCode());
        lambdaQueryWrapper.last("limit 1");
        return getBaseMapper().selectOne(lambdaQueryWrapper);
    }

    public boolean insertNew(TmUsedEstate estate){
        if(StringUtils.isBlank(estate.getId())){
            estate.setId(SnowFlakeUUidUtils.generaUUid(null , null ,  "EST00001"));
        }
        estate.setCreateTime(LocalDateTime.now());
        estate.setUpdateTime(LocalDateTime.now());
        estate.setIsDelete(DeleteStatus.NOT_DELETE.getCode());
        return 1 == getBaseMapper().insert(estate);
    }
}
