package com.community.huiju.service.impl;

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.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.common.base.messagePush;
import com.community.huiju.dao.*;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.feign.TaUserFeignService;
import com.community.huiju.model.*;
import com.community.huiju.service.ITaUserVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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;

/**
 * 审核 业务实现
 *
 * @author weiximei
 */
@Service
@Slf4j
public class TaUserVerifyServiceImpl extends ServiceImpl<TaUserVerifyMapper, TaUserVerify> implements ITaUserVerifyService {

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;

    @Autowired
    private TpPhaseMapper tpPhaseMapper;

    @Autowired
    private TpBuildingMapper tpBuildingMapper;

    @Autowired
    private TpUnitMapper tpUnitMapper;

    @Autowired
    private TpLevelMapper tpLevelMapper;

    @Autowired
    private TpRoomNoMapper tpRoomNoMapper;

    @Autowired
    private TaUserFeignService taUserFeignService;

    @Autowired
    private MessageMapper tpmessageMapper;

    @Override
    public ResponseBean selectAll(String phone, String userName, String idCard, Integer pageNum, Integer pageSize, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        Page<TaUserVerify> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        IPage<TaUserVerify> userVerifyIPage = taUserVerifyMapper.selectAllByPhoneAndUserNameAndIdCard(page, phone, userName, idCard, userElement.getCommunityId());
        responseBean.addSuccess(userVerifyIPage);

        return responseBean;
    }

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

        TaUserVerify userVerify = taUserVerifyMapper.selectById(userVerifyId);
        if (null == userVerify) {
            responseBean.addError("审核数据不存在！");
            return responseBean;
        }

        if (!Constant.TO_AUDIT.equals(userVerify.getVerifyStatus())) {
            responseBean.addError("审核状态错误！");
            return responseBean;
        }
        // 设置成用户提交上来的状态结果
        String status = verifyStatus == true ? Constant.APPROVED : Constant.REJECTED;
        userVerify.setVerifyStatus(status);

        // 校验房产
        hasUserVerify(userElement, userVerify, true);

        User user = userMapper.selectById(userElement.getId());


        TaUser taUser = taUserMapper.selectById(userVerify.getUserId());
        TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectCommunityIdAndAddress(userVerify.getCommunityId(), userVerify.getPhaseId(),
                userVerify.getBuildingId(), userVerify.getUnitId(),
                userVerify.getLevelId(), userVerify.getRoomNoId(),
                taUser.getLoginName());
        // 插入楼栋资料库
        // 保证这个用户在这个小区的房产中只存在一个数据
        if (verifyStatus && null == tpBuildingOwnerInfo) {
            insertBuildingOwnerInfo(userVerify, user);
        }
        // 只有审核不通过的时候，写入不通过原因
        if (Constant.REJECTED.equals(status)) {
            userVerify.setRemark(remark);
        }

        userVerify.setVerifyName(user.getUserName());
        taUserVerifyMapper.updateById(userVerify);

        try {
            // 推送海康
            ResponseBean pushHKPerson = taUserFeignService.pushHKPerson(userVerify.getUserId(), userVerifyId);
            if (!"0".equals(pushHKPerson.getCode())) {
                throw new WisdomException("设备推送失败！");
            }
        } catch (Exception e) {
            log.info("设备推送失败！，人员id：{}", userVerify.getUserId());
            throw new WisdomException("设备推送失败！");
        }


        String[] messageArr= new messagePush().messagePushAll( );
        for (String count : messageArr) {
            Message message = new Message();
            message.setCommunityId(userVerify.getCommunityId());
            message.setMessageType("9");
            message.setAdviceType("1");
            message.setModelType("1");
            message.setUuid(userVerify.getId());
            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(LocalDateTime.now());
            tpmessageMapper.insert(message);
        }
        responseBean.addSuccess("操作成功！");

