package com.community.huiju.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.huiju.common.base.ResponseBean;
import com.community.huiju.dao.*;
import com.community.huiju.enums.ResponseErrorsMessages;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.ITaUserVerifyService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * app端用户审核表，存放用户的角色还有房产信息 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-16
 */
@Service
public class TaUserVerifyServiceImpl extends ServiceImpl<TaUserVerifyMapper, TaUserVerify> implements ITaUserVerifyService {

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private TpPhaseMapper tpPhaseMapper;

    @Autowired
    private TpBuildingMapper tpBuildingMapper;

    @Autowired
    private TpUnitMapper tpUnitMapper;

    @Autowired
    private TpLevelMapper tpLevelMapper;

    @Autowired
    private TpRoomNoMapper tpRoomNoMapper;

    @Autowired
    private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addUserVerify(Integer userId, Integer roleId, Integer communityId, Integer phaseId, Integer buildingId, Integer unitId, Integer levelId, Integer roomNoId) {
        ResponseBean responseBean = new ResponseBean();

        TaUser taUser = taUserMapper.selectById(userId);
        if (null == taUser) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER.getCode(), ResponseErrorsMessages.NOT_USER.getMsg());
            return responseBean;
        }

        TaSysRole taSysRole = taSysRoleMapper.selectById(roleId);
        if (null == taSysRole) {
            responseBean.addError(ResponseErrorsMessages.NO_ROLE.getCode(), ResponseErrorsMessages.NO_ROLE.getMsg());
            return responseBean;
        }

        QueryWrapper<TpPhase> phaseQueryWrapper = new QueryWrapper<>();
        phaseQueryWrapper.eq("community_id", communityId);
        phaseQueryWrapper.eq("id", phaseId);
        TpPhase tpPhase = tpPhaseMapper.selectOne(phaseQueryWrapper);
        if (null == tpPhase) {
            responseBean.addError(ResponseErrorsMessages.NO_PHASE.getCode(), ResponseErrorsMessages.NO_PHASE.getMsg());
            return responseBean;
        }

        QueryWrapper<TpBuilding> buildingQueryWrapper = new QueryWrapper<>();
        buildingQueryWrapper.eq("community_id", communityId);
        buildingQueryWrapper.eq("phase_id", phaseId);
        buildingQueryWrapper.eq("id", buildingId);
        TpBuilding tpBuilding = tpBuildingMapper.selectOne(buildingQueryWrapper);
        if (null == tpBuilding) {
            responseBean.addError(ResponseErrorsMessages.NO_BUILDING.getCode(), ResponseErrorsMessages.NO_BUILDING.getMsg());
            return responseBean;
        }

        QueryWrapper<TpUnit> unitQueryWrapper = new QueryWrapper<>();
        unitQueryWrapper.eq("community_id", communityId);
        unitQueryWrapper.eq("phase_id", phaseId);
        unitQueryWrapper.eq("building_id", buildingId);
        unitQueryWrapper.eq("id", unitId);
        TpUnit tpUnit = tpUnitMapper.selectOne(unitQueryWrapper);
        if (null == tpUnit) {
            responseBean.addError(ResponseErrorsMessages.NO_UNIT.getCode(), ResponseErrorsMessages.NO_UNIT.getMsg());
            return responseBean;
        }

        QueryWrapper<TpLevel> levelQueryWrapper = new QueryWrapper<>();
        levelQueryWrapper.eq("community_id", communityId);
        levelQueryWrapper.eq("phase_id", phaseId);
        levelQueryWrapper.eq("building_id", buildingId);
        levelQueryWrapper.eq("unit_id", unitId);
        levelQueryWrapper.eq("id", levelId);
        TpLevel tpLevel = tpLevelMapper.selectOne(levelQueryWrapper);
        if (null == tpLevel) {
            responseBean.addError(ResponseErrorsMessages.NO_LEVEL.getCode(), ResponseErrorsMessages.NO_LEVEL.getMsg());
            return responseBean;
        }

        QueryWrapper<TpRoomNo> roomNoQueryWrapper = new QueryWrapper<>();
        roomNoQueryWrapper.eq("community_id", communityId);
        roomNoQueryWrapper.eq("phase_id", phaseId);
        roomNoQueryWrapper.eq("building_id", buildingId);
        roomNoQueryWrapper.eq("unit_id", unitId);
        roomNoQueryWrapper.eq("level_id", levelId);
        roomNoQueryWrapper.eq("id", roomNoId);
        TpRoomNo tpRoomNo = tpRoomNoMapper.selectOne(roomNoQueryWrapper);
        if (null == tpRoomNo) {
            responseBean.addError(ResponseErrorsMessages.NO_ROOM_NO.getCode(), ResponseErrorsMessages.NO_ROOM_NO.getMsg());
            return responseBean;
        }


        // 校验身份
        verifyBuidingRole(userId, roleId, true,communityId, phaseId, buildingId, unitId, levelId, roomNoId);

        // 插入房产审核表，默认审核通过
        TaUserVerify taUserVerify = new TaUserVerify();
        taUserVerify.setUserId(taUser.getUserId());
        taUserVerify.setCommunityId(communityId);
        taUserVerify.setRoleId(taSysRole.getRoleId());
        taUserVerify.setPhaseId(tpPhase.getPhaseId());
        taUserVerify.setPhaseName(tpPhase.getName());
        taUserVerify.setBuildingId(tpBuilding.getBuildingId());
        taUserVerify.setBuildingName(tpBuilding.getName());
        taUserVerify.setUnitId(tpUnit.getUnitId());
        taUserVerify.setUnitName(tpUnit.getName());
        taUserVerify.setLevelId(tpLevel.getLevelId());
        taUserVerify.setLevelName(tpLevel.getName());
        taUserVerify.setRoomNoId(tpRoomNo.getRoomNoId());
        taUserVerify.setRoomNoName(tpRoomNo.getName());
        taUserVerify.setVerifyStatus("1");
        taUserVerify.setCreateDate(new Date());
        taUserVerify.setVerifyName("大苏");

        taUserVerifyMapper.insert(taUserVerify);

        // 开始插入 楼栋资料库
        TpBuildingOwnerInfo tpBuildingOwnerInfo = new TpBuildingOwnerInfo();
        tpBuildingOwnerInfo.setCommunityId(communityId);
        tpBuildingOwnerInfo.setPhaseId(tpPhase.getPhaseId());
        tpBuildingOwnerInfo.setPhaseName(tpPhase.getName());
        tpBuildingOwnerInfo.setBuildingId(tpBuilding.getBuildingId());
        tpBuildingOwnerInfo.setBuildingName(tpBuilding.getName());
        tpBuildingOwnerInfo.setUnitId(tpUnit.getUnitId());
        tpBuildingOwnerInfo.setUnitName(tpUnit.getName());
        tpBuildingOwnerInfo.setLevelId(tpLevel.getLevelId());
        tpBuildingOwnerInfo.setLevelName(tpLevel.getName());
        tpBuildingOwnerInfo.setRoomNoId(tpRoomNo.getRoomNoId());
        tpBuildingOwnerInfo.setRoomNoName(tpRoomNo.getName());
        tpBuildingOwnerInfo.setOwnerName(taUser.getUserName());
        tpBuildingOwnerInfo.setOwnerTel(taUser.getLoginName());
        tpBuildingOwnerInfo.setGender(taUser.getGender());
        tpBuildingOwnerInfo.setPairStatus("1");
        tpBuildingOwnerInfo.setVerifyStatus("1");
        tpBuildingOwnerInfo.setCreateDate(new Date());
        // tpBuildingOwnerInfo.setCreateUser(taUser.getUserId());
        tpBuildingOwnerInfo.setTaUserVerifyId(taUserVerify.getUserVerifyId());

        tpBuildingOwnerInfoMapper.insert(tpBuildingOwnerInfo);

        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

    /**
     * 检查房产是否存在业主
     * 检查这个用户是否在这个房产存在合法角色
     *
     * @param userId
     * @param roleId
     * @param hasOwner 是否执行业主校验
     * @param communityId
     * @param phaseId
     * @param buildingId
     * @param unitId
     * @param levelId
     * @param roomNoId
     */
    private void verifyBuidingRole(Integer userId, Integer roleId, boolean hasOwner, Integer communityId, Integer phaseId, Integer buildingId, Integer unitId, Integer levelId, Integer roomNoId){
        if (roleId == 1 && hasOwner) {
            // 查询这个房产是否存在业主
            TaUserVerify userVerify = taUserVerifyMapper.selectCommunityAndAddress(communityId, phaseId, buildingId, unitId, levelId, roomNoId);
            if (null != userVerify) {
                throw new WisdomException(ResponseErrorsMessages.EXIST_OWNER.getCode(), ResponseErrorsMessages.EXIST_OWNER.getMsg());
            }
        }

        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectAddress(userId, communityId, phaseId, buildingId, unitId, levelId, roomNoId);
        if (CollectionUtils.isNotEmpty(userVerifyList) && userVerifyList.size() > 0) {
            throw new WisdomException(ResponseErrorsMessages.EXIST_BUIDDING_ROLE.getCode(), ResponseErrorsMessages.EXIST_BUIDDING_ROLE.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteUserVerify(Integer userId, Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        // 判断用户是否存在
        // 判断是否是这个用户关联房产
        // 删除楼栋资料库

        TaUser taUser = taUserMapper.selectById(userId);
        if (null == taUser) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER.getCode(), ResponseErrorsMessages.NOT_USER.getMsg());
            return responseBean;
        }

        TaUserVerify hasUserVerify = taUserVerifyMapper.selectByUserIdAndUserVerifyId(userId, userVerifyId);
        if (null == hasUserVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY.getMsg());
            return responseBean;
        }

        this.removeById(userVerifyId);

        QueryWrapper<TpBuildingOwnerInfo> buildingOwnerInfoQueryWrapper = new QueryWrapper<>();
        buildingOwnerInfoQueryWrapper.eq("ta_user_verify_id", userVerifyId);
        tpBuildingOwnerInfoMapper.delete(buildingOwnerInfoQueryWrapper);

        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

    @Override
    public ResponseBean getUserVerifyByUserIdAndCommunityId(Integer userId, Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaUserVerify> taUserVerifyQueryWrapper = new QueryWrapper<>();
        taUserVerifyQueryWrapper.eq("community_id", communityId);
        taUserVerifyQueryWrapper.eq("user_id", userId);
        List<TaUserVerify> list = this.list(taUserVerifyQueryWrapper);
        responseBean.addSuccess(list);
        return responseBean;
    }


    @Override
    public ResponseBean getUserVerifyByByUserIdAndUserVerifyId(Integer userId, Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();
        TaUserVerify hasUserVerify = taUserVerifyMapper.selectByUserIdAndUserVerifyId(userId, userVerifyId);
        if (null == hasUserVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY.getMsg());
            return responseBean;
        }

        responseBean.addSuccess(hasUserVerify);
        return responseBean;
    }
}
