package com.community.huiju.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.common.messagePush;
import com.community.huiju.dao.*;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.IHKService;
import com.community.huiju.service.TaUserVerifyServicel;
import com.community.huiju.vo.TaUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 *
 * app端用户审核表，存放用户的角色还有房产信息
 * @author weiximei
 */
@Slf4j
@Service
public class TaUserVerifyServicelmpl implements TaUserVerifyServicel {

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private ToCommunitiesMapper toCommunitiesMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private SysNationMapper sysNationMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TpMessageMapper tpMessageMapper;

    /**
     * 期
     */
    @Autowired
    private TpPhaseMapper tpPhaseMapper;

    /**
     * 单元
     */
    @Autowired
    private TpUnitMapper tpUnitMapper;

    /**
     * 楼层
     */
    @Autowired
    private TpLevelMapper tpLevelMapper;

    /**
     * 栋
     */
    @Autowired
    private TpBuildingMapper tpBuildingMapper;

    /**
     * 楼栋资料库
     */
    @Autowired
    private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;

    /**
     * 户号
     */
    @Autowired
    private TpRoomNoMapper tpRoomNoMapper;

    @Autowired
    private IHKService ihkService;

    @Override
    public ResponseBean getToAuditNotApproved(Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();
        TaUserVerify taUserVerify = taUserVerifyMapper.selectByPrimaryKey(userVerifyId);
        TaSysRole taSysRole = taSysRoleMapper.selectByPrimaryKey(taUserVerify.getRoleId());
        taUserVerify.setRoleName(taSysRole.getRoleName());
        if ("2".equals(taUserVerify.getVerifyStatus()) || "1".equals(taUserVerify.getVerifyStatus())) {

            // 开始查询 业主
            TaUserVerify userVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(taUserVerify.getCommunityId(), taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(), taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
            if (null != userVerify) {
                TaUser taUser = taUserMapper.selectByPrimaryKey(userVerify.getUserId());
                taUserVerify.setOwnerName(taUser.getUserName());
            }
        }

        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

    @Override
    public ResponseBean addUserVerify(UserElement userElement, String parameter) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        TaUserVerify taUserVerify = jsonObject.toJavaObject(TaUserVerify.class);

        // 通过 角色名称 查询出角色的id
        String roleName = jsonObject.getString("roleName");
        TaSysRole sysRole = taSysRoleMapper.selectByRoleName(roleName);
        if (null == sysRole) {
            responseBean.addError("非法角色!");
            return responseBean;
        }

        // 如果申请的是户主
        if (sysRole.getId().intValue() == 1) {
            // 校验是否有审核通过的业主
            TaUserVerify hasUserVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(taUserVerify.getCommunityId(), taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(), taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
            if (null != hasUserVerify) {
                responseBean.addError("此房产已存在户主!");
                return responseBean;
            }
        }


        // 校验该用户是否已经提交了一个当前房产的审核, 包含 待审核和已审核通过
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectCommunityAndAddressAndNotVerifyStatus2(userElement.getId(), taUserVerify.getCommunityId(),
                taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(),
                taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
        if (null != userVerifyList && userVerifyList.size() > 0) {
            responseBean.addError("您已提交了这个房产的审核！请等待户主或者物业审核后，再进行下一步操作！");
            return responseBean;
        }


        // 查询 期/栋/单元/楼层/户号 -> 设置 相应 id 和 name
        TpPhase phase = tpPhaseMapper.selectByPrimaryKey(taUserVerify.getPhaseId());
        TpBuilding building = tpBuildingMapper.selectByPrimaryKey(taUserVerify.getBuildingId());
        TpUnit unit = tpUnitMapper.selectByPrimaryKey(taUserVerify.getUnitId());
        TpLevel level = tpLevelMapper.selectByPrimaryKey(taUserVerify.getLevelId());
        TpRoomNo roomNo = tpRoomNoMapper.selectByPrimaryKey(taUserVerify.getRoomNoId());


        taUserVerify.setRoleId(sysRole.getId());
        taUserVerify.setUserId(userElement.getId());
        taUserVerify.setVerifyStatus("0");
        taUserVerify.setCreateDate(new Date());
        taUserVerify.setPhaseName(phase.getName());
        taUserVerify.setBuildingName(building.getName());
        taUserVerify.setUnitName(unit.getName());
        taUserVerify.setLevelName(level.getName());
        taUserVerify.setRoomNoName(roomNo.getName());

        int rows = taUserVerifyMapper.insertSelective(taUserVerify);
        if (rows <= 0) {
            responseBean.addError("操作失败！");
            return responseBean;
        }

        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

    @Override
    public ResponseBean deleteUserVerify(Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userVerifyId);
        if ("1".equals(userVerify.getVerifyStatus())) {
            responseBean.addError("已审核通过的房产，无法删除！");
            return responseBean;
        }

        taUserVerifyMapper.deleteByPrimaryKey(userVerifyId);
        responseBean.addSuccess("操作成功！");
        return responseBean;
    }

    @Override
    public ResponseBean getByCurrentUser(UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectByUserId(userElement.getId());
        userVerifyList.forEach(e -> {
            // 角色
            TaSysRole taSysRole = taSysRoleMapper.selectByPrimaryKey(e.getRoleId());
            e.setRoleName(taSysRole.getRoleName());
            // 小区名称 、省市区
            setUserVoProperties(e.getCommunityId(), e);
        });

        responseBean.addSuccess(userVerifyList);
        return responseBean;
    }

    /**
     * 设置 TaUserVO 的一些信息
     *
     *      小区，省市区
     *
     * @param communityId
     * @param taUserVerify
     */
    private void setUserVoProperties(Integer communityId, TaUserVerify taUserVerify) {
        // 获取小区
        ToCommunities toCommunities = toCommunitiesMapper.selectByPrimaryKey(communityId);
        // 省
        SysNation province = sysNationMapper.selectByPrimaryKey(toCommunities.getProvinceId());
        // 市
        SysNation city = sysNationMapper.selectByPrimaryKey(toCommunities.getCityId());
        // 区
        SysNation district = sysNationMapper.selectByPrimaryKey(toCommunities.getDistrictId());

        taUserVerify.setCommunityAddress(province.getProvince()+""+city.getCity()+""+district.getDistrict() + toCommunities.getCommunityName());
        taUserVerify.setCommunityName(toCommunities.getCommunityName());
    }

    @Override
    public ResponseBean deleteCurrentUserVerify(UserElement userElement, Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userVerifyId);
        if (null != userVerify && null != userElement.getUserVerifyId()  && userElement.getUserVerifyId().intValue()  == userVerify.getId().intValue()) {
            responseBean.addError("无法删除当前登录的房产！");
            return responseBean;
        }
        if (null != userVerify && userElement.getId().intValue() != userVerify.getUserId().intValue()) {
            responseBean.addError("您名下无此房产关联！");
            return responseBean;
        }

        taUserVerifyMapper.deleteByPrimaryKey(userVerifyId);
        responseBean.addSuccess("操作成功！");
        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean verifyUser(UserElement userElement, Integer userVerifyId, String userVerifyStatus, String remark) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userVerifyId);
        if (null == userVerify) {
            responseBean.addError("该审核不存在！");
            return responseBean;
        }
        if (userVerify.getRoleId().intValue() == 1) {
            responseBean.addError("不能审核业主！");
            return responseBean;
        }
        if (!Constant.TO_AUDIT.equals(userVerify.getVerifyStatus())) {
            responseBean.addError("只能审核待审状态！");
            return responseBean;
        }
        List<TaUser> userList = taUserMapper.selectHouseUserList(userElement.getCommunityId(), userVerify.getPhaseId(), userVerify.getBuildingId(), userVerify.getUnitId(), userVerify.getLevelId(), userVerify.getRoomNoId(), userElement.getId());
        boolean bool = userList.stream().anyMatch(e -> e.getId().intValue() == userVerify.getUserId().intValue());
        if (bool) {
            userVerify.setVerifyStatus(userVerifyStatus);
            userVerify.setRemark(remark);
            taUserVerifyMapper.updateByPrimaryKeySelective(userVerify);
            // 如果业主审核 租客/家属 不是审核通过的状态， 就不在往下执行
            if (!Constant.APPROVED.equals(userVerifyStatus)) {
                responseBean.addError("操作成功！");
                return responseBean;
            }

            // 获取这个被审核的用户
            TaUser user = taUserMapper.selectByPrimaryKey(userVerify.getUserId());

            // 往楼栋资料库插入数据
            // 校验楼栋信息表
            TpBuildingOwnerInfo selectBuild = getBuildingInfo(userElement, user.getLoginName());
            if (null == selectBuild) {
                // 插入楼栋信息数据
                insertTpBuildingOwnerInfo(userElement, user, null, userVerify.getId());
            }
            //审核通过后推送消息（临时数据）
             String[] messageArr= new messagePush().messagePushAll();
            for (String count:messageArr) {
                TpMessage message = new TpMessage();
                message.setCommunityId(userVerify.getCommunityId());
                message.setMessageType("9");
                message.setAdviceType("1");
                message.setModelType("1");
                message.setUuid(userElement.getUserVerifyId());
                message.setUuidType("1");
                message.setSource("1");
                message.setMessageContent(count);
                message.setStatus("1");
                message.setResult("");
                message.setMeaasgeTypeId("");
                message.setReadStatus("0");
                message.setCreateUser(userElement.getId());
                message.setCreateDate(new Date());
                tpMessageMapper.insert(message);
            }
            // 推送海康
            responseBean = ihkService.pushPerson(user.getId()+"", userVerify.getId());
            if ("1".equals(responseBean.getCode())) {
                throw new WisdomException("推送HK失败！");
            }

            responseBean.addSuccess("操作成功！");
            return responseBean;
        }
        responseBean.addError("操作失败！");
        return responseBean;
    }

    /**
     * 查询 楼栋信息
     *      根据小区Id, 栋,单元,楼层,房号, 手机号
     * @param userElement
     * @param phone
     * @return
     */
    private TpBuildingOwnerInfo getBuildingInfo(UserElement userElement, String phone) {

        TpBuildingOwnerInfo selectBuild = tpBuildingOwnerInfoMapper.selectCommunityAndAddressAndPhone(userElement.getCommunityId(),
                userElement.getPhaseId(), userElement.getBuildingId(), userElement.getUnitId(), userElement.getLevelId(),
                userElement.getRoomNoId(), phone);

        return selectBuild;
    }

    /**
     * 插入 楼栋资料库
     *
     * @param userElement
     * @param user
     * @param userId 创建人
     * @param userVerifyId 审核的id
     */
    private TpBuildingOwnerInfo insertTpBuildingOwnerInfo (UserElement userElement, TaUser user, Integer userId, Integer userVerifyId) {
        TpBuildingOwnerInfo tpBuildingOwnerInfo = new TpBuildingOwnerInfo();
        // 查询 期/楼栋/单元/层/户号
        TpPhase phase = tpPhaseMapper.selectByPrimaryKey(userElement.getPhaseId());
        TpBuilding building = tpBuildingMapper.selectByPrimaryKey(userElement.getBuildingId());
        TpUnit unit = tpUnitMapper.selectByPrimaryKey(userElement.getUnitId());
        TpLevel level = tpLevelMapper.selectByPrimaryKey(userElement.getLevelId());
        TpRoomNo roomNo = tpRoomNoMapper.selectByPrimaryKey(userElement.getRoomNoId());


        // 主键是自增的, 所以设置为 null
        tpBuildingOwnerInfo.setId(null);
        tpBuildingOwnerInfo.setPhaseId(phase.getId());
        tpBuildingOwnerInfo.setPhaseName(phase.getName());
        tpBuildingOwnerInfo.setBuildingId(building.getId());
        tpBuildingOwnerInfo.setBuildingName(building.getName());
        tpBuildingOwnerInfo.setUnitId(unit.getId());
        tpBuildingOwnerInfo.setUnitName(unit.getName());
        tpBuildingOwnerInfo.setLevelId(level.getId());
        tpBuildingOwnerInfo.setLevelName(level.getName());
        tpBuildingOwnerInfo.setRoomNoId(roomNo.getId());
        tpBuildingOwnerInfo.setRoomNoName(roomNo.getName());
        tpBuildingOwnerInfo.setOwnerName(user.getUserName());
        tpBuildingOwnerInfo.setOwnerTel(user.getLoginName());
        tpBuildingOwnerInfo.setGender(user.getGender());
        // tpBuildingOwnerInfo.setUpdateUser(userId);
        tpBuildingOwnerInfo.setUpdateDate(new Date());
        tpBuildingOwnerInfo.setCreateDate(new Date());
        // tpBuildingOwnerInfo.setCreateUser(userId);
        tpBuildingOwnerInfo.setVerifyStatus("1");
        tpBuildingOwnerInfo.setPairStatus("1");
        tpBuildingOwnerInfo.setTaUserVerifyId(userVerifyId);

        // 添加的时候, 默认是当前操作的小区
        tpBuildingOwnerInfo.setCommunityId(userElement.getCommunityId());

        int row = tpBuildingOwnerInfoMapper.insertSelective(tpBuildingOwnerInfo);
        if (row <= 0) {
            log.error("添加操作! 楼栋业主信息表 失败!");
            throw new WisdomException("操作失败!");
        }
        return tpBuildingOwnerInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addDaSuUserVerify(String parameter) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        TaUserVerify taUserVerify = jsonObject.toJavaObject(TaUserVerify.class);

        // 通过 角色名称 查询出角色的id
        String roleName = jsonObject.getString("roleName");
        TaSysRole sysRole = taSysRoleMapper.selectByRoleName(roleName);
        if (null == sysRole) {
            responseBean.addError("非法角色!");
            return responseBean;
        }

        // 如果申请的是户主
        if (sysRole.getId().intValue() == 1) {
            // 校验是否有审核通过的业主
            TaUserVerify hasUserVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(taUserVerify.getCommunityId(), taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(), taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
            if (null != hasUserVerify) {
                responseBean.addError("此房产已存在户主!");
                return responseBean;
            }
        }


        // 校验该用户是否已经提交了一个当前房产的审核, 包含 待审核和已审核通过
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectCommunityAndAddressAndNotVerifyStatus2(taUserVerify.getUserId(), taUserVerify.getCommunityId(),
                taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(),
                taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
        if (null != userVerifyList && userVerifyList.size() > 0) {
            responseBean.addError("您已添加了这个房产！");
            return responseBean;
        }


        // 查询 期/栋/单元/楼层/户号 -> 设置 相应 id 和 name
        TpPhase phase = tpPhaseMapper.selectByPrimaryKey(taUserVerify.getPhaseId());
        TpBuilding building = tpBuildingMapper.selectByPrimaryKey(taUserVerify.getBuildingId());
        TpUnit unit = tpUnitMapper.selectByPrimaryKey(taUserVerify.getUnitId());
        TpLevel level = tpLevelMapper.selectByPrimaryKey(taUserVerify.getLevelId());
        TpRoomNo roomNo = tpRoomNoMapper.selectByPrimaryKey(taUserVerify.getRoomNoId());


        taUserVerify.setRoleId(sysRole.getId());
        taUserVerify.setUserId(taUserVerify.getUserId());
        taUserVerify.setCreateDate(new Date());
        taUserVerify.setPhaseName(phase.getName());
        taUserVerify.setBuildingName(building.getName());
        taUserVerify.setUnitName(unit.getName());
        taUserVerify.setLevelName(level.getName());
        taUserVerify.setRoomNoName(roomNo.getName());
        taUserVerify.setVerifyStatus("1");

        int rows = taUserVerifyMapper.insertSelective(taUserVerify);
        if (rows <= 0) {
            responseBean.addError("操作失败！");
            return responseBean;
        }

        // 获取这个被审核的用户
        TaUser user = taUserMapper.selectByPrimaryKey(taUserVerify.getUserId());
        if (null == user) {
            throw new WisdomException("用户不存在！");
        }

        UserElement userElement = new UserElement();
        userElement.setPhaseId(taUserVerify.getPhaseId());
        userElement.setBuildingId(taUserVerify.getBuildingId());
        userElement.setUnitId(taUserVerify.getUnitId());
        userElement.setLevelId(taUserVerify.getLevelId());
        userElement.setRoomNoId(taUserVerify.getRoomNoId());
        userElement.setCommunityId(taUserVerify.getCommunityId());

        // 往楼栋资料库插入数据
        // 校验楼栋信息表
        TpBuildingOwnerInfo selectBuild = getBuildingInfo(userElement, user.getLoginName());
        if (null == selectBuild) {
            // 插入楼栋信息数据
            insertTpBuildingOwnerInfo(userElement, user, null, taUserVerify.getId());
        }

        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

}
