package com.huiju.estateagents.center.taUser.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaTagUser;
import com.huiju.estateagents.center.taUser.entity.TaTags;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.entity.TaUserRole;
import com.huiju.estateagents.center.taUser.mapper.TaTagUserMapper;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.center.taUser.mapper.TaUserRoleMapper;
import com.huiju.estateagents.center.taUser.service.ITaUserService;
import com.huiju.estateagents.channel.sysChannel.entity.TaChannelProxy;
import com.huiju.estateagents.channel.sysChannel.mapper.TaChannelProxyMapper;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.common.WxUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-11
 */
@Service
public class TaUserServiceImpl extends ServiceImpl<TaUserMapper, TaUser> implements ITaUserService {

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaOrgMapper taOrgMapper;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private TaMiniappTemplateMapper taMiniappTemplateMapper;

    @Autowired
    private TaTagUserMapper taTagUserMapper;

    @Autowired
    private TaPersonBuildingMapper taPersonBuildingMapper;

    @Autowired
    private TaPersonMapper taPersonMapper;

    @Autowired
    private TaUserRoleMapper taUserRoleMapper;

    @Autowired
    private TdPointsRulesMapper tdPointsRulesMapper;

    @Autowired
    private ITdReportService iTdReportService;

    @Autowired
    private ITaBuildingReportService iTaBuildingReportService;

    @Autowired
    private TdCityMapper tdCityMapper;

    @Autowired
    private TaOrgCityMapper taOrgCityMapper;

    @Autowired
    private ITaPersonService iTaPersonService;

    @Autowired
    private ITaRecommendCustomerService iTaRecommendCustomerService;

    @Autowired
    private ISysOrgParamsService iSysOrgParamsService;

    @Autowired
    private TaChannelAppRelationMapper taChannelAppRelationMapper;

    @Autowired
    private TaChannelProxyMapper taChannelProxyMapper;

    @Autowired
    private WxUtils wxUtils;

    @Override
    public IPage<Map<String, Object>> getPageList(IPage pg, Integer channelId, String miniAppName) {
        List<Map<String, Object>> taUserList = taUserMapper.getPageList(pg, channelId, miniAppName);

        for (Map map : taUserList) {
            if (map.get("orgId") == null) {
                map.put("userCount", 0);
                map.put("registeredCount", 0);
                continue;
            }
            Integer userCount = taPersonMapper.selectChannelUserCount(map.get("orgId").toString());
            Integer registeredCount = taPersonMapper.selectChannelRegisteredCount(map.get("orgId").toString());
            map.put("userCount", userCount);
            map.put("registeredCount", registeredCount);
        }
        pg.setRecords(taUserList);
        return pg;
    }

