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.core.toolkit.StringUtils;
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.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.IBillInvoiceService;
import com.huiju.estateagents.property.service.IBuildingOwnerInfoService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * <p>
 * 楼栋业主资料信息表 服务实现类
 * </p>
 *
 * @author weiximei
 * @since 2018-12-18
 */
@Service("iBuildingOwnerInfoService")
@Slf4j
@Transactional
public class BuildingOwnerInfoServiceImpl extends ServiceImpl<TpBuildingOwnerInfoMapper, TpBuildingOwnerInfo> implements IBuildingOwnerInfoService {

    @Autowired
    private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;
    
    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TaSysUserRoleMapper taSysUserRoleMapper;
    
    @Autowired
    private BillInvoiceMapper billInvoiceMapper;

    @Autowired
    private IBillInvoiceService iBillInvoiceService;

    @Autowired
    private TpBuildingMapper tpBuildingMapper;
    
    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;
    
    @Autowired
    private TpPhaseMapper tpPhaseMapper;
    
    @Autowired
    private TpUnitMapper tpUnitMapper;
    
    @Autowired
    private TpLevelMapper tpLevelMapper;
    
    @Autowired
    private TpRoomNoMapper tpRoomNoMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private TaFaceMapper taFaceMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private TpTransactionMapper tpTransactionMapper;
    
    public static final Logger logger = LoggerFactory.getLogger(BuildingOwnerInfoServiceImpl.class);
    
