package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.biz.dal.dao.StudentDao;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.entity.SysArea;
import com.yonge.cooleshow.biz.dal.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.entity.TenantInfo;
import com.yonge.cooleshow.biz.dal.entity.TenantStaff;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.mapper.SysUserMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantApplyRecordMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantEntryRecordMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantInfoMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantStaffMapper;
import com.yonge.cooleshow.biz.dal.service.SysAreaService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.service.TenantInfoService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantInfoWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.SysUserType;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.utils.obj.ObjectUtil;
import feign.Client;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 机构表
 * 2023-07-21 17:26:59
 */
@Slf4j
@Service
public class TenantInfoServiceImpl extends ServiceImpl<TenantInfoMapper, TenantInfo> implements TenantInfoService {
    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    TenantInfoMapper tenantInfoMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private TenantStaffMapper tenantStaffMapper;

    @Autowired
    TenantEntryRecordMapper tenantEntryRecordMapper;

    @Autowired
    TenantApplyRecordMapper tenantApplyRecordMapper;

    @Autowired
    TenantInfoService tenantInfoService;


    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private SysUserFeignService sysUserFeignService;


    /**
     * 查询详情
     *
     * @param id 详情ID
     * @return TenantInfo
     */
    @Override
    public TenantInfo detail(Long id) {
        if (id == null || id == -1) {
            return null;
        }

        TenantInfo info = baseMapper.selectById(id);
        return info;
    }


    /**
     * 查询机构详情
     *
     * @param id 详情ID
     * @return TenantInfo
     */
    @Override
    public TenantInfoWrapper.TenantInfo detailTenantInfo(Long id) {
        if (id == null || id == -1) {
            return null;
        }
        TenantInfo info = baseMapper.selectById(id);
        TenantInfoWrapper.TenantInfo tenantInfo = JSON.parseObject(JSON.toJSONString(info), TenantInfoWrapper.TenantInfo.class);

        //查询对应老师数量
        Integer teacherCounts = teacherDao.queryTeacherCounts(id);

        //查询对应学生数量
        Integer studentCounts = studentDao.queryStudentCounts(id);


        tenantInfo.setTeacherCounts(teacherCounts);
        tenantInfo.setStudentCounts(studentCounts);

        //获取省市区信息
        Set<Integer> codes = new HashSet<>();
        codes.add(tenantInfo.getCityCode());
        codes.add(tenantInfo.getProvinceCode());
        codes.add(tenantInfo.getRegionCode());

        //将地区码转化为对应的地名
        List<Integer> areaCodeList = new ArrayList<>();
        areaCodeList.addAll(codes);

        Map<Integer, String> codeNameMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(areaCodeList)) {
            List<SysArea> sysAreaList = sysAreaService.queryByCodes(areaCodeList);
            codeNameMap = sysAreaList.stream().collect(Collectors.toMap(SysArea::getCode,
                    SysArea::getName));
        }

        tenantInfo.setProvinceName(codeNameMap.get(tenantInfo.getProvinceCode()));
        tenantInfo.setCityName(codeNameMap.get(tenantInfo.getCityCode()));
        tenantInfo.setRegionName(codeNameMap.get(tenantInfo.getRegionCode()));


