package com.huiju.estateagents.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
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.plugins.pagination.Page;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.service.ITaUserService;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.DateUtils;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaPersonServiceImpl extends ServiceImpl<TaPersonMapper, TaPerson> implements ITaPersonService {

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaPersonSignMapper taPersonSignMapper;

    @Autowired
    TaUvMapper taUvMapper;

    @Autowired
    TaFavorMapper taFavorMapper;

    @Autowired
    TaPersonBuildingMapper taPersonBuildingMapper;

    @Autowired
    TaRecommendCustomerMapper taRecommendCustomerMapper;

    @Autowired
    TaChatMapper taChatMapper;

    @Autowired
    private ITaRecommendCustomerService iTaRecommendCustomerService;

    @Autowired
    private TaSaveMapper taSaveMapper;

    @Autowired
    private TaActivityDynamicEnlistMapper taActivityDynamicEnlistMapper;

    @Autowired
    private TaBuildingDynamicMapper taBuildingDynamicMapper;

    @Autowired
    private ITaPointsRecordsService pointsRecordsService;

    @Autowired
    private ITaUserService taUserService;

    @Autowired
    private TaPosterService taPosterService;

    @Autowired
    private TaShareContentService taShareContentService;
    
    @Autowired
    private TaBuildingMapper taBuildingMapper;


    @Resource
    private ApplicationContext applicationContext;

    @Override
    public TaPerson mergePersonWxInfo(WxMaUserInfo userInfo) {
        // 先查询是否存在用户
        String openid = userInfo.getOpenId();
        List<TaPerson> persons = taPersonMapper.getPersonByOpenId(openid);

        if (null == persons || persons.size() != 1) {
//            // 没有则插入新记录
//            person = new TaPerson();
//            person.setMiniOpenid(openid);
//            person.setNickname(userInfo.getNickName());
//            person.setAvatarurl(userInfo.getAvatarUrl());
//            person.setStatus(CommConstant.STATUS_NORMAL);
//            person.setCreateDate(LocalDateTime.now());
//            person.setIsSignup(CommConstant.STATUS_NORMAL);
//
//            if (taPersonMapper.insert(person) > 0) {
//                return person;
//            }
            return null;
        } else {
            // 否则更新
            TaPerson person = persons.get(0);
            UpdateWrapper<TaPerson> wrapper = new UpdateWrapper<>();
            wrapper.eq("mini_openid", openid);
            wrapper.set("nickname", userInfo.getNickName());
            wrapper.set("avatarurl", userInfo.getAvatarUrl());
            wrapper.set("gender",userInfo.getGender());
            wrapper.set("city",userInfo.getCity());
            wrapper.set("province",userInfo.getProvince());
            wrapper.set("language",userInfo.getLanguage());
            wrapper.set("union_id",userInfo.getUnionId());
            wrapper.set("country",userInfo.getCountry());
            wrapper.set("auth_nickname_time", LocalDateTime.now());
            taPersonMapper.update(person, wrapper);

            person.setAvatarurl(userInfo.getAvatarUrl());
            person.setNickname(userInfo.getNickName());

            //获取推荐客户表中此人的信息并更新头像和姓名
            updateTaRecommendCustomer(person);

            return person;
        }
    }

    //获取推荐客户表中此人的信息并更新头像和姓名
    private void updateTaRecommendCustomer(TaPerson person) {
        //获取客户列表
        QueryWrapper<TaRecommendCustomer> taRecommendCustomerQueryWrapper = new QueryWrapper<>();
        taRecommendCustomerQueryWrapper.eq("person_id",person.getPersonId());
        taRecommendCustomerQueryWrapper.eq("org_id",person.getOrgId());
        List<TaRecommendCustomer> taRecommendCustomerList = taRecommendCustomerMapper.selectList(taRecommendCustomerQueryWrapper);
        taRecommendCustomerList.forEach(e -> {
            //没有姓名和头像的情况下更新
            if (StringUtils.isEmpty(e.getName()) || "匿名用户".equals(e.getName())){
                e.setName(person.getNickname());
                e.setPicture(person.getAvatarurl());
                taRecommendCustomerMapper.updateById(e);
            }
        });
    }

    @Override
    public TaPerson updatePersonPhone(String miniOpenid, String phone, String buildingId, Integer orgId) {
        // 先查询是否存在用户
        TaPerson person = null;
        List<TaPerson> taPersons = getPersonsByOpenId(miniOpenid);
        if (null != taPersons && taPersons.size() > 0) {
            person = taPersons.get(0);
        }

        if (null == person) {
            // 发生了未知错误
            return null;
        }

        // 电话为空, 代表没有获取到电话
        if (null == phone || "".equals(phone)) {
            return null;
        }

        String tel = person.getTel();

        UpdateWrapper<TaPerson> wrapper = new UpdateWrapper<>();
        wrapper.set("phone", phone);
        wrapper.set("auth_phone_time", LocalDateTime.now());
        if (!StringUtils.isEmpty(buildingId)){
            wrapper.set("building_id", buildingId);
        }

        if (CommConstant.PERSON_ESTATE_DRIFT.equals(person.getPersonType())) {
            wrapper.set("person_type",CommConstant.PERSON_ESTATE_CUSTOMER);
        }

        wrapper.eq("mini_openid", miniOpenid);
//        wrapper.eq("person_type",CommConstant.PERSON_ESTATE_DRIFT);
        taPersonMapper.update(new TaPerson(), wrapper);

        person.setPhone(phone);
        if (null == tel || "".equals(tel)){
            person.setTel(phone);
        }

       // iTaRecommendCustomerService.newByPerson(person);
        
        // 发放积分
        applicationContext.publishEvent(new EventBus(person, EventBus.EventType.SignUpAgent, orgId));
        
        return person;
    }

    @Override
    public IPage<Map<String, Object>> getCardList(int pageNumber, int pageSize, String buildingId, Integer orgId, TaPerson person) {
        // 获取当前人员的推荐置业顾问ID
        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("person_id", person.getPersonId());
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        queryWrapper.last("limit 1");
        TaRecommendCustomer cust = taRecommendCustomerMapper.selectOne(queryWrapper);
        String consultant = "";
        if (cust != null) {
            // 有可能是 personId, 有可能是 userId
            consultant = cust.getRealtyConsultant();
        }

        Page<Map<String, Object>> page = new Page<>();
        page.setSize(pageSize);
        page.setPages(pageNumber);
        page.setCurrent(pageNumber);

        List<Map<String, Object>> result = taPersonMapper.selectCardList(page, CommConstant.PERSON_REALTY_CONSULTANT, CommConstant.STATUS_NORMAL,buildingId,orgId, consultant);
        page.setRecords(result);

        return page;
    }

    @Override
    public ResponseBean checkPhoneAndPass(String phone, String pass) {
        QueryWrapper<TaPerson> query = new QueryWrapper<>();
        query.eq("tel", phone);
        query.eq("person_type", CommConstant.PERSON_REALTY_CONSULTANT);

        List<TaPerson> result = taPersonMapper.selectList(query);
        if (null == result || result.size() == 0) {
            return ResponseBean.error("数据异常: 电话号码不存在", ResponseBean.ERROR_UNAVAILABLE);
        }

        if (result.size() > 1) {
            return ResponseBean.error("数据异常: 电话记录重复, 或者重复绑定不同人员", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson person = result.get(0);
        if (person.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("数据异常: 该置业可能被禁用", ResponseBean.ERROR_UNAVAILABLE);
        }

        // todo
        // 验证密码

        return ResponseBean.success(person);
    }

    @Override
    public ResponseBean getCardDetail(String openid, String id,String personId) {
        // 卡片人员
        TaPerson person = taPersonMapper.selectById(id);
        if (null == person) {
            return ResponseBean.success("");
        }

        if (person.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("数据异常: 该数据可能被禁用", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 获取访问记录
        List<Map<String, Object>> visitors = taUvMapper.getLastVisitors(CommConstant.FAVOR_CONSULTANT, person.getPersonId(), 10);

        TaUser user = taUserService.getById(person.getUserId());
        // 获取关联项目
        List<TaPersonBuilding> buildingList = getPersonBuildings(user.getUserId().toString());
        List<String> buildings = new ArrayList<>();
        TaBuilding taBuilding = new TaBuilding();
        if (null != buildingList && buildingList.size() > 0) {
            for(TaPersonBuilding b: buildingList) {
                buildings.add(b.getBuildingId());
            }
            //获取楼盘信息
            taBuilding = taBuildingMapper.selectById(buildingList.get(0).getBuildingId());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("id", person.getPersonId());
        result.put("personType",person.getPersonType());
        result.put("name", user.getUserName());
        result.put("company", user.getOrgName());
        result.put("department", user.getDepartment());
        result.put("picture", user.getPhoto());
        result.put("hotNum", person.getHotNum());
        result.put("likeNum", person.getLikeNum());
        result.put("pvNum", person.getPvNum());
        result.put("post", person.getPost());
        result.put("phone", user.getPhone());
        result.put("avatar",user.getAvatar());
        result.put("visitors", visitors);
        result.put("liked", false);
        result.put("unReadNum", 0);
        result.put("projects", buildings);
        result.put("address", taBuilding.getAddress());
        result.put("buildingName", taBuilding.getBuildingName());
        result.put("coordinate", taBuilding.getCoordinate());
        result.put("personTags",person.getPersonTags());
        result.put("posters",taPosterService.getPostersForTarget(user.getUserId().toString(),CommConstant.POSTER_CONTENT_TYPE_PERSON));
        result.put("shareContent",taShareContentService.getPostersForTarget(user.getUserId().toString(),CommConstant.POSTER_CONTENT_TYPE_PERSON));
        QueryWrapper<TaSave> saveQueryWrapper = new QueryWrapper<>();
        saveQueryWrapper.eq("tagert_type", "card");
        saveQueryWrapper.eq("person_id",personId);
        saveQueryWrapper.eq("saved_target",person.getPersonId());
        Integer num = taSaveMapper.selectCount(saveQueryWrapper);
        Integer save = 0;
        if (num>0){
            save=CommConstant.STATUS_NORMAL;
        }
        result.put("isSave",save);

        // 当前人员
        List<TaPerson> taPersonList = getPersonsByOpenId(openid);
        if (null == taPersonList || taPersonList.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson currentPerson = taPersonList.get(0);
        if (!currentPerson.getPersonId().equals(person.getPersonId())) {
            // 如果不是请求当前人员的卡片, 那么验证下当前人员是否对卡片人员点过赞
            List<TaFavor> taUvList = getFavorListBy(currentPerson, person);
            result.put("liked", null != taUvList && taUvList.size() > 0);

            // 获取未读消息数量
            Integer unReadNum = taChatMapper.getUnReadMessage(person.getPersonId(), currentPerson.getPersonId());
            QueryWrapper<TaRecommendCustomer> recommendCustomerQueryWrapper = new QueryWrapper<>();
            recommendCustomerQueryWrapper.in("building_id",buildings);
            recommendCustomerQueryWrapper.eq("person_id",personId);
            recommendCustomerQueryWrapper.isNotNull("recommend_person");
            Integer count = iTaRecommendCustomerService.count(recommendCustomerQueryWrapper);
            if(count>0){
                result.put("isReport",true);
            }else {
                result.put("isReport",false);
            }
            result.put("unReadNum", null == unReadNum ? 0 : unReadNum);
        } else {
            List<TaFavor> taUvList = getFavorListBy(person, person);
            result.put("liked", null != taUvList && taUvList.size() > 0);
            Integer unReadNum = taChatMapper.getAllUnReadMessage(person.getPersonId());
            result.put("unReadNum", null == unReadNum ? 0 : unReadNum);
        }

        return ResponseBean.success(result);
    }

    @Override
    public ResponseBean resgiteAgent(String name, String phone, Integer sex, String explain, String openid) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);
        if (taPerson.getSignupStatus() == CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("请不要重复注册", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        taPerson.setTel(phone);
        taPerson.setName(name);
        taPerson.setSex(sex);
        taPerson.setRemark(explain);
        taPerson.setCreateDate(LocalDateTime.now());
        taPerson.setStatus(CommConstant.STATUS_NORMAL);
        taPerson.setPersonType(CommConstant.PERSON_ESTATE_AGENT);
        taPerson.setSignupStatus(CommConstant.STATUS_NORMAL);

        return ResponseBean.success(taPerson);
    }

    @Override
    public ResponseBean getWxUser(String openid) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);
        Map<String, Object> result = new HashMap<>();
        result.put("id", taPerson.getPersonId());
        result.put("name", taPerson.getName());
        result.put("liked", false);
        result.put("unReadNum", 0);
        result.put("nickname", taPerson.getNickname());
        result.put("avatar", taPerson.getAvatarurl());
        result.put("sex", taPerson.getSex());
        result.put("phone",StringUtils.ifNull(taPerson.getTel(),taPerson.getPhone()) );
        result.put("points", taPerson.getPoints());
        result.put("personType",taPerson.getPersonType());
        Integer unReadNum = taChatMapper.getAllUnReadMessage(taPerson.getPersonId());
        result.put("unReadNum", null == unReadNum ? 0 : unReadNum);

       // 查询最早的签到记录
        TaPersonSign taPersonSign = taPersonSignMapper.getLastSignRecord(taPerson.getPersonId());
        int havaSigned =  null == taPersonSign || !DateUtils.sameDay(LocalDateTime.now(), taPersonSign.getSignDate()) ? 0 : 1;

        result.put("havaSigned", havaSigned);

        // 查詢我的客戶數量
        Integer customerNum = taRecommendCustomerMapper.getMyCutsomerNum(taPerson.getPersonId());
        result.put("customerNum", customerNum);

        // 收藏數
        QueryWrapper<TaSave> saveQueryWrapper = new QueryWrapper<>();
        saveQueryWrapper.eq("person_id",taPerson.getPersonId());
        Integer saved = taSaveMapper.selectCount(saveQueryWrapper);
        result.put("saved",saved);
        result.put("personType",taPerson.getPersonType());
        result.put("userId", taPerson.getUserId());

        return ResponseBean.success(result);
    }

    @Override
    public ResponseBean getWxUserSign(String openid, Integer orgId) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);
        TaPersonSign taPersonSign = taPersonSignMapper.getLastSignRecord(taPerson.getPersonId());
        boolean todaySigned =  null != taPersonSign && DateUtils.sameDay(LocalDateTime.now(), taPersonSign.getSignDate());
        boolean yestodaySigned = null != taPersonSign && DateUtils.sameDay(LocalDateTime.now().minusDays(1), taPersonSign.getSignDate());

        if (todaySigned) {
            return ResponseBean.error("请不要重复签到", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        int durationDays = !yestodaySigned ? 1 : taPersonSign.getDurationDays() + 1;

        TaPersonSign sign = new TaPersonSign();
        sign.setPersonId(taPerson.getPersonId());
        sign.setSignDate(LocalDateTime.now());
        sign.setDurationDays(durationDays);

        int row = taPersonSignMapper.insert(sign);
        if (row <= 0) {
            return ResponseBean.error("签到失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        sign.setPerson(taPerson);
        pointsRecordsService.checkinPoints(sign, orgId);
        applicationContext.publishEvent(new EventBus(sign, EventBus.EventType.DailyCheckin, orgId));

        return ResponseBean.success("success");
    }

    @Override
    public TaPerson getPersonByTel(String userPhone) {
        QueryWrapper<TaPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tel", userPhone);

        List<TaPerson> taPersonList = taPersonMapper.selectList(queryWrapper);
        if (null == taPersonList || taPersonList.size() == 0) return null;

        return taPersonList.get(0);
    }

    @Override
    public IPage<TaPerson> getPersonList(int pageNumber, int pageSize, String personType, String name, String phone,Integer status,String buildingId,String personTags) {
//        QueryWrapper<TaPerson> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(!StringUtils.isEmpty(personType), "person_type", personType);
//        queryWrapper.like(!StringUtils.isEmpty(name), "name", name);
//        queryWrapper.eq(!StringUtils.isEmpty(phone), "tel", phone);
        //queryWrapper.eq(!StringUtils.isEmpty(buildingId),"building_id",buildingId);

        IPage<TaPerson> page = new Page<>(pageNumber, pageSize);
        return taPersonMapper.getPersonList(page,personType,name,phone,status,buildingId,personTags);
    }

    @Override
    public IPage<TaUser> getBuildingConsultantList(int pageNumber, int pageSize,String buildingId){
        IPage<TaUser> page = new Page<>(pageNumber,pageSize);
        QueryWrapper<TaPersonBuilding> personBuildingQueryWrapper = new QueryWrapper<>();
        personBuildingQueryWrapper.eq("building_id",buildingId);
        List<TaPersonBuilding> list = taPersonBuildingMapper.selectList(personBuildingQueryWrapper);
        List<Integer>idLists = new ArrayList<>();
//        for(int i=0; i<list.size();i++){
//            if(null != list.get(i).getUserId()){
//                idLists.add(list.get(i).getUserId());
//            }
//        }

        idLists = list.stream().filter(e -> null != e.getUserId()).map(e -> e.getUserId()).collect(Collectors.toList());
        IPage<TaUser> data = new Page<>();
        if(CollectionUtils.isNotEmpty(idLists)) {
            QueryWrapper<TaUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("user_id",idLists);
            userQueryWrapper.eq("is_consultant", true);
            userQueryWrapper.eq("status",CommConstant.STATUS_NORMAL);
            data = taUserService.page(page,userQueryWrapper);
        }

        return data;
    }

    @Override
    public TaPerson newPersonByOpenid(String openid,Integer orgId) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            TaPerson taPerson = new TaPerson();
            taPerson.setMiniOpenid(openid);
            taPerson.setNickname("匿名用户");
            taPerson.setOrgId(orgId);
            taPerson.setAvatarurl(CommConstant.MINIAPP_DEFAULT_AVATAR);
            taPerson.setPersonType(CommConstant.PERSON_ESTATE_DRIFT);
            taPerson.setStatus(CommConstant.STATUS_NORMAL);
            taPerson.setCreateDate(LocalDateTime.now());
            if (taPersonMapper.insert(taPerson) > 0) {
                return taPerson;
            }
        } else {
            return taPersons.get(0);
        }


        return null;
    }

    @Override
    public ResponseBean bindCard(String phone, String pass, String openid) {

        QueryWrapper<TaPerson> query = new QueryWrapper<>();
        query.eq("tel", phone);

        // 可能不仅仅只置业, 只要后台有的，应该都可以绑定
//        query.eq("person_type", CommConstant.PERSON_REALTY_CONSULTANT);

        List<TaPerson> result = taPersonMapper.selectList(query);
        if (result == null || result.size() != 1) {
            return ResponseBean.error("数据异常: 电话记录重复", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson person = result.get(0);
        if (person.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("数据异常: 该置业可能被禁用", ResponseBean.ERROR_UNAVAILABLE);
        }

        //
        List<TaPerson> crus = getPersonsByOpenId(openid);
        TaPerson current = crus.get(0);

        // 绑卡操作
        // 如果是同一个人, 不操作
        if (current.getPersonId().equals(person.getPersonId())) {
            return ResponseBean.success("");
        }

        // 如果不是同一个人, 把 current 的信息更新到 person 上, 但是 personId 不变
        // 同时把 person 信息置为不可用

        UpdateWrapper<TaPerson> up2 = new UpdateWrapper<>();
        up2.set("mini_openid", ""); // openid 更新为空, 避免多用户问题
        up2.set("status", CommConstant.STATUS_DELETE); // 人员置为已删除
        up2.set("remark", person.getPersonId()); // 备注里面填写被合并到的人员ID
        up2.set("person_id", current.getPersonId() + "-bak"); // 变更主键
        up2.eq("person_id", current.getPersonId());

        if (taPersonMapper.update(new TaPerson(), up2) < 1) {
            return ResponseBean.error("绑定卡片, 清除无效数据失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        UpdateWrapper<TaPerson> up1 = new UpdateWrapper<>();
        up1.set("mini_openid", current.getMiniOpenid());
        up1.set("nickname", current.getNickname());
        up1.set("avatarurl", current.getAvatarurl());
        up1.set("phone", current.getPhone());
        up1.set("person_id", current.getPersonId());  // 变更主键
        up1.eq("person_id", person.getPersonId());

        if (taPersonMapper.update(new TaPerson(), up1) < 1) {
            return ResponseBean.error("绑定卡片失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 变更授权项目, 从 current 变更到 person
        UpdateWrapper<TaPersonBuilding> up3 = new UpdateWrapper<>();
        up3.set("person_id", current.getPersonId());
        up3.eq("person_id", person.getPersonId());

        if (taPersonBuildingMapper.update(new TaPersonBuilding(), up3) < 1) {
            return ResponseBean.error("绑定卡片失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        return ResponseBean.success(current.getPersonId());
    }

    @Override
    public ResponseBean newConsultant(String paramStr) {
        TaPerson taPerson = JSONObject.parseObject(paramStr, TaPerson.class);
        taPerson.setCreateDate(LocalDateTime.now());
        taPerson.setPersonType(CommConstant.PERSON_REALTY_CONSULTANT);


        if (taPersonMapper.insert(taPerson) > 0) {
            // 授权项目
            addConsultantBuildings(taPerson.getPersonId(), paramStr);

            return ResponseBean.success(taPerson);
        }

        return ResponseBean.error("新增信息失败", ResponseBean.ERROR_UNAVAILABLE);
    }

    @Override
    public ResponseBean editConsultant(String id, String paramStr) {
        TaPerson taPerson = JSONObject.parseObject(paramStr, TaPerson.class);
        taPerson.setPersonId(id);

        // 授权项目
        addConsultantBuildings(id, paramStr);

        if (taPersonMapper.updateById(taPerson) > 0) {
            return ResponseBean.success("更新信息成功");
        }

        return ResponseBean.error("更新信息失败", ResponseBean.ERROR_UNAVAILABLE);
    }

    @Override
    public Map<String, Object> getExtraInfo(String personId) {
        Map<String, Object> result = new HashMap<>();

        // 查询最早的签到记录
        TaPersonSign taPersonSign = taPersonSignMapper.getLastSignRecord(personId);
        int havaSigned =  null == taPersonSign || !DateUtils.sameDay(LocalDateTime.now(), taPersonSign.getSignDate()) ? 0 : 1;
        result.put("havaSigned", havaSigned);

        // 查询我的客户记录
        Integer customerNum = taRecommendCustomerMapper.getMyCutsomerNum(personId);
        result.put("customerNum", null == customerNum ? 0 : customerNum.intValue());

        return result;
    }

    public void addConsultantBuildings(String personId, String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        String building = params.getString("buildings");
        if (StringUtils.isEmpty(building)) {
            return;
        }

//        JSONArray buildings = params.getJSONArray("buildings");

//        if (null != buildings && !buildings.isEmpty()) {
            // 先删除原来授权楼栋
            QueryWrapper<TaPersonBuilding> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id", personId);
            taPersonBuildingMapper.delete(queryWrapper);

            // 再插入新的授权
//            for (Object b : buildings) {
                TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
//                taPersonBuilding.setBuildingId(b.toString());
                taPersonBuilding.setBuildingId(building);
                taPersonBuilding.setPersonId(personId);
                taPersonBuilding.setCreateDate(LocalDateTime.now());
                taPersonBuildingMapper.insert(taPersonBuilding);
//            }
//        }
    }

    @Override
    public ResponseBean resetPassword(String phone, String pass, String plat) {
        // todo 待修复 三目表达式
        String personType = "wx".equals(plat) ? CommConstant.PERSON_REALTY_CONSULTANT : "";

        QueryWrapper<TaPerson> query = new QueryWrapper<>();
        query.eq("tel", phone);
        query.eq("person_type", personType);

        List<TaPerson> result = taPersonMapper.selectList(query);
        if (result.size() > 1) {
            return ResponseBean.error("数据异常: 电话记录重复", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson person = result.get(0);
        if (person.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("数据异常: 该置业可能被禁用", ResponseBean.ERROR_UNAVAILABLE);
        }

        String newPass = MD5Utils.md5(pass, person.getPersonId());

        UpdateWrapper<TaPerson> wrapper = new UpdateWrapper<>();
        wrapper.set("password", newPass);
        wrapper.eq("person_id", person.getPersonId());

        taPersonMapper.update(new TaPerson(), wrapper);
        return ResponseBean.success("");
    }

    // from 给 to 点赞
    List<TaFavor> getFavorListBy(TaPerson from, TaPerson to) {
        QueryWrapper<TaFavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", from.getPersonId());
        queryWrapper.eq("be_favor", to.getPersonId());
        queryWrapper.eq("tagert_type", CommConstant.FAVOR_CONSULTANT);

        return taFavorMapper.selectList(queryWrapper);
    }

    @Override
    public List<TaPerson> getPersonsByOpenId(String openid) {
        return taPersonMapper.getPersonByOpenId(openid);
    }

    public List<TaPersonBuilding> getPersonBuildings(String userId) {
        QueryWrapper<TaPersonBuilding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return taPersonBuildingMapper.selectList(queryWrapper);
    }

    @Override
    public ResponseBean channelBrokerList(String name, String phone,Integer pageNum,Integer pageSize,Integer orgid,Integer channelId) {
        ResponseBean responseBean = new ResponseBean<>();
        IPage<TaChannel> pg = new Page<>(pageNum, pageSize);
        IPage<TaPerson> IPage = taPersonMapper.channelBrokerList(pg,name,phone,orgid,channelId);
        List<TaPerson> taPersonList= IPage.getRecords();
        for (TaPerson taPerson:taPersonList){
            QueryWrapper<TaRecommendCustomer> taRecommendCustomerQuery= new QueryWrapper<>();
            taRecommendCustomerQuery.eq("recommend_person",taPerson.getPersonId());
            taRecommendCustomerQuery.eq("status",1);
            taRecommendCustomerQuery.eq("org_id", orgid);
            /*推荐客户总数*/
            int recommendCount= taRecommendCustomerMapper.selectCount(taRecommendCustomerQuery);
            taPerson.setRecommendCount(recommendCount);

            // 邀请客户总数
            QueryWrapper<TaPerson> taPersonQueryWrapper= new QueryWrapper<>();
            taPersonQueryWrapper.eq("recommend_agent",taPerson.getPersonId());
            int  inviteCount= taPersonMapper.selectCount(taPersonQueryWrapper);
            taPerson.setInviteCount(inviteCount);
        }
        HashMap hashMap= new HashMap<>();
        hashMap.put("list",taPersonList);
        hashMap.put("total",IPage.getTotal());
        hashMap.put("pageNum",IPage.getCurrent());
        hashMap.put("pageSize",IPage.getSize());
        responseBean.addSuccess(hashMap);
        return responseBean;
    }

    @Override
    public ResponseBean InviteClientsList(String id, String phone, Integer pageNum, Integer pageSize) {
        ResponseBean responseBean = new ResponseBean<>();
        IPage<TaChannel> pg = new Page<>(pageNum, pageSize);
        IPage<TaPerson> IPage = taPersonMapper.InviteClientsList(pg,id);
        responseBean.addSuccess(IPage);
        return responseBean;
    }

    @Override
    public IPage<TaPerson> getDriftCustomerList (int pageNumber, int pageSize,String building, Integer orgId,String sceneType){
        QueryWrapper<TaPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_type",CommConstant.PERSON_ESTATE_DRIFT);
        if(building.equals("") && null != building){
            queryWrapper.eq("building_id",building);
        }
        queryWrapper.eq(orgId != null, "org_id", orgId);
        queryWrapper.orderByDesc("create_date");
        IPage<TaPerson> page = new Page<>(pageNumber, pageSize);
        return taPersonMapper.selectDriftCustomerPageList(page,building,orgId,CommConstant.PERSON_ESTATE_DRIFT,sceneType);
    }

    @Override
    public String getPersonIdByCustomerId(String customerId){
        return taRecommendCustomerMapper.getCustomerPersonId(customerId);
    }

    @Override
    public IPage<Map<String,Object>> getSavedConsaultants(int pageNumber,int pageSize,String personId){
        QueryWrapper<TaSave> savePerson = new QueryWrapper<>();
        savePerson.eq("person_id",personId);
        savePerson.eq("tagert_type","card");
        List<TaSave> savedPerson = taSaveMapper.selectList(savePerson);
        List<String> personIds = new ArrayList<>();
        for(int i =0;i<savedPerson.size();i++){
            personIds.add(savedPerson.get(i).getSavedTarget());
        }
        Page<Map<String, Object>> page = new Page<>();
        page.setSize(pageSize);
        page.setPages(pageNumber);
        page.setCurrent(pageNumber);
        page.setRecords(taPersonMapper.selectCardListofMine(page,CommConstant.PERSON_REALTY_CONSULTANT,CommConstant.STATUS_NORMAL,personIds));
        return page;

    }
    @Override
    public void upDatePersonCityToId (String personId){
        taPersonMapper.upDatePersonCityToId(personId);
    }

    @Override
    public Integer judgeBindStatusByCondition(Integer userId, Integer orgId, String phone) {
        return taPersonMapper.judgeBindStatusByCondition(userId, orgId, phone);
    }

    /**
     * 第三方获取人员信息接口
     *
     * @param personId
     * @return
     */
    @Override
    public ResponseBean ThirdUserInfo(String personId) {
        TaPerson person = taPersonMapper.getById(personId);
        if (null == person){
            return ResponseBean.error("当前人员不存在",ResponseBean.ERROR_UNAVAILABLE);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("name", person.getName());
        map.put("avatar", person.getPhoto());
        map.put("wxname", person.getNickname());
        map.put("wxavatar", person.getAvatarurl());
        map.put("tel", StringUtils.isEmpty(person.getTel()) ? person.getPhone() : person.getTel());
        map.put("personType", person.getPersonType());
        map.put("personId", person.getPersonId());
        return ResponseBean.success(map);
    }

    @Override
    public Integer savePersonPosition(TaPersonPositon record) {
        return taPersonMapper.savePersonPosition(record);
    }


    public String codeGenerator (){
        double r = Math.random();
        int i = (int)(r*100000);
        String str = String.valueOf(i);
        if(str.length()<6){
            int need = 6-str.length();
            for(int j=0;j<need;j++){
                str += "0";
            }
        }
        return str;
    }

    @Override
    public String agentCodeGenerator (){
        QueryWrapper<TaPerson>queryWrapper = new QueryWrapper<>();
        while (true){
            String code = codeGenerator();
            queryWrapper.eq("agent_code",code);
            Integer count = taPersonMapper.selectCount(queryWrapper);
            if (count<=0){
                return code;
            }
        }
    }

    @Override
    public Integer sumPointsByOrgId(Integer orgId) {
        return taPersonMapper.sumPointsByOrgId(orgId);
    }


}
