package com.huiju.estateagents.property.service.impl;

import com.alibaba.fastjson.JSONObject;
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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.property.common.Constant;
import com.huiju.estateagents.property.common.UserElement;
import com.huiju.estateagents.property.common.base.messagePush;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.exception.WisdomException;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.ITaUserVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private TaPersonMapper taPersonMapper;

    @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 MessageMapper tpmessageMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public ResponseBean selectAll(String phone, String userName, String idCard, Integer pageNum, Integer pageSize, TaUser 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.getOrgId());
        responseBean.addSuccess(userVerifyIPage);

        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean auditUser(TaUser 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);

        TaUser user = taUserMapper.selectById(userElement.getUserId());


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

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

        taPerson.setName(userVerify.getOwnerName());
        taPersonMapper.updateById(taPerson);

        if (Constant.APPROVED.equals(status)){
            // 审核通过加20积分
            applicationContext.publishEvent(new EventBus(userVerify, EventBus.EventType.UserVerify,1));
        }

        String[] messageArr= new messagePush().messagePushAll( );
        for (String count : messageArr) {
            Message message = new Message();
            message.setOrgId(userVerify.getOrgId());
            message.setMessageType("9");
            message.setAdviceType("1");
            message.setModelType("1");
            message.setUuid(userVerify.getId().toString());
            message.setUuidType("1");
            message.setSource("1");
            message.setMessageContent(count);
            message.setStatus("1");
            message.setResult("");
            message.setMeaasgeTypeId("");
            message.setReadStatus("0");
            message.setCreateUser(userElement.getUserId().toString());
            message.setCreateDate(LocalDateTime.now());
            tpmessageMapper.insert(message);
        }
        responseBean.addSuccess("操作成功！");

        return responseBean;
    }

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

        // 校验当前身份 和 角色，是否有审核通过的！
        hasUserVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(userVerify.getPersonId(), userVerify.getOrgId(), 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, TaUser user) {
        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.setOrgId(userVerify.getOrgId());
        tpBuildingOwnerInfo.setIdCard(userVerify.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(userVerify.getOwnerName());
        tpBuildingOwnerInfo.setOwnerTel(userVerify.getPhone());
        tpBuildingOwnerInfo.setGender(userVerify.getGender());
        tpBuildingOwnerInfo.setPairStatus("1");
        tpBuildingOwnerInfo.setVerifyStatus("1");
        tpBuildingOwnerInfo.setCreateDate(LocalDateTime.now());
        tpBuildingOwnerInfo.setCreateUser(user.getUserId());
        tpBuildingOwnerInfo.setTaUserVerifyId(userVerify.getId());

        tpBuildingOwnerInfoMapper.insert(tpBuildingOwnerInfo);
        return tpBuildingOwnerInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean verifyinfoAdd(TaUser 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);

        // 被审核的用户
        TaPerson taPerson = taPersonMapper.selectById(userVerify.getPersonId());
        // 物业人员
        TaUser user = taUserMapper.selectById(userElement.getUserId());
        TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectCommunityIdAndAddress(userVerify.getOrgId(), userVerify.getPhaseId(),
                userVerify.getBuildingId(), userVerify.getUnitId(),
                userVerify.getLevelId(), userVerify.getRoomNoId(),
                taPerson.getPhone()
        );

        // 审核通过的情况
        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);
            }

        }
        userVerify.setVerifyName(user.getUserName());
        taUserVerifyMapper.updateById(userVerify);
        //推送消息
        String[] messageArr= new messagePush().messagePushAll( );
        for (String count : messageArr) {
            Message message = new Message();
            message.setOrgId(userVerify.getOrgId());
            message.setMessageType("9");
            message.setAdviceType("1");
            message.setModelType("1");
            message.setUuid(userVerify.getId().toString());
            message.setUuidType("1");
            message.setSource("1");
            message.setMessageContent(count);
            message.setStatus("1");
            message.setResult("");
            message.setMeaasgeTypeId("");
            message.setReadStatus("0");
            message.setCreateUser(userElement.getUserId().toString());
            message.setCreateDate(LocalDateTime.now());
            tpmessageMapper.insert(message);
        }

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

        return responseBean;
    }



    @Override
    public ResponseBean getToAuditNotApproved(Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();
        TaUserVerify taUserVerify = taUserVerifyMapper.selectById(userVerifyId);
        TaPerson currentUser = taPersonMapper.selectById(taUserVerify.getPersonId());
        taUserVerify.setLoginName(currentUser.getName());

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

        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

    @Override
    @Transactional
    public ResponseBean addUserVerify(String personId, String parameter,Integer orgId) {
        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;
        }

        // 校验是否有审核通过的业主
        TaUserVerify hasUserVerify = taUserVerifyMapper.selectWxCommunityAndAddressAndRoleId(taUserVerify.getOrgId(), taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(), taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
        if (null != hasUserVerify) {
            responseBean.addError("此房产已存在户主!");
            return responseBean;
        }


        // 校验该用户是否已经提交了一个当前房产的审核, 包含 待审核和已审核通过
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectCommunityAndAddressAndNotVerifyStatus2(taUserVerify.getPersonId(), taUserVerify.getOrgId(),
                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.selectById(taUserVerify.getPhaseId());
        TpBuilding building = tpBuildingMapper.selectById(taUserVerify.getBuildingId());
        TpUnit unit = tpUnitMapper.selectById(taUserVerify.getUnitId());
        TpLevel level = tpLevelMapper.selectById(taUserVerify.getLevelId());
        TpRoomNo roomNo = tpRoomNoMapper.selectById(taUserVerify.getRoomNoId());


        taUserVerify.setRoleId(sysRole.getId());
        taUserVerify.setPersonId(personId);
        taUserVerify.setVerifyStatus("0");
        taUserVerify.setOrgId(orgId);
        taUserVerify.setCreateDate(LocalDateTime.now());
        taUserVerify.setPhaseName(phase.getName());
        taUserVerify.setBuildingName(building.getName());
        taUserVerify.setUnitName(unit.getName());
        taUserVerify.setLevelName(level.getName());
        taUserVerify.setRoomNoName(roomNo.getName());

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

        // 查询是否有相同的房间号
        TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectCommunityIdAndAddress(taUserVerify.getOrgId(), taUserVerify.getPhaseId(),
                taUserVerify.getBuildingId(), taUserVerify.getUnitId(),
                taUserVerify.getLevelId(), taUserVerify.getRoomNoId(),
                taUserVerify.getPhone());
        if (null != tpBuildingOwnerInfo){
            // 自动审核通过
            tpBuildingOwnerInfo.setPairStatus("1");
            tpBuildingOwnerInfo.setVerifyStatus("1");
            tpBuildingOwnerInfo.setCreateDate(LocalDateTime.now());
            tpBuildingOwnerInfo.setCreateUser(-1);
            tpBuildingOwnerInfo.setTaUserVerifyId(taUserVerify.getId());
            tpBuildingOwnerInfoMapper.insert(tpBuildingOwnerInfo);

            taUserVerify.setVerifyStatus("1");
            taUserVerify.setVerifyName("自动审核通过");
            taUserVerifyMapper.updateById(taUserVerify);

            TaPerson taPerson = taPersonMapper.selectById(personId);
            taPerson.setName(taUserVerify.getOwnerName());
            taPersonMapper.updateById(taPerson);

        }
//        // 推送消息
//        TaUserVerify userVerify = taUserVerifyMapper.selectCommunityAndAddressAndRoleId(taUserVerify.getCommunityId(), taUserVerify.getPhaseId(), taUserVerify.getBuildingId(), taUserVerify.getUnitId(), taUserVerify.getLevelId(), taUserVerify.getRoomNoId());
//        if (null != userVerify){
//            // 先推app
//            Map<String,Object> map = new HashMap<>();
//            map.put("communityId",userVerify.getCommunityId());
//            map.put("createUserId",userVerify.getId());
//            map.put("userVerify",userVerify.getId());
//            map.put("name",userElement.getUserName());
//            map.put("roleName",sysRole.getDescription());
//            applicationContext.publishEvent(new MessageEvent(sysRole, Constant.CUSTOMER_SUBMIT_VERIFY,map));
//        }
//        // 推物业端，推这个小区下的所有管理员
//        List<TpUser> tpUserList= tpUserMapper.selectCommunityId(taUserVerify.getCommunityId());
//        for (TpUser tpUser:tpUserList) {
//            Map<String, Object> mapProp = new HashMap<>();
//            mapProp.put("communityId", taUserVerify.getCommunityId());
//            mapProp.put("createUserId", taUserVerify.getId());
//            mapProp.put("userVerifyId", taUserVerify.getId());
//            mapProp.put("name", userElement.getUserName());
//            mapProp.put("tpUserId", tpUser.getId());
//            applicationContext.publishEvent(new MessageEvent(mapProp, Constant.CUSTOMER_SUBMIT_PROP_VERIFY, mapProp));
//        }
        responseBean.addSuccess(taUserVerify);
        return responseBean;
    }

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

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

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

    @Override
    public ResponseBean getByCurrentUser(String personId) {
        ResponseBean responseBean = new ResponseBean();

        QueryWrapper<TaUserVerify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id",personId);
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectList(queryWrapper);
        responseBean.addSuccess(userVerifyList);
        return responseBean;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteCurrentUserVerify(TaUser userElement, Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectById(userVerifyId);

        taUserVerifyMapper.deleteById(userVerifyId);

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