    @Override
    public TaUser newUserAndOrg(TaUser taUser, Integer channelId) throws Exception {
        if (StringUtils.isEmpty(taUser.getPhone())) {
            throw new Exception("电话号码不能为空");
        }
        if (StringUtils.isEmpty(taUser.getUserName())) {
            throw new Exception("用户名称不能为空");
        }

        if (StringUtils.isEmpty(taUser.getLoginName())) {
            taUser.setLoginName(taUser.getPhone());
        }

        //判断默认城市是否在维护城市内
        verificationCity(taUser.getSelectCityTree(), taUser.getDefaultCityId());

        QueryWrapper<TaUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", taUser.getPhone()).or().eq("login_Name", taUser.getLoginName());
        List<TaUser> taUserList = this.list(wrapper);
        if (null != taUserList && taUserList.size() > 0) {
            throw new Exception("电话号码或登录名重复");
        }

        //判断渠道端新增小程序最大数
        QueryWrapper<TaChannelProxy> taChannelProxyQueryWrapper = new QueryWrapper<>();
        taChannelProxyQueryWrapper.eq("channel_id", channelId);
        TaChannelProxy taChannelProxy = taChannelProxyMapper.selectOne(taChannelProxyQueryWrapper);

        QueryWrapper<TaChannelAppRelation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.eq("channel_id", channelId);
        Integer miniAppCount = taChannelAppRelationMapper.selectCount(relationQueryWrapper);
        if (miniAppCount >= taChannelProxy.getAppMaxNum()) {
            throw new Exception("当前系统仅供维护" + taChannelProxy.getAppMaxNum() + "个小程序，需要维护更多项目，请联系相关管理人员");
        }

        // 先插入 org
        TaOrg taOrg = new TaOrg();
        taOrg.setName(taUser.getOrgName());
        taOrg.setLogo(taUser.getOrgLogo());
        taOrg.setWaterMark(taUser.getWaterMark());
        taOrg.setCreateDate(LocalDateTime.now());
        taOrg.setBuildingNum(taUser.getOrgNum());
        taOrg.setDefaultCityId(taUser.getDefaultCityId());
        taOrg.setThumb(taUser.getOrgThumb());
        taOrg.setOrgDesc(taUser.getOrgDesc());
        taOrg.setBossDisplay(taUser.getBossDisplay());
        if (taOrgMapper.insert(taOrg) < 1) {
            throw new Exception("生成用户公司信息失败");
        }

        //维护渠道和小程序关系
        TaChannelAppRelation taChannelAppRelation = new TaChannelAppRelation();
        taChannelAppRelation.setChannelId(channelId);
        taChannelAppRelation.setOrgId(taOrg.getOrgId());
        taChannelAppRelation.setCreateTime(LocalDateTime.now());
        taChannelAppRelationMapper.insert(taChannelAppRelation);

        // 维护当前城市所在城市
        addAndupdate(taUser.getSelectCityTree(), false, taOrg.getOrgId());

        // 插入积分, 默认全部 1 积分
        List<TdPointsRules> pointsRules = tdPointsRulesMapper.getTPLRules();
        if (pointsRules != null) {
            for (int i = 0; i < pointsRules.size(); i++) {
                TdPointsRules rule = pointsRules.get(i);
                rule.setOrgId(taOrg.getOrgId());
                rule.setStatus(CommConstant.STATUS_NORMAL);
                rule.setPointsAmount(1);    // 默认1积分
                tdPointsRulesMapper.insert(rule);
            }
        }

        // 插入统计，默认全部显示
        QueryWrapper<TdReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date");
        queryWrapper.eq("status", 1);
        List<TdReport> tdReportList = iTdReportService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(tdReportList)) {
            List<TaBuildingReport> buildingReportList = tdReportList.stream().map(e -> {
                TaBuildingReport taBuildingReport = new TaBuildingReport();
                taBuildingReport.setOrgId(taOrg.getOrgId());
                taBuildingReport.setReportCode(e.getReportCode());
                taBuildingReport.setCreateDate(LocalDateTime.now());

                return taBuildingReport;
            }).collect(Collectors.toList());

            iTaBuildingReportService.saveBatch(buildingReportList);
        }

        taUser.setOrgId(taOrg.getOrgId());
        taUser.setIsAdmin(true);
        taUser.setLoginPassword(MD5Utils.md5(taUser.getLoginPassword()));
        taUser.setStatus(CommConstant.STATUS_NORMAL);
        taUser.setCreateDate(LocalDateTime.now());
        if (!this.save(taUser)) {
            throw new Exception("生成用户信息失败");
        }

        // 导入系统参数
        iSysOrgParamsService.importParamsFromTemplate(taOrg.getOrgId());