        return responseBean;
    }

    /**
     * 校验这个房产
     * @param userElement
     * @param userVerify
     * @param hasOwner 是否执行业主校验
     */
    private void hasUserVerify(UserElement userElement, TaUserVerify userVerify, boolean hasOwner){
        TaUserVerify hasUserVerify = null;
        // 校验这个房产有没有业主，只能存在一个业主
        if (hasOwner && userVerify.getRoleId().intValue() == 1 && "1".equals(userVerify.getVerifyStatus())) {
            hasUserVerify = taUserVerifyMapper.selectCommunityAndAddress(userElement.getCommunityId(), userVerify.getPhaseId(),
                    userVerify.getBuildingId(), userVerify.getUnitId(),
                    userVerify.getLevelId(), userVerify.getRoomNoId());
            if (null != hasUserVerify) {
                throw new WisdomException("已经存在审核通过的业主！");
            }
        }

        // 校验当前身份 和 角色，是否有审核通过的！
        hasUserVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(userVerify.getUserId(), userVerify.getCommunityId(), userVerify.getPhaseId(),
                userVerify.getBuildingId(), userVerify.getUnitId(),
                userVerify.getLevelId(), userVerify.getRoomNoId(), userVerify.getRoleId());
        if (null != hasUserVerify) {
            throw new WisdomException("在当前房产中已存在这个身份！");
        }
    }

    /**
     * 插入楼栋资料库
     *
     * @param user 物业人员
     * @param userVerify 审核数据
     * @return TpBuildingOwnerInfo
     */
    private TpBuildingOwnerInfo insertBuildingOwnerInfo(TaUserVerify userVerify, User user) {
        TaUser taUser = taUserMapper.selectById(userVerify.getUserId());
        TpPhase tpPhase = tpPhaseMapper.selectById(userVerify.getPhaseId());
        TpBuilding tpBuilding = tpBuildingMapper.selectById(userVerify.getBuildingId());
        TpUnit tpUnit = tpUnitMapper.selectById(userVerify.getUnitId());
        TpLevel tpLevel = tpLevelMapper.selectById(userVerify.getLevelId());
        TpRoomNo tpRoomNo = tpRoomNoMapper.selectById(userVerify.getRoomNoId());
        TpBuildingOwnerInfo tpBuildingOwnerInfo = new TpBuildingOwnerInfo();
        tpBuildingOwnerInfo.setCommunityId(userVerify.getCommunityId());
        tpBuildingOwnerInfo.setIdCard(taUser.getIdCard());
        tpBuildingOwnerInfo.setPhaseId(tpPhase.getId());
        tpBuildingOwnerInfo.setPhaseName(tpPhase.getName());
        tpBuildingOwnerInfo.setBuildingId(tpBuilding.getId());
        tpBuildingOwnerInfo.setBuildingName(tpBuilding.getName());
        tpBuildingOwnerInfo.setUnitId(tpUnit.getId());
        tpBuildingOwnerInfo.setUnitName(tpUnit.getName());
        tpBuildingOwnerInfo.setLevelId(tpLevel.getId());
        tpBuildingOwnerInfo.setLevelName(tpLevel.getName());
        tpBuildingOwnerInfo.setRoomNoId(tpRoomNo.getId());
        tpBuildingOwnerInfo.setRoomNoName(tpRoomNo.getName());
        tpBuildingOwnerInfo.setOwnerName(taUser.getUserName());
        tpBuildingOwnerInfo.setOwnerTel(taUser.getLoginName());
        tpBuildingOwnerInfo.setGender(taUser.getGender());
        tpBuildingOwnerInfo.setPairStatus("1");
        tpBuildingOwnerInfo.setVerifyStatus("1");
        tpBuildingOwnerInfo.setCreateDate(LocalDateTime.now());
        tpBuildingOwnerInfo.setCreateUser(user.getId());
        tpBuildingOwnerInfo.setTaUserVerifyId(userVerify.getId());

        tpBuildingOwnerInfoMapper.insert(tpBuildingOwnerInfo);
        return tpBuildingOwnerInfo;
    }

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

        TaUserVerify userVerify = taUserVerifyMapper.selectById(userVerifyId);
        if (null == userVerify) {
            responseBean.addError("审核数据不存在！");
            return responseBean;
        }
        // 不通过的原因
        userVerify.setRemark(remark);
        userVerify.setRoleId(Integer.valueOf(roleState));
        userVerify.setVerifyStatus(verifyStatus);

        //判断审核数据是否冲突
        hasUserVerify(userElement,  userVerify,  true);

        // 被审核的用户(APP端)
        TaUser taUser = taUserMapper.selectById(userVerify.getUserId());
        // 物业人员
        User user = userMapper.selectById(userElement.getId());
        TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectCommunityIdAndAddress(userVerify.getCommunityId(), userVerify.getPhaseId(),
                userVerify.getBuildingId(), userVerify.getUnitId(),
                userVerify.getLevelId(), userVerify.getRoomNoId(),
                taUser.getLoginName());

        // 审核通过的情况
        if ("1".equals(verifyStatus) && StringUtils.isNotBlank(roleState)) {
            // 审核通过就把 不通过的原因拿掉
            userVerify.setRemark("");
            userVerify.setRoleId(Integer.valueOf(roleState));
            // 只有这个人在当前房产没有楼栋资料的时候才添加
            if (null == tpBuildingOwnerInfo) {
                // 添加楼栋数据
               tpBuildingOwnerInfo = insertBuildingOwnerInfo(userVerify, user);

               // 设置审核id
               tpBuildingOwnerInfo.setTaUserVerifyId(userVerify.getId());
               tpBuildingOwnerInfoMapper.updateById(tpBuildingOwnerInfo);
            }

            try {
                // 推送海康
                ResponseBean pushHKPerson = taUserFeignService.pushHKPerson(userVerify.getUserId(), userVerifyId);
                if (!"0".equals(pushHKPerson.getCode())) {
                    throw new WisdomException("设备推送失败！");
                }
            } catch (Exception e) {
                log.info("设备推送失败！，人员id：{}", userVerify.getUserId());
                throw new WisdomException("设备推送失败！");
            }

        }
        userVerify.setVerifyName(user.getUserName());
        taUserVerifyMapper.updateById(userVerify);
        //推送消息
        String[] messageArr= new messagePush().messagePushAll( );
        for (String count : messageArr) {
            Message message = new Message();
            message.setCommunityId(userVerify.getCommunityId());
            message.setMessageType("9");
            message.setAdviceType("1");
            message.setModelType("1");
            message.setUuid(userVerify.getId());
            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(LocalDateTime.now());
            tpmessageMapper.insert(message);
        }

        responseBean.addSuccess("操作成功！");

        return responseBean;
    }
}