    @Override
    public ResponseBean listQuery(String parameter, TaUser userElement) {

        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        TpBuildingOwnerInfo tpBuildingOwnerInfo = jsonObject.toJavaObject(jsonObject,TpBuildingOwnerInfo.class);
        tpBuildingOwnerInfo.setCommunityId(userElement.getOrgId());
        Long pageNum = jsonObject.getLong("pageNum") == null ? 1 : jsonObject.getLong("pageNum");
        Long pageSize = jsonObject.getLong("pageSize") == null ? 10 : jsonObject.getLong("pageSize");

        Page page = new Page(pageNum,pageSize);

        // 分页查询
        List<TpBuildingOwnerInfo> list = tpBuildingOwnerInfoMapper.selectListByParams(page,tpBuildingOwnerInfo);

        Map<String, Object> retMap = Maps.newHashMap();

        retMap.put("list", list);
        retMap.put("total", page.getTotal());
        retMap.put("pageNum", page.getCurrent());
        retMap.put("pageSize", page.getSize());

        responseBean.addSuccess(retMap);

        return responseBean;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean update(String parameter, TaUser userElement) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        // 审核id
        Integer userVerifyId = jsonObject.getInteger("userVerifyId");
        Integer roleId = jsonObject.getInteger("roleId");
        Boolean verifyStatus = jsonObject.getBoolean("verifyStatus");
        String remark = jsonObject.getString("remark");

        // 查询需要审核的id
        TaUserVerify userVerify = taUserVerifyMapper.selectById(userVerifyId);
        if (null == userVerify) {
            responseBean.addError("审核不存在！");
            return responseBean;
        }
        if (!"0".equals(userVerify.getVerifyStatus())) {
            responseBean.addError("只能审核待审核状态！");
            return responseBean;
        }

        // 判断当前是否存在审核通过的业主
        // 根据 小区id 、 小区、期、栋、单元、楼层、户号 进行条件查询出 已审核通过的并且是业主
        TaUserVerify ownerUserVerify = taUserVerifyMapper.selectCommunityAndAddress(userVerify.getCommunityId(), userVerify.getPhaseId(), userVerify.getBuildingId(), userVerify.getUnitId(), userVerify.getLevelId(), userVerify.getRoomNoId());
        if (null != ownerUserVerify && roleId.intValue() == 1) {
            responseBean.addSuccess("已存在业主！");
            return responseBean;
        }

        String verify = verifyStatus.booleanValue() == true ? "1" : "2";

        userVerify.setRoleId(roleId);
        userVerify.setVerifyStatus(verify);
        userVerify.setRemark(remark);
        taUserVerifyMapper.updateById(userVerify);

        // app 用户信息
//        TaUser user = taUserMapper.selectById(userVerify.getUserId());

        // 审核通过后，往楼栋资料库添加数据
//        if ("1".equals(verify)) {
//            TpBuildingOwnerInfo tpBuildingOwnerInfo = insertTpBuildingOwnerInfo(userVerify.getPhaseId(), userVerify.getBuildingId(), userVerify.getUnitId(),
//                    userVerify.getLevelId(), userVerify.getRoomNoId(), userElement.getOrgId(), userElement.getUserId(),
//                    userVerify.getGender(), user.getUserName(), user.getLoginName());
//
//            // 设置审核id
//            tpBuildingOwnerInfo.setTaUserVerifyId(userVerify.getId());
//            tpBuildingOwnerInfoMapper.updateById(tpBuildingOwnerInfo);
//
//        }


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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean add(String parameter, TaUser userElement) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        // 角色id
        Integer roleId = jsonObject.getInteger("roleId");
        TpBuildingOwnerInfo tpBuildingOwnerInfo = jsonObject.toJavaObject(TpBuildingOwnerInfo.class);
        // 物业端的用户,也就是正在操作的物业人员
        User user = userMapper.selectById(userElement.getUserId());

        /**
         * 允许有多个手机号，一个业主允许在小区允许有多套房产
         * 一个房号只允许有一个业主
         */

        // 校验楼栋信息表
        TpBuildingOwnerInfo selectBuild = getBuildingInfo(tpBuildingOwnerInfo, userElement.getOrgId());
        if (null != selectBuild) {
            responseBean.addError("该户号，此人员信息已存在!");
            return responseBean;
        }

        TaUser appUser = getByLoginName(tpBuildingOwnerInfo.getOwnerTel());

        TaUser taUser =null;
        // 开始匹配 APP 端用户表
        if (null == appUser) {
            // 如果 APP端 没有这个用户，则自动注册一个
            taUser = new TaUser();
            taUser.setUserName(tpBuildingOwnerInfo.getOwnerName());
            taUser.setLoginName(tpBuildingOwnerInfo.getOwnerTel());
//            taUser.setGender(tpBuildingOwnerInfo.getGender());
//            taUser.setStatus("1");
//            taUser.setRemark("系统自动注册！");
//            taUser.setAcceptAgreementStatus("1");
//            taUser.setVerifyStatus("1");
////            taUserMapper.insert(taUser);
//            taUser.setCreateUser(taUser.getId());
            taUser.setCreateDate(LocalDateTime.now());
//            taUserMapper.updateById(taUser);
            appUser = taUser;
        }

        // 设置 用户性别 和 用户姓名
//        tpBuildingOwnerInfo.setGender(appUser.getGender());
        tpBuildingOwnerInfo.setOwnerName(appUser.getUserName());

        // 插入楼栋资料库
        tpBuildingOwnerInfo = insertTpBuildingOwnerInfo(tpBuildingOwnerInfo.getPhaseId(), tpBuildingOwnerInfo.getBuildingId(), tpBuildingOwnerInfo.getUnitId(),
                tpBuildingOwnerInfo.getLevelId(), tpBuildingOwnerInfo.getRoomNoId(), userElement.getOrgId(), userElement.getUserId(),
                tpBuildingOwnerInfo.getGender(), tpBuildingOwnerInfo.getOwnerName(), tpBuildingOwnerInfo.getOwnerTel());

        // 更新 APP 端用户姓名
        appUser.setUserName(tpBuildingOwnerInfo.getOwnerName());
        appUser.setCreateDate(LocalDateTime.now());
//        appUser.setCreateUser(appUser.getId());

//        int row = taUserMapper.updateById(appUser);
//        if (row <= 0) {
//            log.error("添加操作! 楼栋业主信息表 过程中 更新 APP 端用户姓名失败! ");
//            throw new WisdomException("操作失败!");
//        }

        // 更新 楼栋业主信息表 的认证,关联状态
        // 认证状态  0 是未认证    1是认证通过   2是已作废
        tpBuildingOwnerInfo.setVerifyStatus("1");
        // 关联状态   0 未关联  1 是已关联
        tpBuildingOwnerInfo.setPairStatus("1");
//        row = tpBuildingOwnerInfoMapper.updateById(tpBuildingOwnerInfo);
//        if (row <= 0) {
//            log.error("添加操作! 更新 楼栋业主信息表 的认证,关联状态 失败!");
//            throw new WisdomException("操作失败!");
//        }

        // 根据 小区id 、 小区、期、栋、单元、楼层、户号 进行条件查询出 已审核通过的并且是业主
        TaUserVerify userVerify = taUserVerifyMapper.selectCommunityAndAddress(userElement.getOrgId(), tpBuildingOwnerInfo.getPhaseId(), tpBuildingOwnerInfo.getBuildingId(), tpBuildingOwnerInfo.getUnitId(), tpBuildingOwnerInfo.getLevelId(), tpBuildingOwnerInfo.getRoomNoId());
        if (null != userVerify && roleId.intValue() == 1) {
            responseBean.addSuccess("已存在业主！");
            return responseBean;
        }

        // 审核表中插入一条数据, 审核已通过，并且是业主角色
        TaUserVerify taUserVerify = new TaUserVerify();
//        taUserVerify.setUserId(appUser.getId());
        taUserVerify.setCommunityId(userElement.getOrgId());
        taUserVerify.setRoleId(roleId);
        taUserVerify.setPhaseId(tpBuildingOwnerInfo.getPhaseId());
        taUserVerify.setPhaseName(tpBuildingOwnerInfo.getPhaseName());
        taUserVerify.setBuildingId(tpBuildingOwnerInfo.getBuildingId());
        taUserVerify.setBuildingName(tpBuildingOwnerInfo.getBuildingName());
        taUserVerify.setUnitId(tpBuildingOwnerInfo.getUnitId());
        taUserVerify.setUnitName(tpBuildingOwnerInfo.getUnitName());
        taUserVerify.setLevelId(tpBuildingOwnerInfo.getLevelId());
        taUserVerify.setLevelName(tpBuildingOwnerInfo.getLevelName());
        taUserVerify.setRoomNoId(tpBuildingOwnerInfo.getRoomNoId());
        taUserVerify.setRoomNoName(tpBuildingOwnerInfo.getRoomNoName());
        // 审核通过
        taUserVerify.setVerifyStatus("1");
        taUserVerify.setCreateDate(LocalDateTime.now());
        taUserVerify.setVerifyName(user.getUserName());
//        row = taUserVerifyMapper.insert(taUserVerify);

        tpBuildingOwnerInfo.setTaUserVerifyId(taUserVerify.getId());
//        row = tpBuildingOwnerInfoMapper.updateById(tpBuildingOwnerInfo);
        //推送消息
        String[] messageArr= new messagePush().messagePushAll( );
        for (String count : messageArr) {
            Message message = new Message();
            message.setCommunityId(taUserVerify.getCommunityId());
            message.setMessageType("9");
            message.setAdviceType("1");
            message.setModelType("1");
            message.setUuid(taUserVerify.getId());
            message.setUuidType("1");
            message.setSource("1");
            message.setMessageContent(count);
            message.setStatus("1");
            message.setResult("");
            message.setMeaasgeTypeId("");
            message.setReadStatus("0");
            message.setCreateUser(userElement.getUserId());
            message.setCreateDate(LocalDateTime.now());
            messageMapper.insert(message);
        }

        try {

        } catch (Exception e) {
            log.info("设备推送失败！，人员id：{}", userVerify.getUserId());
            throw new WisdomException("设备推送失败！");
        }

//        if (row <= 0) {
//            throw new WisdomException("操作失败!");
//        } else {
//            responseBean.addSuccess(appUser);
//        }
        return responseBean;
    }