        return tenantInfo;
    }

    /**
     * 分页查询
     *
     * @param query TenantInfoWrapper.TenantInfoQuery
     * @return IPage<TenantInfo>
     */
    @Override
    public IPage<TenantInfoWrapper.TenantInfo> selectPage(TenantInfoWrapper.TenantInfoQuery query) {

        //分页查询
        IPage<TenantInfoWrapper.TenantInfo> page = QueryInfo.getPage(query);
        List<TenantInfoWrapper.TenantInfo> tenantInfos = baseMapper.selectPage(page, query);
        if (tenantInfos.isEmpty()) {
            return page.setRecords(new ArrayList<>());
        }

        List<Long> tenantIdList =
                tenantInfos.stream().map(TenantInfoWrapper.TenantInfo::getId).collect(Collectors.toList());

        List<TenantInfoWrapper.UserCount> teacherByTenantIds = teacherDao.countTeacherByTenantIds(tenantIdList);
        List<TenantInfoWrapper.UserCount> studentByTenantIds = studentDao.countTeacherByTenantIds(tenantIdList);

        Map<Long, Integer> teacherIdCountMap = teacherByTenantIds.stream()
                .collect(Collectors.toMap(TenantInfoWrapper.UserCount::getTenantId,
                        TenantInfoWrapper.UserCount::getCount));

        Map<Long, Integer> studentIdCountMap = studentByTenantIds.stream()
                .collect(Collectors.toMap(TenantInfoWrapper.UserCount::getTenantId,
                        TenantInfoWrapper.UserCount::getCount));


        for (TenantInfoWrapper.TenantInfo info : tenantInfos) {
            info.setTeacherCounts(teacherIdCountMap.getOrDefault(info.getId(), 0));
            info.setStudentCounts(studentIdCountMap.getOrDefault(info.getId(), 0));
        }

        //获取省市区信息
        List<TenantInfoWrapper.TenantInfo> tenantList = queryArea(tenantInfos);
        return page.setRecords(tenantList);
    }


    /**
     * 新增
     *
     * @param tenantInfo TenantInfoWrapper.TenantInfo
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(TenantInfo tenantInfo) {
        TenantInfo oldInfo =new TenantInfo();
        //查询要新增的信息 是否存在机构
        String phone = tenantInfo.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            List<TenantInfo> list = tenantInfoService.lambdaQuery().eq(TenantInfo::getPhone, phone).list();
            if (CollectionUtils.isNotEmpty(list)){
                throw new BizException("手机号已经注册机构账号");
            }
        }


        SysUser sysUser = getOrCreateAccount(tenantInfo, oldInfo);
        tenantInfo.setEnableFlag(true);
        if (StringUtils.isEmpty(tenantInfo.getLogo())) {
            // todo 设置默认logo
            tenantInfo.setLogo(sysConfigService.findConfigValue(SysConfigConstant.TENANT_DEFAULT_HEAD));
        }
        tenantInfo.setEnableFlag(true);
        tenantInfo.setUserId(sysUser.getId());
        tenantInfo.setUsername(sysUser.getUsername());
        tenantInfoMapper.insert(tenantInfo);

        TenantStaff tenantStaff = new TenantStaff();
        tenantStaff.setTenantId(tenantInfo.getId());
        tenantStaff.setUserId(sysUser.getId());
        tenantStaff.setAvatar(sysUser.getAvatar());
        tenantStaff.setNickname(tenantInfo.getUsername());
        tenantStaff.setStatus(UserLockFlag.NORMAL);
        tenantStaff.setManageAdmin(true);
        tenantStaffMapper.insert(tenantStaff);
        return true;
    }

    private SysUser getOrCreateAccount(TenantInfo tenantInfo, TenantInfo oldTenantInfo) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getPhone, tenantInfo.getPhone());
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserQueryWrapper);
        SysUser sysUser;
        //若存在信息
        if (!sysUsers.isEmpty()) {
            sysUser = sysUsers.get(0);
            TenantStaff tenantStaff = tenantStaffMapper.selectByUserId(sysUser.getId());
            if ( !ObjectUtil.isEmpty(tenantStaff) && !ObjectUtil.isEmpty(oldTenantInfo) &&
                    !tenantInfo.getPhone().equals(oldTenantInfo.getPhone())) {
                throw new BizException("手机号已经注册机构账号");
            }
            //获取当前账户的用户类型
            String userType = sysUser.getUserType();

//            if (userType.contains(SysUserType.SYSTEM.getCode())){
//                throw new BizException("该手机号已注册平台员工");
//            }
            //设置默认机构类型
            String tenantUserType = SysUserType.ORGANIZATION.getCode();
            if (StringUtils.isEmpty(userType)) {
                sysUser.setUserType(tenantUserType);
            } else if (!userType.contains(tenantUserType)) {
                sysUser.setUserType(userType + "," + tenantUserType);
            }

            //更新当前账号的用户名
            sysUser.setUsername(tenantInfo.getUsername());

            sysUserMapper.updateById(sysUser);
        } else {
            sysUser = new SysUser();
            sysUser.setPhone(tenantInfo.getPhone());
            sysUser.setAvatar(sysConfigService.findConfigValue(SysConfigConstant.TEACHER_AVATAR));
            sysUser.setUserType(SysUserType.ORGANIZATION.getCode());
            sysUser.setUsername(tenantInfo.getUsername());
//            String newPassword = MessageFormat.format("klxjg{0}", tenantInfo.getPhone().substring(7));
//            String password = new BCryptPasswordEncoder().encode(newPassword);
            //sysUser.setPassword(password);
            sysUserMapper.insert(sysUser);
        }
        return sysUser;
    }

    private SysUser getUpdateAccount(TenantInfo tenantInfo, TenantInfo oldTenantInfo) {
        SysUser sysUser = new SysUser();
        com.yonge.cooleshow.auth.api.entity.SysUser newSysUser = sysUserMapper.findUserByPhone(tenantInfo.getPhone());
        if (!tenantInfo.getPhone().equals(oldTenantInfo.getPhone())) {
            if (newSysUser != null) {
                throw new BizException("手机号已经注册平台账号");
            } else {
                com.yonge.cooleshow.auth.api.entity.SysUser oldSysUser = sysUserMapper.findUserByPhone(oldTenantInfo.getPhone());
                sysUser.setId(oldSysUser.getId());
            }
        } else {
            sysUser.setId(newSysUser.getId());
        }
        sysUser.setPhone(tenantInfo.getPhone());
        sysUser.setUsername(tenantInfo.getUsername());
        sysUserMapper.updateById(sysUser);
        return sysUser;
    }



    private SysUser getAccount(TenantInfo tenantInfo, TenantInfo oldTenantInfo) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getPhone, tenantInfo.getPhone());
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserQueryWrapper);
        SysUser sysUser = new SysUser();
        //若存在信息
        if (!sysUsers.isEmpty()) {
            sysUser = sysUsers.get(0);
            TenantStaff tenantStaff = tenantStaffMapper.selectByUserId(sysUser.getId());
            if (tenantStaff != null && oldTenantInfo != null &&
                    !tenantStaff.getUserId().equals(oldTenantInfo.getUserId())) {
                throw new BizException("手机号已经注册机构账号");
            }
            //获取当前账户的用户类型
            String userType = sysUser.getUserType();
            //设置默认机构类型
            String tenantUserType = SysUserType.ORGANIZATION.getCode();
            if (StringUtils.isEmpty(userType)) {
                sysUser.setUserType(tenantUserType);
            } else if (!userType.contains(tenantUserType)) {
                sysUser.setUserType(userType + "," + tenantUserType);
            }

            //更新当前账号的用户名
            sysUser.setUsername(tenantInfo.getUsername());

            sysUserMapper.updateById(sysUser);
        }
        return sysUser;
    }



    /*@Override
    public Boolean add(TenantInfoWrapper.TenantInfo tenantInfo) {    	
        
        return this.save(JSON.parseObject(tenantInfo.jsonString(), TenantInfo.class));
    }*/


    /*@Override
    public Boolean update(TenantInfoWrapper.TenantInfo tenantInfo){

        return this.updateById(JSON.parseObject(tenantInfo.jsonString(), TenantInfo.class));       
    }*/

    /**
     * 机构信息
     *
     * @param tenantIds 机构ID
     */
    @Override
    public Map<Long, TenantInfo> getMapByIds(List<Long> tenantIds) {
        if (CollectionUtils.isEmpty(tenantIds)) {
            return new HashMap<>();
        }
        List<TenantInfo> list = this.lambdaQuery()
                .in(TenantInfo::getId, tenantIds)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.toMap(TenantInfo::getId, tenantInfo -> tenantInfo));
    }

    @Override
    public HttpResponseResult<Boolean> submit(TenantInfoWrapper.TenantInfoQuery query) {
        return null;
    }

    /**
     * 修改状态
     *
     * @param updateStatus updateStatus
     * @return true
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateStatus(TenantInfoWrapper.UpdateStatus updateStatus) {

        boolean update = this.lambdaUpdate()
                .set(TenantInfo::getEnableFlag, updateStatus.getEnableFlag())
                .eq(TenantInfo::getId, updateStatus.getId())
                .update();
        if (!update) {
            throw new BizException("机构信息不存在");
        }

        if (!updateStatus.getEnableFlag()) {
            // 账号退出登录
            QueryWrapper<TenantStaff> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(TenantStaff::getTenantId, updateStatus.getId());
            List<TenantStaff> tenantStaffs = tenantStaffMapper.selectList(queryWrapper);
            List<Long> userIdList = tenantStaffs.stream().map(TenantStaff::getUserId).collect(Collectors.toList());
            Map<Long, String> idPhoneMap = sysUserMapper.selectBatchIds(userIdList).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getPhone));
            tenantStaffs.stream().filter(next -> StringUtils.isNotEmpty(next.getWxOpenid()))
                    .forEach(staff -> sysUserFeignService.exitByPhoneAndOpenId(ClientEnum.ORGANIZATION.getCode().toLowerCase(),
                            idPhoneMap.get(staff.getUserId()), staff.getWxOpenid()));

            tenantStaffMapper.update(null, Wrappers.<TenantStaff>lambdaUpdate()
                    .set(TenantStaff::getStatus, UserLockFlag.LOCKED)
                    .set(TenantStaff::getWxOpenid, null)
                    .eq(TenantStaff::getTenantId, updateStatus.getId()));
        } else {
            tenantStaffMapper.update(null, Wrappers.<TenantStaff>lambdaUpdate()
                    .set(TenantStaff::getStatus, UserLockFlag.NORMAL)
                    .eq(TenantStaff::getTenantId, updateStatus.getId()));
        }



        if (updateStatus.getSettlement() != null) {
            teacherDao.update(null, Wrappers.<Teacher>lambdaUpdate()
                    .set(Teacher::getSettlementFrom, updateStatus.getSettlement())
                    .eq(Teacher::getTenantId, updateStatus.getId()));
        }
        return true;
    }


    /**
     * 更新
     *
     * @param info TenantInfoWrapper.TenantInfo
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean update(TenantInfo info) {
        // todo  机构冻结状态是否允许修改
        //更新或创建sysUser
        TenantInfo oldTenantInfo = this.getById(info.getId());
        SysUser sysUser = getUpdateAccount(info, oldTenantInfo);

        if (sysUser.getId() != null){
            tenantStaffMapper.update(null, Wrappers.<TenantStaff>lambdaUpdate()
                .set(TenantStaff::getUserId, sysUser.getId())
                .set(TenantStaff::getNickname, info.getUsername())
                .eq(TenantStaff::getUserId, oldTenantInfo.getUserId())
        );}


        if (StringUtils.isEmpty(info.getLogo())) {
            // todo 设置默认logo
            info.setLogo(sysConfigService.findConfigValue(SysConfigConstant.TENANT_DEFAULT_HEAD));
        }

        //判断修改手机号后所属
        if (!info.getPhone().equals(oldTenantInfo.getPhone())) {
            // 清除登录token信息
            TenantStaff tenantStaff = tenantStaffMapper.selectByUserId(sysUser.getId());
            if(tenantStaff != null){
                sysUserFeignService.exitByPhoneAndOpenId(ClientEnum.ORGANIZATION.getCode().toLowerCase(),
                        oldTenantInfo.getPhone(),tenantStaff.getWxOpenid());
                // 清除WXOpenId
                tenantStaffMapper.update(null, Wrappers.<TenantStaff>lambdaUpdate()
                        .set(TenantStaff::getWxOpenid, null)
                        .eq(TenantStaff::getUserId, sysUser.getId()));
            }
        }
        tenantInfoMapper.update(null, Wrappers.<TenantInfo>lambdaUpdate()
                .set(TenantInfo::getName, info.getName())
                .set(TenantInfo::getLogo, info.getLogo())
                .set(TenantInfo::getBriefIntroduction, info.getBriefIntroduction())
                .set(TenantInfo::getProvinceCode, info.getProvinceCode())
                .set(TenantInfo::getCityCode, info.getCityCode())
                .set(TenantInfo::getRegionCode, info.getRegionCode())
                .set(TenantInfo::getPhone, info.getPhone())
                .set(TenantInfo::getUsername, info.getUsername())
                .set(TenantInfo::getUserId,sysUser.getId())
                .eq(TenantInfo::getId, info.getId())
        );
        return true;
    }


    /**
     * 机构申请分页查询
     *
     * @param query
     * @return
     */
    @Override
    public IPage<TenantInfoWrapper.TenantInfo> applyPage(IPage<TenantInfoWrapper.TenantInfo> page,
                                                         TenantInfoWrapper.TenantInfoQuery query) {
        //分页查询
        List<TenantInfoWrapper.TenantInfo> tenantInfos = baseMapper.selectApplyPage(page, query);
        List<TenantInfoWrapper.TenantInfo> infos = queryArea(tenantInfos);
        return page.setRecords(infos);
    }


    /**
     * 机构入驻审核历史记录查询
     *
     * @param query
     * @return
     */
    @Override
    public IPage<TenantInfoWrapper.TenantInfo> historyPage(IPage<TenantInfoWrapper.TenantInfo> page,
                                                           TenantInfoWrapper.TenantInfoQuery query) {
//        long id = query.getId();
//        //分页查询
//        List<TenantInfoWrapper.TenantInfo> tenantInfos = baseMapper.selectHistoryPage(page, id);
//        //查询对应省市区
//        List<TenantInfoWrapper.TenantInfo> infos = queryArea(tenantInfos);
//
//        return page.setRecords(infos);
        return null;
    }

    /**
     * 机构入驻审核本次提交查询
     *
     * @param query
     * @return
     */
    @Override
    public TenantInfoWrapper.TenantInfo queryNow(TenantInfoWrapper.TenantInfoQuery query) {
        //查询本次提交记录
        TenantInfoWrapper.TenantInfo info = tenantInfoMapper.queryNow(query);
        Set<Integer> codes = new HashSet<>();
        codes.add(info.getCityCode());
        codes.add(info.getProvinceCode());
        codes.add(info.getRegionCode());

        //将地区码转化为对应的地名
        List<Integer> areaCodeList = new ArrayList<>();
        areaCodeList.addAll(codes);

        Map<Integer, String> codeNameMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(areaCodeList)) {
            List<SysArea> sysAreaList = sysAreaService.queryByCodes(areaCodeList);
            codeNameMap = sysAreaList.stream().collect(Collectors.toMap(SysArea::getCode,
                    SysArea::getName));
        }

        info.setProvinceName(codeNameMap.get(info.getProvinceCode()));
        info.setCityName(codeNameMap.get(info.getCityCode()));
        info.setRegionName(codeNameMap.get(info.getRegionCode()));
        return info;
    }

    @Override
    public Boolean entry(TenantInfoWrapper.TenantInfoQuery query) {
//        Integer pass = query.getIfPass();
//        //审核通过
//        if (pass == 1) {
//            //查询本次提交记录，并插入审核表
//            TenantInfoWrapper.TenantInfo info = queryNow(query);
//            TenantEntryRecord entryRecord = new TenantEntryRecord();
//            entryRecord.setId(info.getId());
//            entryRecord.setName(info.getName());
//            entryRecord.setLogo(info.getLogo());
//            entryRecord.setProvinceCode(info.getProvinceCode());
//            entryRecord.setCityCode(info.getCityCode());
//            entryRecord.setRegionCode(info.getRegionCode());
//            entryRecord.setUsername(info.getUserName());
//            entryRecord.setPhone(info.getPhone());
//            entryRecord.setStatus("PASS");
//            entryRecord.setVerifyUserId(info.getVerifyUserId());
//            entryRecord.setReason(info.getReason());
//            entryRecord.setCreateTime(info.getCreateTime());
//            tenantEntryRecordMapper.insert(entryRecord);
//            //更改当前记录的审核状态
//            long id = info.getId();
//            tenantInfoMapper.updateStatusById(id);
//
//            //机构账户新增逻辑
//            TenantInfo tenantInfo = new TenantInfo();
//            tenantInfo.setId(info.getId());
//            tenantInfo.setLogo(info.getLogo());
//            tenantInfo.setName(info.getName());
//            tenantInfo.setProvinceCode(info.getProvinceCode());
//            tenantInfo.setCityCode(info.getCityCode());
//            tenantInfo.setRegionCode(info.getRegionCode());
//            tenantInfo.setUsername(info.getUserName());
//            tenantInfo.setPhone(info.getPhone());
//            tenantInfo.setEnableFlag(true);
//            tenantInfo.setBriefIntroduction(info.getBriefIntroduction());
//            tenantInfo.setUpdateTime(info.getUpdateTime());
//            tenantInfo.setCreateTime(info.getCreateTime());
//            add(tenantInfo);
//
//
//        } else {
//            //查询本次提交记录，并插入审核表
//            TenantInfoWrapper.TenantInfo info = queryNow(query);
//            TenantEntryRecord entryRecord = new TenantEntryRecord();
//            entryRecord.setId(info.getId());
//            entryRecord.setName(info.getName());
//            entryRecord.setLogo(info.getLogo());
//            entryRecord.setProvinceCode(info.getProvinceCode());
//            entryRecord.setCityCode(info.getCityCode());
//            entryRecord.setRegionCode(info.getRegionCode());
//            entryRecord.setUsername(info.getUserName());
//            entryRecord.setPhone(info.getPhone());
//            entryRecord.setStatus("UNPASS");
//            entryRecord.setVerifyUserId(info.getVerifyUserId());
//            entryRecord.setReason(info.getReason());
//            entryRecord.setCreateTime(info.getCreateTime());
//            tenantEntryRecordMapper.insert(entryRecord);
//            //更改当前记录的审核状态
//            long id = info.getId();
//            tenantInfoMapper.updateUnpassStatusById(id);
//        }
        return true;
    }

    @Override
    public TenantInfoWrapper.TenantInfo Infodetail(Long id) {
//        if (id == null || id == -1) {
//            return null;
//        }
//        TenantInfoWrapper.TenantInfo info = tenantInfoMapper.selectInfoById(id);
//
//        info.setStudentCounts(tenantInfoMapper.queryStudentCount(id));
//        info.setTeacherCounts(tenantInfoMapper.queryTeacherCount(id));
//        return info;
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateTenantInfo(TenantInfo info, Long tenantId) {
        boolean update = this.lambdaUpdate().set(TenantInfo::getName, info.getName())
                .set(TenantInfo::getLogo, info.getLogo())
                .set(TenantInfo::getBriefIntroduction, info.getBriefIntroduction())
                .set(TenantInfo::getProvinceCode, info.getProvinceCode())
                .set(TenantInfo::getCityCode, info.getCityCode())
                .set(TenantInfo::getRegionCode, info.getRegionCode())
                .eq(TenantInfo::getId, tenantId).update();
        return update;
    }

    @Override
    public Boolean updateSysUser(SysUser sysUser, Long id) {
        sysUser.setId(id);
        sysUserMapper.updateById(sysUser);
        return true;
    }


    /**
     * 匹配地区码与省市区
     *
     * @param tenantInfos
     * @return
     */
    private List<TenantInfoWrapper.TenantInfo> queryArea(List<TenantInfoWrapper.TenantInfo> tenantInfos) {
        List<Integer> areaCodeList = tenantInfos.stream().map(next -> {
            Set<Integer> codes = new HashSet<>();
            codes.add(next.getCityCode());
            codes.add(next.getProvinceCode());
            codes.add(next.getRegionCode());
            return codes;
        }).flatMap(Collection::stream).filter(Objects::nonNull).distinct().collect(Collectors.toList());

        Map<Integer, String> codeNameMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(areaCodeList)) {
            List<SysArea> sysAreaList = sysAreaService.queryByCodes(areaCodeList);
            codeNameMap = sysAreaList.stream().collect(Collectors.toMap(SysArea::getCode,
                    SysArea::getName));
        }

        for (TenantInfoWrapper.TenantInfo next : tenantInfos) {
            next.setProvinceName(codeNameMap.getOrDefault(next.getProvinceCode(), ""));
            next.setCityName(codeNameMap.getOrDefault(next.getCityCode(), ""));
            next.setRegionName(codeNameMap.getOrDefault(next.getRegionCode(), ""));
        }

        return tenantInfos;
    }

}