        return taUser;
    }

    // 维护公司所在城市
    public void addAndupdate(ArrayList<String> selectCityTree, boolean isA, Integer orgid) {
        // 查询当前所有的市
        QueryWrapper<TdCity> tdCityQuery = new QueryWrapper<>();
        tdCityQuery.eq("leveltype", 2);
        List<TdCity> tdCityList = tdCityMapper.selectList(tdCityQuery);

        // isA=true删除所有城市重新添加
        if (isA == true) {
            QueryWrapper<TaOrgCity> taOrgCity = new QueryWrapper<>();
            taOrgCity.eq("org_id", orgid);
            taOrgCityMapper.delete(taOrgCity);
        }
        TaOrgCity taOrgCity = new TaOrgCity();
        // 对比现在的城市ID
        for (String city : selectCityTree) {
            for (TdCity tdCity : tdCityList) {
                // 入库城市
                if (city.equals(String.valueOf(tdCity.getId()))) {
                    taOrgCity.setCityId(Integer.valueOf(city)).setName(tdCity.getName()).setOrgId(orgid).setStatus(1).setParentid(tdCity.getParentid());
                    taOrgCityMapper.insert(taOrgCity);
                    // 查询当前公司选择省份是否存在
                    QueryWrapper<TaOrgCity> taOrgCityParent = new QueryWrapper<>();
                    taOrgCityParent.eq("city_id", tdCity.getParentid());
                    taOrgCityParent.eq("org_id", orgid);
                    taOrgCityParent.last("limit 1");
                    TaOrgCity taOrgParent = taOrgCityMapper.selectOne(taOrgCityParent);
                    // 如果为空，查询行政表
                    if (null == taOrgParent) {
                        TdCity tdCityParent = tdCityMapper.selectById(tdCity.getParentid());
                        taOrgCity.setCityId(tdCityParent.getId()).setName(tdCityParent.getName()).setOrgId(orgid).setStatus(1).setParentid(100000);
                        taOrgCityMapper.insert(taOrgCity);
                    }
                }

            }
        }

    }

    // 判断当前城市是否存在
    public void verificationCity(ArrayList<String> selectCityTree, Integer city) throws Exception {
        for (String id : selectCityTree) {
            if (id.equals(String.valueOf(city))) {
                return;
            }
        }
        throw new Exception("当前默认城市不在维护城市内");
    }

    @Override
    public TaUser getInfoWithOrg(Integer id) {
        TaUser taUser = this.getById(id);
        if (null == taUser) {
            return taUser;
        }

        TaOrg taOrg = taOrgMapper.selectById(taUser.getOrgId());
        if (null != taOrg) {
            taUser.setOrgName(taOrg.getName());
            taUser.setWaterMark(taOrg.getWaterMark());
            taUser.setOrgNum(taOrg.getBuildingNum());
            taUser.setDefaultCityId(taOrg.getDefaultCityId());
            taUser.setOrgThumb(taOrg.getThumb());
            taUser.setOrgDesc(taOrg.getOrgDesc());
            taUser.setOrgLogo(taOrg.getLogo());
            taUser.setBossDisplay(taOrg.getBossDisplay());
        }

        TaMiniapp taMiniapp = getMiniappByOrg(taOrg);
        if (null != taMiniapp) {
            QueryWrapper<TaMiniappTemplate> query = new QueryWrapper<>();
            query.eq("miniapp_id", taMiniapp.getMiniappId());
            taMiniapp.setTpls(taMiniappTemplateMapper.selectList(query));
        }

        taUser.setMiniapp(taMiniapp);
        taUser.setLoginPassword(null);
        // 查询所有城市id
        ArrayList<String> taOrgCityList = taOrgCityMapper.selectByIdCity(taUser.getOrgId());
        taUser.setSelectCityTree(taOrgCityList);
        return taUser;
    }

    @Override
    public void updateInfoWithOrg(TaUser taUser) throws Exception {
        //判断默认城市是否在维护城市内
        verificationCity(taUser.getSelectCityTree(), taUser.getDefaultCityId());

        TaOrg taOrg = taOrgMapper.selectById(taUser.getOrgId());
        if (null != taOrg) {
            taOrg.setName(taUser.getOrgName());
            taOrg.setLogo(taUser.getOrgLogo());
            taOrg.setWaterMark(taUser.getWaterMark());
            taOrg.setBuildingNum(taUser.getOrgNum());
            taOrg.setDefaultCityId(taUser.getDefaultCityId());
            taOrg.setThumb(taUser.getOrgThumb());
            taOrg.setOrgDesc(taUser.getOrgDesc());
            taOrg.setBossDisplay(taUser.getBossDisplay());
            if (taOrgMapper.updateById(taOrg) < 1) {
                throw new Exception("更新用户公司信息失败");
            }

            addAndupdate(taUser.getSelectCityTree(), true, taOrg.getOrgId());
        }

        taUser.setLoginPassword(null);
        if (taUserMapper.updateById(taUser) < 1) {
            throw new Exception("更新用户信息失败");
        }

        // 如果服务未启动, 则启动服务
        TaMiniapp miniapp = getMiniappByOrg(taOrg);
        if (miniapp != null) {
            WxMaService maService = wxUtils.getMiniApp(miniapp.getMiniappId());
            if (null == maService) {
                TaUser admin = taUserMapper.getAdminByAppID(miniapp.getMiniappId());

                if (null != admin && CommConstant.STATUS_NORMAL == admin.getStatus() && LocalDateTime.now().isBefore(admin.getExpDate())) {
                    wxUtils.newService(miniapp, true);
                }
            }
        }
    }

    private TaMiniapp getMiniappByOrg(TaOrg taOrg) {
        QueryWrapper<TaMiniapp> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id", taOrg.getOrgId());
        wrapper.last("limit 1");

        return taMiniappMapper.selectOne(wrapper);
    }

    @Override
    public void turnUserOnOrNot(Integer id, boolean isOn, String plat) throws Exception {
        TaUser taUser = this.getById(id);
        if (null == taUser) {
            throw new Exception("未找到有效的用户信息");
        }

        //停用
        if (!isOn){
            //查看是否置业顾问
            if (taUser.getIsConsultant()){
//                taUser.setIsConsultant(false);
//                taUserMapper.updateById(taUser);
                //小程序端调整为普通客户
                QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
                taPersonQueryWrapper.eq("user_id",id);
                taPersonQueryWrapper.eq("org_id",taUser.getOrgId());
                TaPerson taPerson = taPersonMapper.selectOne(taPersonQueryWrapper);
                if (null != taPerson){
                    taPersonMapper.cancelConsulatant(taPerson.getPersonId());
                }
            }
        }

        Integer status = isOn ? CommConstant.STATUS_NORMAL : CommConstant.STATUS_CLOSED;
        TaUser user = new TaUser();
        user.setStatus(status);
        user.setWeight(taUser.getWeight());

        QueryWrapper<TaUser> taUserQueryWrapper = new QueryWrapper<>();
        if (CommConstant.LOGIN_TYPE_ADMIN.equals(plat)) {
            taUserQueryWrapper.eq("user_id", id);
        }
        taUserQueryWrapper.eq("org_id", taUserMapper.selectById(id).getOrgId());

        if (!this.update(user, taUserQueryWrapper)) {
            throw new Exception("开启或禁用用户失败");
        }
    }

    @Override
    public void resetPassword(Integer id, String newPass) throws Exception {
        TaUser taUser = this.getById(id);
        if (null == taUser) {
            throw new Exception("未找到有效的用户信息");
        }

        String encryptPass = MD5Utils.md5(MD5Utils.md5(newPass));
        TaUser user = new TaUser();
        user.setLoginPassword(encryptPass);
        user.setUserId(id);

        if (!this.updateById(user)) {
            throw new Exception("重置用户密码失败");
        }
    }

    @Override
    public List<TaTags> getTagsList(TaUser e) {
        return taUserMapper.getTagsList(e.getUserId(), e.getOrgId());
    }

    @Override
    public TaUser addAdminUser(TaUser taUser) throws Exception {
        if (StringUtils.isEmpty(taUser.getPhone())) {
            throw new Exception("电话号码不能为空");
        }
        if (StringUtils.isEmpty(taUser.getUserName())) {
            throw new Exception("用户名称不能为空");
        }

        if (!StringUtils.isEmpty(taUser.getLoginName())) {
            QueryWrapper<TaUser> wrapper = new QueryWrapper<>();
            wrapper.eq("login_name", taUser.getLoginName());
            List<TaUser> taUserList = this.list(wrapper);
            if (null != taUserList && taUserList.size() > 0) {
                throw new Exception("登录名重复");
            }
        }

        boolean weightCount = validateWeight(taUser, "add");
        if (weightCount) {
            throw new Exception("同一项目下权重值不能重复");
        }

        List<TaUser> taUserList = taUserMapper.getUserList(taUser.getPhone(), taUser.getOrgId());
        if (null != taUserList && taUserList.size() > 0) {
            throw new Exception("电话号码重复");
        }
        taUser.setLoginPassword(MD5Utils.md5(MD5Utils.md5("123456")));
        taUser.setStatus(CommConstant.STATUS_NORMAL);
        taUser.setCreateDate(LocalDateTime.now());
        if (taUser.getIsConsultant() == null) {
            taUser.setIsConsultant(false);
        }
        if (taUserMapper.insert(taUser) < 1) {
            throw new Exception("生成用户信息失败");
        }

        //保存标签
        List<Integer> tags = taUser.getTaTags();
        tags.forEach(e -> {
            TaTagUser taTagUser = new TaTagUser();
            taTagUser.setUserId(taUser.getUserId());
            taTagUser.setTagId(e);
            taTagUserMapper.insert(taTagUser);
        });

        //保存用户角色
        List<Integer> roleIds = taUser.getRoleIds();
        roleIds.forEach(e -> {
            TaUserRole taUserRole = new TaUserRole();
            taUserRole.setUserId(taUser.getUserId());
            taUserRole.setRoleId(e);
            taUserRoleMapper.insert(taUserRole);
        });

        //保存项目
        if (taUser.getIsConsultant()) {
            TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
            taPersonBuilding.setBuildingId(taUser.getBuildingId());
            taPersonBuilding.setUserId(taUser.getUserId());
            taPersonBuilding.setCreateDate(LocalDateTime.now());
            taPersonBuildingMapper.insert(taPersonBuilding);
        } else {
            //非置业顾问可授权多个项目
            List<String> buildingIdList = taUser.getBuildingIds();
            LocalDateTime nowTime = LocalDateTime.now();
            buildingIdList.forEach(e -> {
                TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
                taPersonBuilding.setBuildingId(e);
                taPersonBuilding.setUserId(taUser.getUserId());
                taPersonBuilding.setCreateDate(nowTime);
                taPersonBuildingMapper.insert(taPersonBuilding);
            });
        }

        return taUser;
    }

    @Override
    public TaUser updateAdminUser(TaUser taUser) throws Exception {
        TaUser taUserBefore = taUserMapper.selectById(taUser.getUserId());
        if (StringUtils.isEmpty(taUser.getPhone())) {
            throw new Exception("电话号码不能为空");
        }
        if (StringUtils.isEmpty(taUser.getUserName())) {
            throw new Exception("用户名称不能为空");
        }
        if (!StringUtils.isEmpty(taUser.getWeight()) && taUser.getWeight().length() > 11) {
            throw new Exception("权重最大为11位");
        }
        if (StringUtils.isEmpty(taUser.getWeight())) {
            taUser.setWeight(null);
        }
        if (!StringUtils.isEmpty(taUser.getLoginName()) && !taUser.getLoginName().equals(taUserBefore.getLoginName())) {
            if (!StringUtils.isEmpty(taUser.getLoginName())) {
                QueryWrapper<TaUser> wrapper = new QueryWrapper<>();
                wrapper.eq("login_name", taUser.getLoginName());
                List<TaUser> taUserList = this.list(wrapper);
                if (null != taUserList && taUserList.size() > 0) {
                    throw new Exception("登录名重复");
                }
            }
        }

        boolean weightCount = validateWeight(taUser, "update");
        if (weightCount) {
            throw new Exception("同一项目下权重值不能重复");
        }

        QueryWrapper<TaUser> wrapper = new QueryWrapper<>();
//        wrapper.nested(q -> q.eq("phone", taUser.getPhone()).or().eq("login_Name", taUser.getLoginName()));
        wrapper.eq("phone", taUser.getPhone());
        wrapper.eq("org_id", taUser.getOrgId());
        wrapper.ne("user_id", taUser.getUserId());
        List<TaUser> taUserList = this.list(wrapper);
        if (null != taUserList && taUserList.size() > 0) {
            throw new Exception("电话号码重复");
        }
        if (taUserMapper.updateById(taUser) < 1) {
            throw new Exception("更新用户信息失败");
        }
        QueryWrapper<TaTagUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", taUser.getUserId());
        taTagUserMapper.delete(queryWrapper);
        //保存标签
        List<Integer> tags = taUser.getTaTags();
        tags.forEach(e -> {
            TaTagUser taTagUser = new TaTagUser();
            taTagUser.setUserId(taUser.getUserId());
            taTagUser.setTagId(e);
            taTagUserMapper.insert(taTagUser);
        });

        QueryWrapper<TaUserRole> taUserRoleQueryWrapper = new QueryWrapper<>();
        taUserRoleQueryWrapper.eq("user_id", taUser.getUserId());
        taUserRoleMapper.delete(taUserRoleQueryWrapper);
        //保存用户角色
        List<Integer> roleIds = taUser.getRoleIds();
        roleIds.forEach(e -> {
            TaUserRole taUserRole = new TaUserRole();
            taUserRole.setUserId(taUser.getUserId());
            taUserRole.setRoleId(e);
            taUserRoleMapper.insert(taUserRole);
        });

        QueryWrapper<TaPersonBuilding> taPersonBuildingQueryWrapper = new QueryWrapper<>();
        taPersonBuildingQueryWrapper.eq("user_id", taUser.getUserId());
        taPersonBuildingMapper.delete(taPersonBuildingQueryWrapper);
        //保存项目
        if (taUser.getIsConsultant()) {
            TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
            taPersonBuilding.setBuildingId(taUser.getBuildingId());
            taPersonBuilding.setUserId(taUser.getUserId());
            taPersonBuilding.setCreateDate(LocalDateTime.now());
            taPersonBuildingMapper.insert(taPersonBuilding);
        } else {
            //非置业顾问可授权多个项目
            List<String> buildingIdList = taUser.getBuildingIds();
            LocalDateTime nowTime = LocalDateTime.now();
            buildingIdList.forEach(e -> {
                TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
                taPersonBuilding.setBuildingId(e);
                taPersonBuilding.setUserId(taUser.getUserId());
                taPersonBuilding.setCreateDate(nowTime);
                taPersonBuildingMapper.insert(taPersonBuilding);
            });
        }

        //更新person
        TaPerson taPerson = new TaPerson();
        taPerson.setAvatarurl(taUser.getAvatar());
        taPerson.setCompany(taUser.getOrgName());
        taPerson.setTel(taUser.getPhone());
        taPerson.setName(taUser.getUserName());
        taPerson.setAddress(taUser.getAddress());
        taPerson.setIdNo(taUser.getIdNo());
        taPerson.setDepartment(taUser.getDepartment());
        taPerson.setPost(taUser.getPosition());
        taPerson.setPhoto(taUser.getPhoto());
        QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
        taPersonQueryWrapper.eq("user_id", taUser.getUserId());
        taPersonMapper.update(taPerson, taPersonQueryWrapper);

        return taUser;
    }

    @Override
    public TaUser getAdminByAppID(String appid) {
        return taUserMapper.getAdminByAppID(appid);
    }

    @Override
    public ResponseBean cityTree() {
        ResponseBean responseBean = new ResponseBean<>();
        // 省份
        TaUser taUser = new TaUser();
        QueryWrapper<TdCity> tdCityQueryWrapper = new QueryWrapper<>();
        tdCityQueryWrapper.eq("leveltype", 1);
        List<TdCity> tdCityList = tdCityMapper.selectList(tdCityQueryWrapper);
        taUser.setTdCityList(tdCityList);
        for (TdCity tdCity : tdCityList) {
            // 根据parentid查询城市
            QueryWrapper<TdCity> tdCityQuery = new QueryWrapper<>();
            tdCityQuery.eq("parentid", tdCity.getId());
            List<TdCity> city = tdCityMapper.selectList(tdCityQuery);
            tdCity.setChildren(city);
        }
        responseBean.addSuccess(taUser);
        return responseBean;
    }

    @Override
    public ResponseBean departureUser(Integer userId, List<String> customerIdList, Integer consultantUserId) {
        ResponseBean responseBean = new ResponseBean();
        TaUser user = this.getById(userId);
        if (null == user) {
            responseBean.addError("此员工不存在！");
            return responseBean;
        }

        // 不是置业顾问
        if (user.getIsConsultant() == false) {
            // 设置员工离职
            updateUserStatus(user);
            return ResponseBean.success("操作成功！");
        }
        /**
         * 是置业顾问
         */

        // 更改员工表的用户类型，清空关联关系user_id

        QueryWrapper<TaPerson> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", consultantUserId);
        TaPerson person = iTaPersonService.getOne(userQueryWrapper);
        if (null == person) {
            responseBean.addError("置业顾问未绑定小程序！");
            return responseBean;
        }

        // 设置员工离职
        updateUserStatus(user);

        // 转移客户
        UpdateWrapper<TaRecommendCustomer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("customer_id", customerIdList);
        updateWrapper.set("realty_consultant", person.getPersonId());
        boolean update = iTaRecommendCustomerService.update(updateWrapper);
        if (!update) {
            return ResponseBean.error("操作失败!", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        return ResponseBean.success("操作成功!");
    }

    /**
     * 分页查询用户列表
     *
     * @param pg
     * @param taUser
     * @param personBuildingList
     * @return
     */
    @Override
    public IPage<TaUser> seleUserList(IPage pg, TaUser taUser, List<TaPersonBuilding> personBuildingList) {
        return taUserMapper.seleUserList(pg, taUser, personBuildingList);
    }

    @Override
    public TaUser getUserInfoById(Integer userId, Integer orgId) {
        QueryWrapper<TaUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", userId);
        userQueryWrapper.eq("org_id", orgId);
        userQueryWrapper.ne("status", -1);
        return getOne(userQueryWrapper);
    }

    private boolean updateUserStatus(TaUser user) {
        UpdateWrapper<TaUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getUserId());
        updateWrapper.set("status", 9);

        QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
        taPersonQueryWrapper.eq("user_id", user.getUserId());
        taPersonQueryWrapper.last("limit 1");
        TaPerson taPerson = taPersonMapper.selectOne(taPersonQueryWrapper);
        // 可能存在没有绑定小程序端
        if (null != taPerson) {
            UpdateWrapper<TaPerson> personUpdateWrapper = new UpdateWrapper<>();
            personUpdateWrapper.eq("person_id", taPerson.getPersonId());

            // 如果是置业顾问，设置为客户类型
            if (user.getIsConsultant() == true) {
                personUpdateWrapper.set("person_type", CommConstant.PERSON_ESTATE_CUSTOMER);
            }

            personUpdateWrapper.set("user_id", null);
            iTaPersonService.update(personUpdateWrapper);
        }

        return this.update(updateWrapper);
    }

    public boolean validateWeight(TaUser taUser, String operateType) {
        if (StringUtils.isEmpty(taUser.getWeight())) {
            return false;
        }

        Integer count;
        if (taUser.getIsConsultant() != null && taUser.getIsConsultant()) {
            String buildingId = taUser.getBuildingId();
            String weight = taUser.getWeight();
            count = taUserMapper.validateWeight(null, buildingId, weight, operateType.equals("add") ? null : taUser.getUserId());
        } else {
            List<String> buildingIds = taUser.getBuildingIds();
            String weight = taUser.getWeight();
            count = taUserMapper.validateWeight(buildingIds, null, weight, operateType.equals("add") ? null : taUser.getUserId());
        }

        if (count > 0) {
            return true;
        }
        return false;
    }

}