    /**
     * 插入 楼栋资料库
     * @param phaseId
     * @param buildingId
     * @param unitId
     * @param levelId
     * @param roomNoId
     * @param communityId
     * @param userId 创建人
     * @param gender
     * @param ownerName
     * @param ownerTel
     */
    private TpBuildingOwnerInfo insertTpBuildingOwnerInfo (Integer phaseId, Integer buildingId, Integer unitId,
                                                           Integer levelId, Integer roomNoId, Integer communityId,
                                                           Integer userId, String gender, String ownerName, String ownerTel) {
        TpBuildingOwnerInfo tpBuildingOwnerInfo = new TpBuildingOwnerInfo();

        // 查询 期/楼栋/单元/层/户号
        TpPhase phase = tpPhaseMapper.selectById(phaseId);
        TpBuilding building = tpBuildingMapper.selectById(buildingId);
        TpUnit unit = tpUnitMapper.selectById(unitId);
        TpLevel level = tpLevelMapper.selectById(levelId);
        TpRoomNo roomNo = tpRoomNoMapper.selectById(roomNoId);

        // 主键是自增的, 所以设置为 null
        tpBuildingOwnerInfo.setId(null);
        tpBuildingOwnerInfo.setPhaseId(phaseId);
        tpBuildingOwnerInfo.setPhaseName(phase.getName());
        tpBuildingOwnerInfo.setBuildingId(buildingId);
        tpBuildingOwnerInfo.setBuildingName(building.getName());
        tpBuildingOwnerInfo.setUnitId(unitId);
        tpBuildingOwnerInfo.setUnitName(unit.getName());
        tpBuildingOwnerInfo.setLevelId(levelId);
        tpBuildingOwnerInfo.setLevelName(level.getName());
        tpBuildingOwnerInfo.setRoomNoId(roomNoId);
        tpBuildingOwnerInfo.setRoomNoName(roomNo.getName());
        tpBuildingOwnerInfo.setOwnerName(ownerName);
        tpBuildingOwnerInfo.setOwnerTel(ownerTel);
        tpBuildingOwnerInfo.setGender(gender);
        tpBuildingOwnerInfo.setUpdateUser(userId);
        tpBuildingOwnerInfo.setUpdateDate(LocalDateTime.now());
        tpBuildingOwnerInfo.setCreateDate(LocalDateTime.now());
        tpBuildingOwnerInfo.setCreateUser(userId);
        tpBuildingOwnerInfo.setVerifyStatus("0");
        tpBuildingOwnerInfo.setPairStatus("0");

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

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

    /**
     * 修改 APP 端用户的角色
     * @param communityId 小区Id
     * @param appUserId APP 端用户Id
     * @param roleId 角色Id
     */
    private void updateAppRole(Integer communityId, Integer appUserId, Integer roleId) {
        // 更新APP端用户的角色身份
        taSysUserRoleMapper.deleteByCommunityIdAndUserId(communityId, appUserId);
        TaSysUserRole taSysUserRole = new TaSysUserRole();
        taSysUserRole.setUserId(appUserId);
        taSysUserRole.setRoleId(Constant.OWNER_ID);
        taSysUserRole.setCommunityId(communityId);
        taSysUserRoleMapper.insert(taSysUserRole);
    }


    @Override
    public ResponseBean getPhaseList(Integer communityId) {

        ResponseBean responseBean = new ResponseBean();
        if (null == communityId || "".equals(communityId)) {
            throw new WisdomException("编号:%s 小区不存在!", communityId);
        }

        Map<String, Object> map = Maps.newHashMap();
        // 小区
        map.put("community_id", communityId);
        QueryWrapper<TpPhase> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(map, false);
    
        List<TpPhase> tpPhaseList = tpPhaseMapper.selectList(queryWrapper);
        responseBean.addSuccess(tpPhaseList);

        return responseBean;
    }
    
    /**
     * 上传excel里面的内容
     *
     * @param file
     * @param userElement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean submitExcelData(MultipartFile file, TaUser userElement) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = getExcelData(file);

        //获取要上传的数据
        Map<String,Object> map = (Map<String, Object>) responseBean.getData();
        List<TpBuildingOwnerInfo> list = (List<TpBuildingOwnerInfo>) map.get("list");
        
        //批量插入
        // tpBuildingOwnerInfoMapper.batchInsert(list);
        
        //构造数据
        for (TpBuildingOwnerInfo tpBuildingOwnerInfo : list){
            //根据手机号查询这个手机号是否注册
            QueryWrapper<TaUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("login_name", tpBuildingOwnerInfo.getOwnerTel());
//            TaUser taUser = taUserMapper.selectOne(queryWrapper);
//            if (null == taUser){
//                //插入新用户并审核通过
//                addNewUser(tpBuildingOwnerInfo,userElement);
//            }else {
//                //已经有用户的情况下看是否审核通过，是否要添加新的房产
//                checkUserVerify(taUser,tpBuildingOwnerInfo,userElement);
//            }
        }
        responseBean.addSuccess("success");
        return responseBean;
    }
    
    private void checkUserVerify(TaUser taUser, TpBuildingOwnerInfo tpBuildingOwnerInfo, TaUser userElement) {

        //有用户的情况下查看是否有申请的房产
        QueryWrapper<TaUserVerify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id",userElement.getOrgId());
        queryWrapper.eq("user_id",taUser.getUserId());
        List<TaUserVerify> verifyList = taUserVerifyMapper.selectList(queryWrapper);
        AtomicInteger rows = new AtomicInteger();
        if (verifyList.size() > 0){
            verifyList.stream().forEach(e -> {
                if (e.getVerifyStatus().equals("0") &&
                    e.getPhaseId().intValue() == tpBuildingOwnerInfo.getPhaseId().intValue()
                        && e.getBuildingId().intValue() == tpBuildingOwnerInfo.getBuildingId().intValue()
                        && e.getUnitId().intValue() == tpBuildingOwnerInfo.getUnitId().intValue()
                        && e.getLevelId().intValue() == tpBuildingOwnerInfo.getLevelId().intValue()
                        && e.getRoomNoId().intValue() == tpBuildingOwnerInfo.getRoomNoId().intValue() ){

                    e.setVerifyStatus("1");
                    e.setVerifyName(userElement.getUserName());
                    rows.set(taUserVerifyMapper.updateById(e));
                }
            });
            if (rows.get() > 0) {
                return;
            }

        }
        //插入一条房产数据
        saveVerifyData(taUser.getUserId(),tpBuildingOwnerInfo,userElement);
    }
    
    /**
     * 插入新用户并审核通过
     * @param tpBuildingOwnerInfo
     * @param userElement
     */
    private void addNewUser(TpBuildingOwnerInfo tpBuildingOwnerInfo, TaUser userElement) {
        //插入用户
        TaUser taUser = new TaUser();
        taUser.setUserName(tpBuildingOwnerInfo.getOwnerName());
        taUser.setLoginName(tpBuildingOwnerInfo.getOwnerTel());
//        taUser.setStatus("1");
        taUser.setCreateDate(LocalDateTime.now());
//        taUser.setFaceStatus("0");
//        taUserMapper.insert(taUser);
        //审核通过
        saveVerifyData(taUser.getUserId(),tpBuildingOwnerInfo,userElement);
        
    }
    
    private void saveVerifyData(Integer userId, TpBuildingOwnerInfo tpBuildingOwnerInfo, TaUser userElement) {
        TaUserVerify taUserVerify = new TaUserVerify();
        taUserVerify.setUserId(userId);
        taUserVerify.setCommunityId(userElement.getOrgId());
        if (tpBuildingOwnerInfo.getRoleName().equals("户主")){
            taUserVerify.setRoleId(1);
        }else if (tpBuildingOwnerInfo.getRoleName().equals("家属")){
            taUserVerify.setRoleId(3);
        }else if (tpBuildingOwnerInfo.getRoleName().equals("租客")){
            taUserVerify.setRoleId(2);
        }

        // 只允许一个房产中只有一个角色
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectUserVerifyCommunityAndAddress(userId, userElement.getOrgId(), tpBuildingOwnerInfo.getPhaseId(),
                tpBuildingOwnerInfo.getBuildingId(), tpBuildingOwnerInfo.getUnitId(),
                tpBuildingOwnerInfo.getLevelId(), tpBuildingOwnerInfo.getRoomNoId(), 1);
        // 表示这个用户在这个房产中已经有了这个角色, 就不进行插入
        if (CollectionUtils.isNotEmpty(userVerifyList) && userVerifyList.size() > 0) {
            return;
        }

        // 校验这个房产有没有业主，只能存在一个业主
        if (taUserVerify.getRoleId().intValue() == 1) {
            TaUserVerify hasUserVerify = taUserVerifyMapper.selectCommunityAndAddress(userElement.getOrgId(), tpBuildingOwnerInfo.getPhaseId(),
                    tpBuildingOwnerInfo.getBuildingId(), tpBuildingOwnerInfo.getUnitId(),
                    tpBuildingOwnerInfo.getLevelId(), tpBuildingOwnerInfo.getRoomNoId());
            if (null != hasUserVerify) {
                throw new WisdomException(" Excel 第" + tpBuildingOwnerInfo.getIndex() + "行房间已存在户主，请修改为其他身份或删除原户主资料后再导入");
            }
        }


        taUserVerify.setPhaseId(tpBuildingOwnerInfo.getPhaseId());
        taUserVerify.setPhaseName(tpBuildingOwnerInfo.getPhaseName());
        taUserVerify.setBuildingId(tpBuildingOwnerInfo.getBuildingId());
        taUserVerify.setBuildingName(tpBuildingOwnerInfo.getBuildingName());
        taUserVerify.setUnitId(tpBuildingOwnerInfo.getUnitId());
        taUserVerify.setUnitName(tpBuildingOwnerInfo.getUnitName());
        taUserVerify.setLevelId(tpBuildingOwnerInfo.getLevelId());
        taUserVerify.setLevelName(tpBuildingOwnerInfo.getLevelName());
        taUserVerify.setRoomNoId(tpBuildingOwnerInfo.getRoomNoId());
        taUserVerify.setRoomNoName(tpBuildingOwnerInfo.getRoomNoName());
        taUserVerify.setVerifyStatus("1");
        taUserVerify.setCreateDate(LocalDateTime.now());
        taUserVerify.setVerifyName(userElement.getUserName());
        taUserVerifyMapper.insert(taUserVerify);

//        TaUser taUser = taUserMapper.selectById(userId);


        // 通过后，需要往楼栋资料库写入数据
        tpBuildingOwnerInfo.setCommunityId(userElement.getOrgId());
//        tpBuildingOwnerInfo.setIdCard(taUser.getIdCard());
//        tpBuildingOwnerInfo.setGender(taUser.getGender());
        tpBuildingOwnerInfo.setPairStatus("1");
        tpBuildingOwnerInfo.setVerifyStatus("1");
        tpBuildingOwnerInfo.setCreateDate(LocalDateTime.now());
        tpBuildingOwnerInfo.setCreateUser(userElement.getUserId());
        tpBuildingOwnerInfo.setTaUserVerifyId(taUserVerify.getId());

        tpBuildingOwnerInfoMapper.insert(tpBuildingOwnerInfo);
    }
    
    @Override
    public ResponseBean updataApprove(String paramets) {
        ResponseBean response = new ResponseBean();
        JSONObject jsonobject = JSONObject.parseObject(paramets);
        String ownerTel=jsonobject.getString("ownerTel");
        String verifyStatus=jsonobject.getString("verifyStatus");
        TaUser user = new TaUser();
        //用手机号去查当前用户id
//        Integer userId = taUserMapper.getUserID(ownerTel);
//        user.setId(userId);
        int vs = Integer.parseInt(verifyStatus);
        if (1==vs) {
            //停用当前业主认证状态，业主和家属将租客将无法使用
//            user.setVerifyStatus("2");
        }else {
        //启动当前业主，判断业主下是否有关联业主或则家属，如果也关联家属返回有关联的用户，如果没有将可以修改认证状态
//        List<TaUser> userParent=taUserMapper.selectUser(userId);
//        for(TaUser users:userParent){
//            if(null !=users.getParentId()&&userId.equals(users.getParentId())){
//                Map<String, Object> map = Maps.newHashMap();
//                map.put("code","0");
//                map.put("data","有关联的用户");
//                response.addSuccess(map);
//                return response;
//            }
//        }
//            user.setVerifyStatus("1");
        }
//        taUserMapper.updateByPrimaryKeySelective(user);
        return response;
    }

    /**
     * 根据excel获取相关信息
     *
     * @param file
     * @return
     */
    @Override
    public ResponseBean getExcelData(MultipartFile file) {
        ResponseBean responseBean = new ResponseBean();
        List<TpBuildingOwnerInfo> list = new ArrayList<>();
        if (file == null) {
            responseBean.addError("对象不能为空");
            return responseBean;
        }
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        Workbook workbook = null;
        try {
            if (originalFilename.endsWith(Constant.SUFFIX_2003)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFilename.endsWith(Constant.SUFFIX_2007)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (Exception e) {
            logger.info(originalFilename);
            e.printStackTrace();
            responseBean.addError("格式错误");
            return responseBean;
        }
        if (workbook == null) {
            logger.info(originalFilename);
            responseBean.addError("格式错误");
            return responseBean;
        } else {
            List<String> temBuildingList = new ArrayList<String>();
            //获取一个sheet也就是一个工作簿
            Sheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            //从第一行开始第一行一般是标题
            for (int j = 3; j <= lastRowNum; j++) {
                Row row = sheet.getRow(j);
                Cell cell = row.getCell(0);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String buildingInfo = cell.getStringCellValue().trim();
                cell = row.getCell(1);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String roomNoId = cell.getStringCellValue().trim();
                cell = row.getCell(2);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String ownerName = cell.getStringCellValue().trim();
                cell = row.getCell(3);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String ownerTel = cell.getStringCellValue().trim();
                cell = row.getCell(4);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String ownerRole = cell.getStringCellValue().trim();
                int currentRow = j+1;
                if (StringUtils.isEmpty(buildingInfo)){
                    responseBean.addError("第" + currentRow + "行" + "房产信息不能为空!");
                    return responseBean;
                }
                if (StringUtils.isEmpty(roomNoId)){
                    responseBean.addError("第" + currentRow + "行" + "房产ID不能为空!");
                    return responseBean;
                }
                //房产ID不为空的情况下检查房产是否存在
                TpRoomNo tpRoomNo = tpRoomNoMapper.selectById(roomNoId);
                if (null == tpRoomNo){
                    responseBean.addError("第" + currentRow + "行" + "房产ID不存在!");
                    return responseBean;
                }
                if (StringUtils.isEmpty(ownerName)){
                    responseBean.addError("第" + currentRow + "行" + "姓名不能为空!");
                    return responseBean;
                }
                if (StringUtils.isEmpty(ownerTel)){
                    responseBean.addError("第" + currentRow + "行" + "手机号不能为空!");
                    return responseBean;
                }

                if (StringUtils.isEmpty(ownerRole)){
                    responseBean.addError("第" + currentRow + "行" + "身份不能为空!");
                    return responseBean;
                }
    
//                if (temBuildingList.contains(roomNoId)){
//                    logger.info("存在重复房源:{}",roomNoId);
//                    responseBean.addError("第"+ currentRow +"行存在重复房源");
//                    return responseBean;
//                }
                
                //把数据塞入temList校验是否有重复的数据
                temBuildingList.add(roomNoId);
                //构建数据
                TpBuildingOwnerInfo checkOwnerInfo = new TpBuildingOwnerInfo();
                checkOwnerInfo.setId(null);
                checkOwnerInfo.setRoleName(ownerRole);
                checkOwnerInfo.setOwnerName(ownerName);
                checkOwnerInfo.setOwnerTel(ownerTel);
                checkOwnerInfo.setPhaseId(tpRoomNo.getPhaseId());
                checkOwnerInfo.setPhaseName(tpRoomNo.getPhaseName());
                checkOwnerInfo.setBuildingId(tpRoomNo.getBuildingId());
                checkOwnerInfo.setBuildingName(tpRoomNo.getBuildingName());
                checkOwnerInfo.setUnitId(tpRoomNo.getUnitId());
                checkOwnerInfo.setUnitName(tpRoomNo.getUnitName());
                checkOwnerInfo.setLevelId(tpRoomNo.getLevelId());
                checkOwnerInfo.setLevelName(tpRoomNo.getLevelName());
                checkOwnerInfo.setRoomNoId(tpRoomNo.getId());
                checkOwnerInfo.setRoomNoName(tpRoomNo.getName());
                // 记录行数
                checkOwnerInfo.setIndex(currentRow);
                list.add(checkOwnerInfo);
            }
        }
        //构建分页
        Map<String,Object> data = new HashMap<String, Object>();
        data.put("list",list);
        data.put("total",list.size());
        
        responseBean.addSuccess(data);
        return responseBean;
    }
    //判断整数
    public static boolean isNumeric(String str){
    for (int i = str.length();--i>=0;){
        if (!Character.isDigit(str.charAt(i))){
            return false;
        }}
            return true;
        }

    @Override
    public ResponseBean selectUserApprove(String paramets,Integer CommunityId) {

        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonobject = JSONObject.parseObject(paramets);
        Integer pageNum = jsonobject.getInteger("pageNum");
        Integer pageSize = jsonobject.getInteger("pageSize");
        TpBuildingOwnerInfo tpBuildingOwnerInfo = JSONObject.parseObject(paramets, TpBuildingOwnerInfo.class);

        // 分页
        Page<TpBuildingOwnerInfo> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<TpBuildingOwnerInfo> ownerInfoIPage = tpBuildingOwnerInfoMapper.selectUserApprove(page, tpBuildingOwnerInfo.getOwnerName(),tpBuildingOwnerInfo.getOwnerTel(),tpBuildingOwnerInfo.getVerifyStatus(),CommunityId);
        List<TpBuildingOwnerInfo> infoList = ownerInfoIPage.getRecords();
        infoList.stream().forEach(e->{
            if (null!=e.getBuildingName()&&!"".equals(e.getBuildingName())&&isNumeric(e.getBuildingName())){
                e.setBuildingName(e.getBuildingName().length()+"栋");
            }
            if (null!=e.getUnitName()&&!"".equals(e.getUnitName())&&isNumeric(e.getUnitName())){
                e.setUnitName(e.getUnitName()+"单元");
            }
            if (null!=e.getLevelName()&&!"".equals(e.getLevelName())&&isNumeric(e.getLevelName())){
                e.setLevelName(e.getLevelName()+"层");
            }
            if (null!=e.getRoomNoName()&&!"".equals(e.getRoomNoName())&&isNumeric(e.getRoomNoName())){
                e.setRoomNoName(e.getRoomNoName()+"户");
            }
            if (null!=e.getPhaseName()&&!"".equals(e.getPhaseName())&&isNumeric(e.getPhaseName())){
                e.setPhaseName(e.getPhaseName()+"期");
            }
        });

        Map<String, Object> map = Maps.newHashMap();
        map.put("list", infoList);
        map.put("total", ownerInfoIPage.getTotal());
        map.put("pageNum", ownerInfoIPage.getCurrent());
        map.put("pageSize", ownerInfoIPage.getSize());

        responseBean.addSuccess(map);

        return responseBean;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    @Deprecated
//    public ResponseBean deleteIds(List<Integer> ids, Integer propertyUserId) {
//
//        ResponseBean responseBean = new ResponseBean();
//
//        List<TpBuildingOwnerInfo> infoList = ids.stream().map(e->{
//            TpBuildingOwnerInfo tpBuildingOwnerInfo = new TpBuildingOwnerInfo();
//            tpBuildingOwnerInfo.setId(e);
//            tpBuildingOwnerInfo.setVerifyStatus("2");
//            tpBuildingOwnerInfo.setUpdateUser(propertyUserId);
//            tpBuildingOwnerInfo.setUpdateDate(LocalDateTime.now());
//            return tpBuildingOwnerInfo;
//        }).collect(Collectors.toList());
//        boolean result = updateBatchById(infoList);
//
//        // APP 端用户
//        List<TaUser> taUserList = Lists.newArrayList();
//
//        ids.forEach(e-> {
//            TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectById(e);
//            if (null != tpBuildingOwnerInfo) {
//                // 查询 APP 端业主
//                TaUser appOwnerUser = getByIdAndCommunityId(tpBuildingOwnerInfo.getOwnerTel(), tpBuildingOwnerInfo.getCommunityId());
//                if (null != appOwnerUser) {
//                    appOwnerUser.setVerifyStatus(2+"");
//                    appOwnerUser.setUpdateDate(LocalDateTime.now());
//                    taUserList.add(appOwnerUser);
//                }
//
//            }
//        });
//
//        if (null != taUserList && taUserList.size() > 0) {
//            result = iTaUserService.updateBatchById(taUserList);
//        }
//
//
//        if (result) {
//            responseBean.addSuccess("操作成功!");
//        }else {
//            responseBean.addError("操作失败!");
//        }
//
//
//        return responseBean;
//    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteIds(List<Integer> ids, Integer propertyUserId) {

        /**
         * 楼栋资料删除的是 审核表里面的数据
         */

        ResponseBean responseBean = new ResponseBean();
        ids.stream().forEach(e->{
            QueryWrapper<TpBuildingOwnerInfo> buildingOwnerInfoQueryWrapper = new QueryWrapper<>();
            buildingOwnerInfoQueryWrapper.eq("ta_user_verify_id", e);
            TpBuildingOwnerInfo tpBuildingOwnerInfo = tpBuildingOwnerInfoMapper.selectOne(buildingOwnerInfoQueryWrapper);
            if (null != tpBuildingOwnerInfo) {
                tpBuildingOwnerInfoMapper.deleteById(tpBuildingOwnerInfo.getId());
            }
            taUserVerifyMapper.deleteById(e);

            // 作废话题
            tpTransactionMapper.invalidByUuidAndUuidType(e, "app");

        });

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

    @Override
    public ResponseBean buildinglist(String paramets, TaUser userElement) {
        ResponseBean responseBean= new ResponseBean();

        TpBuilding   tpBuilding= JSONObject.parseObject(paramets, TpBuilding.class);
        JSONObject object= JSONObject.parseObject(paramets);

        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        Page<TpBuilding> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<TpBuilding> pageInfo = tpBuildingMapper.buildinglist(page,tpBuilding);
        List<TpBuilding> tpBuildingList = pageInfo.getRecords();

        Map<String, Object> map = Maps.newHashMap();
        map.put("list", tpBuildingList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        responseBean.addSuccess(map);
        return responseBean;
    }

    @Override
    public ResponseBean puildinghouse(String parameter, Integer communityId) {
        return null;
    }

    @Override
    public ResponseBean communitybuildingUpdate(String parameter, Integer communityId) {
        return null;
        };


    /**
     * 根据 手机号  查询用户
     * @param phone
     * @return
     */
    private TaUser getByLoginName(String phone){
        // 开始匹配 APP 端用户表
        QueryWrapper<TaUser> taUserQueryWrapper = new QueryWrapper<>();
        taUserQueryWrapper.eq("login_name", phone);
        // 查询 APP 端业主
//        TaUser appOwnerUser = taUserMapper.selectOne(taUserQueryWrapper);

        return null;
    }

    /**
     * 查询 楼栋信息
     *      根据小区Id, 栋,单元,楼层,房号
     * @param tpBuildingOwnerInfo 楼栋信息
     * @param communityId 小区Id
     * @return
     */
    private TpBuildingOwnerInfo getBuildingInfo(TpBuildingOwnerInfo tpBuildingOwnerInfo, Integer communityId) {
        // 校验楼栋信息表
        QueryWrapper<TpBuildingOwnerInfo> queryWrapper = new QueryWrapper<>();
        // 小区ID
        queryWrapper.eq("community_id", communityId);
        // 期
        queryWrapper.eq("phase_id", tpBuildingOwnerInfo.getPhaseId());
        // 栋
        queryWrapper.eq("building_id", tpBuildingOwnerInfo.getBuildingId());
        // 单元
        queryWrapper.eq("unit_id", tpBuildingOwnerInfo.getUnitId());
        // 楼层
        queryWrapper.eq("level_id", tpBuildingOwnerInfo.getLevelId());
        // 房号
        queryWrapper.eq("room_no_id", tpBuildingOwnerInfo.getRoomNoId());
        // 手机号
        queryWrapper.eq("owner_tel", tpBuildingOwnerInfo.getOwnerTel());
        TpBuildingOwnerInfo selectBuild = tpBuildingOwnerInfoMapper.selectOne(queryWrapper);

        return selectBuild;
    }

    @Override
    public ResponseBean downloadExcel(TaUser userElement) {
        ResponseBean responseBean = new ResponseBean();

        InputStream inputStream = null;
        inputStream = this.getClass().getResourceAsStream("/业主资料库.xlsx");

        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        XSSFSheet sheet = workbook.getSheetAt(0);
        // 创建行
        XSSFRow row = null;
        // 创建列
        XSSFCell cell = null;

        Integer pageNum = 0;
        Integer pageSize = 10;

        // 分页查询
        List<TpRoomNo> records = tpRoomNoMapper.selectCommunityIdList(userElement.getOrgId(),pageNum * pageSize, pageSize);
        // 总页数
        Long pages = tpRoomNoMapper.selectCommunityIdCount(userElement.getOrgId());


        // 行数 默认从 第 3 行开始
        int currentRow = 3;
        // 记录坐标
        int index = 0;

        // 样式
        XSSFCellStyle cellStyle = workbook.createCellStyle();
//        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
//        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
//        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
//        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        cellStyle.setAlignment(HorizontalAlignment.LEFT);

        if (records.size() > 0) {
            do {
                TpRoomNo tpRoomNo = records.get(index);
                row = sheet.createRow(currentRow);
                String address = tpRoomNo.getPhaseName() +
                        tpRoomNo.getBuildingName() +
                        tpRoomNo.getUnitName() +
                        tpRoomNo.getLevelName() +
                        tpRoomNo.getName();

                cell = row.createCell(0);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue(address);
                cell.setCellStyle(cellStyle);
                cell = row.createCell(1);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue(tpRoomNo.getId());
                cell.setCellStyle(cellStyle);
                cell = row.createCell(2);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(cellStyle);
                cell = row.createCell(3);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(cellStyle);
                cell = row.createCell(4);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(cellStyle);

                currentRow ++;
                index ++;
                if (index == records.size()) {
                    index = 0;
                    pageNum ++;
                    records = tpRoomNoMapper.selectCommunityIdList(userElement.getOrgId(),pageNum * pageSize, pageSize);
                }
                if (records.isEmpty()) {
                    break;
                }
            } while (pageNum <= pages);
        }

        responseBean.addSuccess(workbook);
        return responseBean;
    }
    
    /**
     * 获取楼栋信息
     *
     * @param phaseId
     * @param communityId
     * @return
     */
    @Override
    public ResponseBean getBuildingList(Integer phaseId, Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        if (null == communityId || "".equals(communityId)) {
            throw new WisdomException("编号:%s 小区不存在!", communityId);
        }
    
        QueryWrapper<TpBuilding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId);
        queryWrapper.eq("phase_id", phaseId);
    
        List<TpBuilding> tpBuildingList = tpBuildingMapper.selectList(queryWrapper);
        responseBean.addSuccess(tpBuildingList);
    
        return responseBean;
    }
    
    /**
     * 获取单元信息
     *
     * @param buildingId
     * @param communityId
     * @return
     */
    @Override
    public ResponseBean getUnitList(Integer buildingId, Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        if (null == communityId || "".equals(communityId)) {
            throw new WisdomException("编号:%s 小区不存在!", communityId);
        }
    
        QueryWrapper<TpUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId);
        queryWrapper.eq("building_id", buildingId);
    
        List<TpUnit> tpUnitList = tpUnitMapper.selectList(queryWrapper);
        responseBean.addSuccess(tpUnitList);
    
        return responseBean;
    }
    
    /**
     * 获取楼层信息
     *
     * @param unitId
     * @param communityId
     * @return
     */
    @Override
    public ResponseBean getLevelList(Integer unitId, Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        if (null == communityId || "".equals(communityId)) {
            throw new WisdomException("编号:%s 小区不存在!", communityId);
        }
    
        QueryWrapper<TpLevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId);
        queryWrapper.eq("unit_id", unitId);
    
        List<TpLevel> tpLevelList = tpLevelMapper.selectList(queryWrapper);
        responseBean.addSuccess(tpLevelList);
    
        return responseBean;
    }
    
    /**
     * 获取室号信息
     *
     * @param levelId
     * @param communityId
     * @return
     */
    @Override
    public ResponseBean getRoomNoList(Integer levelId, Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        if (null == communityId || "".equals(communityId)) {
            throw new WisdomException("编号:%s 小区不存在!", communityId);
        }
    
        QueryWrapper<TpRoomNo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId);
        queryWrapper.eq("level_id", levelId);
    
        List<TpRoomNo> tpLevelList = tpRoomNoMapper.selectList(queryWrapper);
        responseBean.addSuccess(tpLevelList);
    
        return responseBean;
    }

    @Override
    public ResponseBean buildingDetails(String paramets, TaUser userElement) {
        ResponseBean response= new ResponseBean();
        JSONObject object= JSONObject.parseObject(paramets);
        Integer id= object.getInteger("id");

        TaUserVerify taUserVerify= taUserVerifyMapper.selectById(id);
        //根据当前userid查询ta_user
//        TaUser  taUser= taUserMapper.selectById(taUserVerify.getUserId());
        //查询当前的身份
        String description= taSysRoleMapper.selectByPrimaryKey(taUserVerify.getRoleId()).getDescription();
//        taUser.setDescription(description);

        //查询人脸
        QueryWrapper<TaFace> taFace= new QueryWrapper<>();
        taFace.eq("community_id",taUserVerify.getCommunityId());
        taFace.eq("ta_user_verify_id",id);
        TaFace face= taFaceMapper.selectOne(taFace);
        if(null!=face) {
            taUserVerify.setFaceImg(face.getFaceImg());
        }
        // 查询多套关联房产
        QueryWrapper<TaUserVerify> taUserVerifyQueryWrapper= new QueryWrapper<>();
//        taUserVerifyQueryWrapper.eq("user_id",taUser.getId());
        taUserVerifyQueryWrapper.eq("verify_status",1);
        List<TaUserVerify> taUserVerifyList= taUserVerifyMapper.selectList(taUserVerifyQueryWrapper);
        List<String> roomInfoList= new ArrayList<>();
        for (TaUserVerify roomInfo:taUserVerifyList){
            //组装-期/楼栋/单元/楼层/户号
            roomInfoList.add(roomInfo.getPhaseName()
            +roomInfo.getBuildingName()
            +roomInfo.getUnitName()
            +roomInfo.getLevelName()
            +roomInfo.getRoomNoName());
        }
        Map<String, Object> map = Maps.newHashMap();
        /*当前房产信息*/
        map.put("taUserVerify",taUserVerify);
        /*个人信息*/
//        map.put("taUser",taUser);
        /*房屋列表*/
        map.put("roomInfoList",roomInfoList);
        response.addSuccess(map);
        return response;
    }
}
