package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSON;
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.mapper.TaUserMapper;
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.StringUtils;
import com.huiju.estateagents.drainage.entity.TaDrainage;
import com.huiju.estateagents.drainage.mapper.TaDrainageMapper;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.excel.AgentsRecommendCustomer;
import com.huiju.estateagents.excel.ExcelRecommendCustomer;
import com.huiju.estateagents.excel.ReporRecommendCustomer;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.service.ITaRecommendCustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.statistic.entity.TaCustomerFollowUpRecord;
import com.huiju.estateagents.statistic.mapper.TaCustomerFollowUpRecordMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 推荐客户表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaRecommendCustomerServiceImpl extends ServiceImpl<TaRecommendCustomerMapper, TaRecommendCustomer> implements ITaRecommendCustomerService {

    private Logger logger = LoggerFactory.getLogger(TaRecommendCustomerServiceImpl.class);

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaRecommendCustomerMapper taRecommendCustomerMapper;

    @Autowired
    IMiniAppService iMiniAppService;

    @Autowired
    TaPersonVisitRecordMapper taPersonVisitRecordMapper;

    @Autowired
    ITaUserService userService;

    @Autowired
    private TaBuildingMapper taBuildingMapper;

    @Autowired
    private TdCityMapper cityMapper;

    @Autowired
    private TaCustomerFollowUpRecordMapper customerFollowUpRecordMapper;

    @Autowired
    private TaPersonBuildingMapper taPersonBuildingMapper;

    @Autowired
    private TaBuildingDynamicMapper taBuildingDynamicMapper;

    @Autowired
    private TaShareActivityMapper taShareActivityMapper;

    @Autowired
    private HelpActivityMapper helpActivityMapper;

    @Autowired
    private TaNewsMapper taNewsMapper;

    @Autowired
    private TaDrainageMapper taDrainageMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaPersonFromRecordMapper taPersonFromRecordMapper;

    @Autowired
    private TdPersonFromMapper tdPersonFromMapper;

    @Autowired
    private TdWxDictMapper tdWxDictMapper;

    @Autowired
    private TaCustomerFromMapper taCustomerFromMapper;

    @Autowired
    private TaSharePersonFromMapper taSharePersonFromMapper;

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

        TaPerson taPerson = taPersons.get(0);

        IPage<TaRecommendCustomer> page = new Page<>();
        page.setCurrent(pageNumber);
        page.setSize(pageSize);

        QueryWrapper<TaRecommendCustomer> query = new QueryWrapper<>();
        query.eq("recommend_person", taPerson.getPersonId());
        query.like(null != keywords && "".equals(keywords.trim()), "name", keywords);
        query.orderByDesc("report_date");

        IPage<TaRecommendCustomer> result = taRecommendCustomerMapper.selectPage(page, query);
        return ResponseBean.success(result);
    }

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

        TaPerson taPerson = taPersons.get(0);

        IPage<TaRecommendCustomer> page = new Page<>();
        page.setCurrent(pageNumber);
        page.setSize(pageSize);

        QueryWrapper<TaRecommendCustomer> query = new QueryWrapper<>();
        query.eq("realty_consultant", taPerson.getPersonId());
        query.like(null != keywords && "".equals(keywords.trim()), "name", keywords);
        query.orderByDesc("report_date");

        IPage<TaRecommendCustomer> result = taRecommendCustomerMapper.selectPage(page, query);
        return ResponseBean.success(result);
    }

    /**
     * 获取置业顾问下
     *
     * @param userId
     * @param personId
     * @param buildingId
     * @param orgId
     * @param taPersonBuildingListByUserId
     * @return
     */
    @Override
    public List<TaRecommendCustomer> getConsultantCustomerList(Integer userId, String personId, String buildingId, Integer orgId, List<TaPersonBuilding> taPersonBuildingListByUserId) {
        return taRecommendCustomerMapper.getConsultantCustomerList(userId, personId, buildingId, orgId);
    }

    @Override
    public List<TaRecommendCustomer> newCustomer(Integer orgId, TaPerson person, TaPerson recommender, TaPerson consultant, TaBuilding building, TaCustomerFrom from) throws Exception {
        logger.info("newCustomer 接收参数：orgId：{}，person：{}，recommender：{}，consultant：{}，building：{}，from：{}",
                orgId, JSONObject.toJSONString(person), JSONObject.toJSONString(recommender), JSONObject.toJSONString(consultant), JSONObject.toJSONString(building), JSONObject.toJSONString(from));

        // 如果置业推荐了非自己绑定楼盘, 会生成 2 条客户记录
        List<TaRecommendCustomer> result = new ArrayList<>();
        List<TaBuilding> consultBuildings = null;
        List<String> consultBuildingIds = null;
        if (null != consultant) {
            consultBuildings = taPersonBuildingMapper.getBuildingsOf(consultant.getUserId().toString());
            if (null != consultBuildings && consultBuildings.size() > 0) {
                consultBuildingIds = consultBuildings.stream().map(TaBuilding::getBuildingId).collect(Collectors.toList());
            }
        }

        //
        LocalDateTime now = LocalDateTime.now();
        from.setOrgId(orgId);
        from.setPersonId(person.getPersonId());
        from.setPersonName(StringUtils.ifNull(person.getName(), person.getNickname()));
        from.setCreateDate(now);

        Map<String, Number> checkNum = taRecommendCustomerMapper.checkCustomerBy(orgId, person.getPersonId(), consultBuildingIds, null != building ? building.getBuildingId() : null);
        // 是否存在小程序客户记录
        boolean hasOrgCust = checkNum.get("orgNum").intValue() > 0;
        // 是否存在置业绑定的楼盘客户记录
        boolean hasConsultBuildingCust = checkNum.get("consultBuildingNum").intValue() > 0;
        // 是否存在置业绑定的楼盘私客记录
        boolean hasConsultCust = checkNum.get("consultNum").intValue() > 0;
        // 是否存在当前内容楼盘的客户记录
        boolean hasBuildingCust = checkNum.get("buildingNum").intValue() > 0;

        // 置业与内容楼盘是否有关联关系
        boolean builingAssociated = false;

        logger.info("newCustomer checkCustomer查询结果：hasOrgCust：{}，hasConsultBuildingCust：{}，hasConsultCust：{}，hasBuildingCust：{}",
                hasOrgCust, hasConsultBuildingCust, hasConsultCust, hasBuildingCust);

        // 职业顾问不插入客户表
        boolean personIsConsultant = CommConstant.PERSON_REALTY_CONSULTANT.equals(person.getPersonType()) ? true : false;
        if (personIsConsultant) {
            return result;
        }

        // 置业项目
        if (null != consultant && CollectionUtils.isNotEmpty(consultBuildings) && !hasConsultCust) {
            TaBuilding taBuilding = null;
            if (consultBuildingIds.contains(null != building ? building.getBuildingId() : null)) {
                taBuilding = building;
                builingAssociated = true;
            } else {
                taBuilding = consultBuildings.get(0);
            }

            if (hasConsultBuildingCust) {
                // 如果是项目公客
                QueryWrapper<TaRecommendCustomer> taRecommendCustomerQueryWrapper = new QueryWrapper<>();
                taRecommendCustomerQueryWrapper.eq("building_id", taBuilding.getBuildingId());
                taRecommendCustomerQueryWrapper.gt("status", CommConstant.STATUS_DELETE);
                taRecommendCustomerQueryWrapper.orderByAsc("create_date");
                taRecommendCustomerQueryWrapper.last("limit 1");
                TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectOne(taRecommendCustomerQueryWrapper);

                taRecommendCustomer = copyFromPerosn(person, taRecommendCustomer);
                taRecommendCustomer.setRealtyConsultant(consultant.getUserId().toString());
                taRecommendCustomerMapper.updateById(taRecommendCustomer);
                result.add(taRecommendCustomer);
            } else {
                // 如果没有任何置业及置业楼盘相关的数据, 则插入新记录
                TaRecommendCustomer customer = copyFromPerosn(person, new TaRecommendCustomer());
                fillSomeFieldsOfCustomer(customer, recommender, now);
                customer.setBuildingId(taBuilding.getBuildingId());
                customer.setBuildingName(taBuilding.getBuildingName());
                customer.setRealtyConsultant(consultant.getUserId().toString());
                taRecommendCustomerMapper.insert(customer);
                result.add(customer);

                // 是否首次进入标识
                Boolean isFirstOrg = hasOrgCust;

                // 如果非小程序公客, 即首次进入
                if (!isFirstOrg) {
                    // 如果分享内容的楼盘跟置业楼盘一致
                    if (builingAssociated || null  == building ) {
                        isFirstOrg = true;
                    }
                } else {
                    isFirstOrg = false;
                }

                TaCustomerFrom customerFrom = copyPropertiesFrom(from);
                customerFrom.setCustomerId(customer.getCustomerId());
                customerFrom.setSharePersonId(recommender.getPersonId());
                customerFrom.setSharePersonName(StringUtils.ifNull(recommender.getName(), recommender.getNickname()));
                customerFrom.setBuildingId(taBuilding.getBuildingId());
                customerFrom.setBuildingName(taBuilding.getBuildingName());
                customerFrom.setIsOrgFirst(isFirstOrg);
                customerFrom.setIsProjectFirst(true);
                customerFrom.setCreateDate(now);
                taCustomerFromMapper.insert(customerFrom);

                if (isFirstOrg) {
                    hasOrgCust = true;
                }
            }
        }

        // 项目公客
        if (null != building && !hasBuildingCust && !builingAssociated) {
            // 校验客户是否已经是该项目公客
//            QueryWrapper<TaRecommendCustomer> customerQueryWrapper = new QueryWrapper<>();
//            customerQueryWrapper.eq("org_id", orgId);
//            customerQueryWrapper.eq("person_id", person.getPersonId());
//            customerQueryWrapper.eq("building_id", building.getBuildingId());
//            customerQueryWrapper.gt("status", CommConstant.STATUS_DELETE);
//            customerQueryWrapper.orderByAsc("create_date");
//            customerQueryWrapper.last("limit 1");
//            TaRecommendCustomer customerCheck = taRecommendCustomerMapper.selectOne(customerQueryWrapper);
//            if(customerCheck == null){
            TaRecommendCustomer customer = copyFromPerosn(person, new TaRecommendCustomer());
            fillSomeFieldsOfCustomer(customer, recommender, now);
            customer.setBuildingId(building.getBuildingId());
            taRecommendCustomerMapper.insert(customer);
            result.add(customer);

            // 是否首次进入标识
            Boolean isFirstOrg = hasOrgCust;

            TaCustomerFrom customerFrom = copyPropertiesFrom(from);
            customerFrom.setCustomerId(customer.getCustomerId());
            customerFrom.setSharePersonId(null == recommender ? null : recommender.getPersonId());
            customerFrom.setSharePersonName(null == recommender ? null : StringUtils.ifNull(recommender.getName(), recommender.getNickname()));
            customerFrom.setBuildingId(building.getBuildingId());
            customerFrom.setBuildingName(building.getBuildingName());
            customerFrom.setIsOrgFirst(!isFirstOrg);
            customerFrom.setIsProjectFirst(true);
            customerFrom.setCreateDate(now);
            taCustomerFromMapper.insert(customerFrom);
//            }

            // 如果非小程序公客, 即首次进入
            if (!isFirstOrg) {
                hasOrgCust = true;
            }
        }

        // 小程序公客
        if (!hasOrgCust && null == consultant) {
            TaRecommendCustomer customer = copyFromPerosn(person, new TaRecommendCustomer());
            fillSomeFieldsOfCustomer(customer, recommender, now);
            taRecommendCustomerMapper.insert(customer);
            result.add(customer);

            TaCustomerFrom customerFrom = copyPropertiesFrom(from);
            customerFrom.setCustomerId(customer.getCustomerId());
            customerFrom.setSharePersonId(null == recommender ? null : recommender.getPersonId());
            customerFrom.setSharePersonName(null == recommender ? null : StringUtils.ifNull(recommender.getName(), recommender.getNickname()));
            customerFrom.setIsOrgFirst(true);
            customerFrom.setIsProjectFirst(false);
            customerFrom.setCreateDate(now);
            taCustomerFromMapper.insert(customerFrom);
        }

        return result;
    }

    private void fillSomeFieldsOfCustomer(TaRecommendCustomer customer, TaPerson recommender, LocalDateTime now) {
        customer.setVerifyStatus(CommConstant.VERIFY_AGREE);
        customer.setStatus(CommConstant.CUSTOMER_REPORT);
        customer.setEntryType(null == recommender ? CommConstant.ENTRY_VOLUNTEER : CommConstant.ENTRY_INPUT);
        customer.setCreateDate(now);
        customer.setReportDate(now);
//        customer.setRecommendPerson(null == recommender ? null : recommender.getPersonId());
    }

    private TaRecommendCustomer copyFromPerosn(TaPerson person, TaRecommendCustomer cust) {
        cust.setPersonId(person.getPersonId());
        cust.setName(StringUtils.ifNull(person.getName(), person.getNickname()));
        cust.setSex(null == person.getSex() ? str2Int(person.getGender()) : person.getSex());
        cust.setPhone(StringUtils.ifNull(person.getPhone(), person.getTel()));
        cust.setPicture(StringUtils.ifNull(person.getAvatarurl(), person.getPhoto()));
        cust.setCountry(person.getCountry());
        cust.setCity(person.getCity());
        cust.setProvince(person.getProvince());
        cust.setOrgId(person.getOrgId());

        return cust;
    }

    private TaCustomerFrom copyPropertiesFrom(TaCustomerFrom from) {
        BeanCopier copier = BeanCopier.create(TaCustomerFrom.class, TaCustomerFrom.class, false);
        TaCustomerFrom to = new TaCustomerFrom();
        copier.copy(from, to, null);
        return to;
    }

    public void delPubCust(String personId, String buildingId) {
        TaRecommendCustomer recommendCustomer = new TaRecommendCustomer();
        recommendCustomer.setStatus(CommConstant.STATUS_DELETE);

        QueryWrapper<TaRecommendCustomer> taRecommendCustomerQueryWrapper = new QueryWrapper<>();
        taRecommendCustomerQueryWrapper.eq("building_id", buildingId);
        taRecommendCustomerQueryWrapper.eq("person_id", personId);
        taRecommendCustomerMapper.update(recommendCustomer, taRecommendCustomerQueryWrapper);
    }

    @Override
    public ResponseBean getCustDetail(String id) {
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(id);

        if (!StringUtils.isEmpty(taRecommendCustomer.getRealtyConsultant())) {
            TaPerson taPerson = taPersonMapper.selectById(taRecommendCustomer.getRealtyConsultant());
            if (null != taPerson) {
                TaUser user = userService.getById(taPerson.getUserId());
                taRecommendCustomer.setConsultants(new HashMap<String, Object>() {{
                    put("name", user.getUserName());
                    put("phone", user.getPhone());
                    put("photo", user.getPhoto());
                }});
            }
        }

        return ResponseBean.success(taRecommendCustomer);
    }

    @Override
    public ResponseBean updateCustByJSON(String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (null == params) {
            return ResponseBean.error("解析参数失败", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        String checkResult = checkCustomerParams(params);
        if (null != checkResult) {
            return ResponseBean.error(checkResult, ResponseBean.ERROR_MISSING_PARAMS);
        }


        UpdateWrapper<TaRecommendCustomer> wrapper = new UpdateWrapper<>();
        wrapper.eq("customer_id", params.get("id"));
        wrapper.set("name", params.get("name"));
        wrapper.set("picture", params.get("picture"));
        wrapper.set("phone", params.get("phone"));
        wrapper.set("sex", params.get("sex"));
        wrapper.set("describe", params.get("describe"));

        String at = params.getString("appointmentTime");
        if (!StringUtils.isEmpty(at)) {
            wrapper.set("appointmentTime", DateUtils.day2LocalDateime(at));
        }
        wrapper.set("vistors", params.get("vistors"));
        wrapper.set("explain", params.get("explain"));
        wrapper.set("intention", params.get("intention"));
        wrapper.set("realtyManageType", params.get("realtyManageType"));
        wrapper.set("demandType", params.get("demandType"));
        wrapper.set("priceRange", params.get("priceRange"));
        wrapper.set("realtyConsultant", params.get("realtyConsultant"));

        // todo 需要约定时间格式
//        wrapper.set("reportDate", params.get("reportDate"));

        String status = params.getString("status");
        if (null != status) {
            wrapper.set("status", params.get("status"));
        }

        int row = taRecommendCustomerMapper.update(new TaRecommendCustomer(), wrapper);
        if (row <= 0) {
            return ResponseBean.error("更新客户信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        return ResponseBean.success("更新客户信息成功");
    }

    @Override
    public synchronized ResponseBean recommendCust(String paramStr, String openid, Integer orgId) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (null == params) {
            return ResponseBean.error("解析参数失败", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson taPerson = taPersons.get(0);

        String checkResult = checkCustomerParams(params);
        if (null != checkResult) {
            return ResponseBean.error(checkResult, ResponseBean.ERROR_MISSING_PARAMS);
        }

        // 报备有 10 天有效期
        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", params.getString("phone"));
        queryWrapper.eq("building_id", params.getString("intention"));
        queryWrapper.in("verify_status", CommConstant.VERIFY_AGREE, CommConstant.VERIFY_READY);
        List<TaRecommendCustomer> result = taRecommendCustomerMapper.selectList(queryWrapper);
        if (null != result && result.size() > 0) {
            return ResponseBean.error("当前客户已被推荐, 不能再次推荐", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
        taRecommendCustomer.setName(params.getString("name"));
        taRecommendCustomer.setPicture(params.getString("picture"));
        taRecommendCustomer.setPhone(params.getString("phone"));
        taRecommendCustomer.setSex(params.getInteger("sex"));
        taRecommendCustomer.setDescribe(params.getString("describe"));
        taRecommendCustomer.setRecommendPerson(params.getString("recommendPerson"));
        taRecommendCustomer.setBuildingId(params.getString("intention"));
        taRecommendCustomer.setRealtyConsultant(params.getString("realtyConsultant"));
        taRecommendCustomer.setReportRecommendStatus(CommConstant.RECOMMENDED);
        taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_READY);
        taRecommendCustomer.setCreateDate(LocalDateTime.now());
        taRecommendCustomer.setReportDate(LocalDateTime.now());
        taRecommendCustomer.setOrgId(orgId);
        QueryWrapper<TaPerson> personQueryWrapper = new QueryWrapper<>();
        personQueryWrapper.eq("org_id", orgId);
        personQueryWrapper.eq("phone", params.getString("phone"));
        TaPerson currentPerson = taPersonMapper.selectOne(personQueryWrapper);
        if (null != currentPerson) {
            taRecommendCustomer.setPersonId(currentPerson.getPersonId());
        }

        // 时间格式 yyyy-MM-dd
        String at = params.getString("appointmentTime");
        if (!StringUtils.isEmpty(at)) {
            taRecommendCustomer.setAppointmentTime(DateUtils.dayToLocalDateime(at));
        }

//        taRecommendCustomer.setAppointmentTime((String) params.get("appointmentTime"));
        taRecommendCustomer.setVisiteNum(params.getInteger("visiteNum"));

        TaBuilding building = taBuildingMapper.selectById(params.getString("intention"));
        taRecommendCustomer.setIntention(building.getBuildingName());

        taRecommendCustomer.setRealtyManageType(params.getString("realtyManageType"));
        taRecommendCustomer.setDemandType(params.getString("demandType"));
        taRecommendCustomer.setPriceRange(params.getString("priceRange"));
        taRecommendCustomer.setEntryType(CommConstant.ENTRY_INPUT);
        // taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_READY);


        String status = params.getString("status");
        int statusInt = 0;
        if (StringUtils.isEmpty(status)) {
            taRecommendCustomer.setStatus(statusInt);
        } else {
            taRecommendCustomer.setStatus(Integer.parseInt(status));
        }

        taRecommendCustomer.setRecommendPerson(taPerson.getPersonId());

        int row = taRecommendCustomerMapper.insert(taRecommendCustomer);
        if (row < 1) {
            return ResponseBean.error("推荐客户失败", ResponseBean.ERROR_UNAVAILABLE);
        }

//        // 找到销售经理，并推送消息
//        TaPerson saleMan = taPersonMapper.getSalesExecutive();
//        if (null != saleMan && !StringUtils.isEmpty(saleMan.getMiniOpenid())) {
//            // 发送消息
//            iMiniAppService.sendNewCustomerMessage(saleMan.getMiniOpenid(), CommConstant.MINIAPP_INDEX, taRecommendCustomer.getName(), taRecommendCustomer.getPhone(), "", taPerson.getName());
//        }

        return ResponseBean.success(taRecommendCustomer);
    }


    @Override
    public ResponseBean reportCust(String paramStr, String openid, Integer orgId) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (null == params) {
            return ResponseBean.error("解析参数失败", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson taPerson = taPersons.get(0);

//        String checkResult = checkCustomerParams(params);
//        if (null != checkResult) {
//            return ResponseBean.error(checkResult, ResponseBean.ERROR_MISSING_PARAMS);
//        }

        if (StringUtils.isEmpty(params.getString("realtyConsultant"))) {
            return ResponseBean.error("置业顾问不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        // 查找置业顾问对应的 TaPerson 及 TaUser
        TaPerson consultantPerson = taPersonMapper.selectById(params.getString("realtyConsultant"));
        TaUser consultantUser = null;
        if (null == consultantPerson) {
            consultantUser = taUserMapper.selectById(params.getString("realtyConsultant"));
            if (null != consultantUser && null != consultantUser.getUserId() && consultantUser.getUserId() > 0) {
                QueryWrapper<TaPerson> query = new QueryWrapper<>();
                query.eq("org_id", consultantUser.getOrgId());
                query.eq("user_id", consultantUser.getUserId());
                query.last("limit 1");
                consultantPerson = taPersonMapper.selectOne(query);
            }
        } else {
            consultantUser = taUserMapper.selectById(consultantPerson.getUserId());
        }

        if (null == consultantUser || consultantUser.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("置业顾问不存在或已被注销", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 如果置业顾问还没有绑定小程序
        if (null == consultantPerson) {
            consultantPerson = new TaPerson();
        }

        TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
        taRecommendCustomer.setOrgId(orgId);
        taRecommendCustomer.setName(taPerson.getNickname());
        taRecommendCustomer.setPicture(taPerson.getAvatarurl());
        taRecommendCustomer.setPhone(params.getString("phone"));
        taRecommendCustomer.setSex(null == taPerson.getGender() ? null : ("1".equals(taPerson.getGender()) ? 1 : 2));
//        taRecommendCustomer.setDescribe(params.getString("describe"));
        taRecommendCustomer.setRealtyConsultant(consultantUser.getUserId().toString());
        //如果没有传building_id的情况构造building_id
        if (StringUtils.isEmpty(params.getString("buildingId")) && !StringUtils.isEmpty(params.getString("realtyConsultant"))) {
            QueryWrapper<TaPersonBuilding> taPersonBuildingQueryWrapper = new QueryWrapper<>();
            taPersonBuildingQueryWrapper.eq("person_id", consultantPerson.getPersonId()).or().eq("user_id", consultantUser.getUserId());
            List<TaPersonBuilding> taPersonBuildingList = taPersonBuildingMapper.selectList(taPersonBuildingQueryWrapper);
            if (taPersonBuildingList.size() > 0) {
                params.put("buildingId", taPersonBuildingList.get(0).getBuildingId());
            }
        }
        taRecommendCustomer.setBuildingId(params.getString("buildingId"));
        TaBuilding building = taBuildingMapper.selectById(params.getString("buildingId"));
        taRecommendCustomer.setIntention(building.getBuildingName());
        taRecommendCustomer.setReportRecommendStatus(CommConstant.VERIFY_AGREE);
        taRecommendCustomer.setCreateDate(LocalDateTime.now());
        taRecommendCustomer.setReportDate(LocalDateTime.now());
        taRecommendCustomer.setPersonId(taPerson.getPersonId());

        // 时间格式 yyyy-MM-dd
//        String at = params.getString("appointmentTime");
//        if (!StringUtils.isEmpty(at)) {
//            taRecommendCustomer.setAppointmentTime(DateUtils.day2LocalDateime(at));
//        }ni

//        taRecommendCustomer.setAppointmentTime((String) params.get("appointmentTime"));
//        taRecommendCustomer.setVisiteNum(params.getInteger("visiteNum"));
//        taRecommendCustomer.setIntention(params.getString("intention"));
//        taRecommendCustomer.setRealtyManageType(params.getString("realtyManageType"));
//        taRecommendCustomer.setDemandType(params.getString("demandType"));
//        taRecommendCustomer.setPriceRange(params.getString("priceRange"));
        taRecommendCustomer.setEntryType(CommConstant.ENTRY_VERIFY);
        taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
        taRecommendCustomer.setStatus(CommConstant.CUSTOMER_REPORT);
        QueryWrapper<TaPerson> personQueryWrapper = new QueryWrapper<>();
        personQueryWrapper.eq("org_id", orgId);
        personQueryWrapper.eq("phone", params.getString("phone"));
        TaPerson currentPerson = taPersonMapper.selectOne(personQueryWrapper);
        if (null != currentPerson) {
            if (currentPerson.getPersonType().equals(CommConstant.PERSON_REALTY_CONSULTANT)) {
                return ResponseBean.error("置业顾问不可以绑定置业顾问", ResponseBean.ERROR_ILLEGAL_PARAMS);
            }
            taRecommendCustomer.setPersonId(currentPerson.getPersonId());
        }


//        String status = params.getString("status");
//        if (null == status) status = "1";
//        taRecommendCustomer.setStatus(status);
//        taRecommendCustomer.setRecommendPerson(taPerson.getPersonId());
        taRecommendCustomer.setRecommendPerson(params.getString("realtyConsultant"));

        // 插入客户来源逻辑, 防止下面 if 里面的 return
        // 首次报备的客户, 写入客户来源表
        TaCustomerFrom customerFrom = null;
        if (!StringUtils.isEmpty(taRecommendCustomer.getBuildingId())) {
            Map<String, Number> counter = taCustomerFromMapper.countPerson(taRecommendCustomer.getOrgId(), taRecommendCustomer.getBuildingId(), taRecommendCustomer.getPersonId());
            boolean orgFirst = counter.get("orgCount").longValue() < 1;
            boolean projectFirst = counter.get("projectCount").longValue() < 1;
            if (projectFirst) {
                TaBuilding taBuilding = taBuildingMapper.selectById(taRecommendCustomer.getBuildingId());

                customerFrom = new TaCustomerFrom();
                customerFrom.setPersonId(taRecommendCustomer.getPersonId());
                customerFrom.setCustomerId(taRecommendCustomer.getCustomerId());
                customerFrom.setPersonName(taRecommendCustomer.getName());
                customerFrom.setOrgId(taRecommendCustomer.getOrgId());
//              customerFrom.setSceneId(sceneId);
                customerFrom.setIsOrgFirst(orgFirst);
                QueryWrapper<TaCustomerFrom> queryWrapper = new QueryWrapper<TaCustomerFrom>();
                queryWrapper.eq("person_id", taRecommendCustomer.getPersonId());
                queryWrapper.eq("org_id", taRecommendCustomer.getOrgId());
                queryWrapper.eq("building_id", taRecommendCustomer.getBuildingId());
                if (taCustomerFromMapper.selectList(queryWrapper).size() < 1) {
                    customerFrom.setIsProjectFirst(true);
                }
                customerFrom.setCreateDate(LocalDateTime.now());
                customerFrom.setBuildingId(taRecommendCustomer.getBuildingId());
                customerFrom.setBuildingName(taBuilding.getBuildingName());
                customerFrom.setSharePersonId(consultantPerson.getPersonId());
                customerFrom.setSharePersonName(consultantUser.getUserName());

                // 半小时内如果有当前人员的分享记录
                // 那么就认为当前客户是通过分享进入的
                TaSharePersonFrom personShare = taSharePersonFromMapper.getConsultantLastShare(taRecommendCustomer.getOrgId(),
                        taRecommendCustomer.getBuildingId(),
                        consultantUser.getUserId(),
                        taRecommendCustomer.getPersonId());
                if (null != personShare) {
                    // 强制转换 targetType
                    String targetType = personShare.getTargetType().replace("_share", "").replace("dynamic", "activity");
                    customerFrom.setTargetType(targetType);
                    customerFrom.setTargetId(personShare.getTargetId());
                    customerFrom.setTargetName(personShare.getTargetName());
                }

                taCustomerFromMapper.insert(customerFrom);
            }
        }


        // 报备有 10 天有效期
        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", taRecommendCustomer.getPhone());
        queryWrapper.eq("building_id", taRecommendCustomer.getBuildingId());
        queryWrapper.eq("org_id", taRecommendCustomer.getOrgId());
        queryWrapper.in("verify_status", CommConstant.VERIFY_AGREE, CommConstant.VERIFY_READY);
        List<TaRecommendCustomer> result = taRecommendCustomerMapper.selectList(queryWrapper);
        if (null != result && result.size() > 0) {
            String conName = "";
            TaPerson conPerson = taPersonMapper.selectById(result.get(0).getRealtyConsultant());
            if (null != conPerson) {
                if (null != consultantPerson && consultantPerson.getPersonId().equals(conPerson.getPersonId())) {
                    return ResponseBean.success("bound");
                }
                conName = conPerson.getName();
            } else {
                TaUser conUser = userService.getById(result.get(0).getRealtyConsultant());
                if (null != conUser) {
                    if (consultantUser.getUserId().equals(conUser.getUserId())) {
                        return ResponseBean.success("bound");
                    }
                    conName = conUser.getUserName();

                }
            }
            TaRecommendCustomer oldRecomendCustomer = result.get(0);
            if (!StringUtils.isEmpty(oldRecomendCustomer.getRealtyConsultant())) {
                return ResponseBean.error("您在当前项目的置业顾问是:" + conName, ResponseBean.ERROR_ILLEGAL_PARAMS);
            } else {
                oldRecomendCustomer.setRealtyConsultant(consultantUser.getUserId().toString());
                taRecommendCustomerMapper.updateById(oldRecomendCustomer);
                if (null != customerFrom) {
                    customerFrom.setCustomerId(oldRecomendCustomer.getCustomerId());
                    taCustomerFromMapper.updateById(customerFrom);
                }
                return ResponseBean.success(oldRecomendCustomer);
            }
        }

        int row = taRecommendCustomerMapper.insert(taRecommendCustomer);
        if (row < 1) {
            return ResponseBean.error("报备客户失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        if (null != customerFrom) {
            customerFrom.setCustomerId(taRecommendCustomer.getCustomerId());
            taCustomerFromMapper.updateById(customerFrom);
        }

        // 找到销售经理，并推送消息
//        TaPerson saleMan = taPersonMapper.getSalesExecutive();
//        if (null != saleMan && !StringUtils.isEmpty(saleMan.getMiniOpenid())) {
//            // 发送消息
//            iMiniAppService.sendNewCustomerMessage(saleMan, CommConstant.MINIAPP_INDEX, taRecommendCustomer.getName(), taRecommendCustomer.getPhone(), "", taPerson.getName());
//        }

        return ResponseBean.success(taRecommendCustomer);
    }

    String checkCustomerParams(JSONObject params) {
        if (null == params.getString("name")) {
            return "请设置客户姓名";
        }
        if (null == params.getString("phone")) {
            return "请设置客户电话";
        }
        if (null == params.getInteger("sex")) {
            return "请设置客户性别";
        }
        if (null == params.getString("intention")) {
            return "请设置意向楼盘";
        }

        return null;
    }


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

    @Override
    public IPage<TaRecommendCustomer> getUnSignedCustomerList(int pageNumber, int pageSize, String building, String personId) {
        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("building_id",building);
        queryWrapper.eq("realty_consultant", personId);
        queryWrapper.gt("status", CommConstant.MESSAGE_UNREAD);
        IPage<TaRecommendCustomer> page = new Page<>(pageNumber, pageSize);
        return taRecommendCustomerMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage getCustomerList(Integer status, int pageNumber, int pageSize, String building, String name, String tel, String consultName, String consultTel, String entryType, String verifyStatus, Integer sex, String customerType, Integer orgId, List<TaPersonBuilding> taPersonBuildingList, String sceneType, String startCreateDate, String endCreateDate, String sharePersonName, Integer belongStatus) {

        if (CommConstant.CUTOMER_TYPE_PUBLIC.equals(customerType)) {
            // 公客
            IPage<TaPerson> page = new Page<>(pageNumber, pageSize);
            // 公客就不用 buildingId 进行查询
            return taRecommendCustomerMapper.getPublicCustomerList(page, name, tel, entryType, verifyStatus, sex, orgId, consultTel, sceneType, taPersonBuildingList, building, startCreateDate, endCreateDate, sharePersonName, belongStatus);
        } else {
            // 私客
            IPage<TaRecommendCustomer> page = new Page<>(pageNumber, pageSize);
            return taRecommendCustomerMapper.getCustomerList(page, building, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId, status, taPersonBuildingList, sceneType, startCreateDate, endCreateDate, sharePersonName);
        }

    }

    @Override
    public IPage<TaPerson> getIndependentAgents(int pageNumber, int pageSize, String name, String tel, String channelId, Integer orgId) {
        IPage<TaPerson> page = new Page<>(pageNumber, pageSize);
        return taRecommendCustomerMapper.getIndependentAgents(page, name, tel, channelId, orgId);
    }

    @Override
    public IPage<TaRecommendCustomer> getRecCustomerList(int pageNumber, int pageSize, String building, String name, String tel, String consultName, String consultTel, String entryType, String verifyStatus, Integer sex, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
        IPage<TaRecommendCustomer> page = new Page<>(pageNumber, pageSize);
        return taRecommendCustomerMapper.getRecCustomerList(page, building, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId, taPersonBuildingList);
    }


    @Override
    public IPage<TaRecommendCustomer> getRepCustomerList(int pageNumber, int pageSize, String building, String name, String tel, String consultName, String consultTel, String entryType, String verifyStatus, Integer sex, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
        IPage<TaRecommendCustomer> page = new Page<>(pageNumber, pageSize);
        return taRecommendCustomerMapper.getRepCustomerList(page, building, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId, taPersonBuildingList);
    }

    @Override
    public TaRecommendCustomer getCustomerById(String customerId) {
        return taRecommendCustomerMapper.getCustomerById(customerId);
    }


    @Override
    public TaRecommendCustomer getCustomerDetail(String customerId, int pageNumber, int pageSize, List<TaPersonBuilding> taPersonBuildingList, String buildingId) {
        String personId = taRecommendCustomerMapper.getCustomerById(customerId).getPersonId();
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.getCustomerDetail(customerId, personId);
        TaPerson person = taPersonMapper.selectById(personId);
        if (!StringUtils.isEmpty(personId)) {
            IPage<TaPersonVisitRecord> page = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> taPersonVisitRecordIPage = taPersonVisitRecordMapper.visitRecordByPersonId(page, personId, taPersonBuildingList, buildingId);
            List<TaPersonVisitRecord> records = taPersonVisitRecordIPage.getRecords();
            records.forEach(e -> {
                //获取活动标题
                if ("activity".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaBuildingDynamic taBuildingDynamic = taBuildingDynamicMapper.selectById(e.getTargetId());
                    if (null != taBuildingDynamic) {
                        e.setActivityName(taBuildingDynamic.getTitle());
                    }

                }
                //获取拼团标题
                if ("group".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaShareActivity taShareActivity = taShareActivityMapper.selectById(e.getTargetId());
                    if (null != taShareActivity) {
                        e.setActivityName(taShareActivity.getActivityName());
                    }
                }
                //获取助力标题
                if ("help".equals(e.getEventType()) && null != e.getTargetId()) {
                    HelpActivity helpActivity = helpActivityMapper.selectById(e.getTargetId());
                    if (null != helpActivity) {
                        e.setActivityName(helpActivity.getTitle());
                    }
                }
                //获取咨询标题
                if ("news".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaNews taNews = taNewsMapper.selectById(e.getTargetId());
                    if (null != taNews) {
                        e.setActivityName(taNews.getNewsName());
                    }
                }
                //获取H5活动标题
                if ("h5".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaDrainage taDrainage = taDrainageMapper.selectById(e.getTargetId());
                    if (null != taDrainage) {
                        e.setActivityName(taDrainage.getName());
                    }
                }
            });
            taPersonVisitRecordIPage.setRecords(records);
            taRecommendCustomer.setVisitRecords(taPersonVisitRecordIPage);
            taRecommendCustomer.setVisitTimes(taPersonVisitRecordIPage.getRecords().size());
            taRecommendCustomer.setIntentions(taRecommendCustomerMapper.getCustomerIntentions(personId, taPersonBuildingList));
        }
        if (!StringUtils.isEmpty(taRecommendCustomer.getRealtyConsultant())) {
            TaPerson consultant = taPersonMapper.getById(taRecommendCustomer.getRealtyConsultant());
            TaUser user = new TaUser();
            if (null == consultant) {
                user = userService.getById(taRecommendCustomer.getRealtyConsultant());
            } else {
                user = userService.getById(consultant.getUserId());
            }
            if (null != user) {
                List<String> projects = taPersonMapper.getUserProjects(user.getUserId());
                if (projects.size() > 0) {
                    user.setProjects(projects);
                }
                taRecommendCustomer.setConsultant(user);
            }
        }
        //构造来源类型
        taRecommendCustomer.setPersonFrom("");
        if (null != person) {
            Map<String, String> geoInfo = new HashMap<>();
            geoInfo.put("provience", person.getProvince());
            geoInfo.put("country", person.getCountry());
            TdCity city = cityMapper.selectById(person.getCity());
            if (null != city) {
                geoInfo.put("city", city.getName());
            } else {
                geoInfo.put("city", "未知");
            }
            taRecommendCustomer.setGeoInfo(geoInfo);

            QueryWrapper<TaPersonFromRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", person.getOrgId());
            queryWrapper.eq("person_id", person.getPersonId());
            queryWrapper.eq("is_first_time", 1);
            List<TaPersonFromRecord> taPersonFromRecords = taPersonFromRecordMapper.selectList(queryWrapper);
            if (taPersonFromRecords.size() > 0) {
                QueryWrapper<TdWxDict> tdWxDictQueryWrapper = new QueryWrapper<>();
                tdWxDictQueryWrapper.eq("scene_id", taPersonFromRecords.get(0).getSceneId());
                TdWxDict tdWxDict = tdWxDictMapper.selectOne(tdWxDictQueryWrapper);
                taRecommendCustomer.setPersonFrom(null != tdWxDict ? tdWxDict.getSceneAlias() : "");
            }
        }

        return taRecommendCustomer;
    }

    @Override
    public TaPerson getPublicCustomerDetail(String personId, int pageNumber, int pageSize, List<TaPersonBuilding> taPersonBuildingList, String buildingId) {
        TaPerson taPerson = taPersonMapper.getById(personId);
        if (!StringUtils.isEmpty(personId)) {
            IPage<TaPersonVisitRecord> page = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> taPersonVisitRecordIPage = taPersonVisitRecordMapper.visitRecordByPersonId(page, personId, taPersonBuildingList, buildingId);
            List<TaPersonVisitRecord> records = taPersonVisitRecordIPage.getRecords();
            records.forEach(e -> {
                //获取活动标题
                if ("activity".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaBuildingDynamic taBuildingDynamic = taBuildingDynamicMapper.selectById(e.getTargetId());
                    if (null != taBuildingDynamic) {
                        e.setActivityName(taBuildingDynamic.getTitle());
                    }

                }
                //获取拼团标题
                if ("group".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaShareActivity taShareActivity = taShareActivityMapper.selectById(e.getTargetId());
                    if (null != taShareActivity) {
                        e.setActivityName(taShareActivity.getActivityName());
                    }
                }
                //获取助力标题
                if ("help".equals(e.getEventType()) && null != e.getTargetId()) {
                    HelpActivity helpActivity = helpActivityMapper.selectById(e.getTargetId());
                    if (null != helpActivity) {
                        e.setActivityName(helpActivity.getTitle());
                    }
                }
                //获取咨询标题
                if ("news".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaNews taNews = taNewsMapper.selectById(e.getTargetId());
                    if (null != taNews) {
                        e.setActivityName(taNews.getNewsName());
                    }
                }
                //获取H5活动标题
                if ("h5".equals(e.getEventType()) && null != e.getTargetId()) {
                    TaDrainage taDrainage = taDrainageMapper.selectById(e.getTargetId());
                    if (null != taDrainage) {
                        e.setActivityName(taDrainage.getName());
                    }
                }
            });
            taPersonVisitRecordIPage.setRecords(records);
            taPerson.setVisitRecords(taPersonVisitRecordIPage);
            taPerson.setVisitTimes(taPersonVisitRecordIPage.getRecords().size());
            taPerson.setIntentions(taRecommendCustomerMapper.getCustomerIntentions(personId, taPersonBuildingList));
            taPerson.setDuration(taPersonVisitRecordMapper.getDurationByPersonId(personId));
            taPerson.setVisitTime(taPersonVisitRecordMapper.getFirstVisitTimeByPersonId(personId));
            TdCity city = cityMapper.selectById(taPerson.getCity());
            if (null != city) {
                taPerson.setCity(city.getName());
            }

            //构造来源类型
            taPerson.setPersonFrom("");
            if (null != taPerson) {
                QueryWrapper<TaPersonFromRecord> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("org_id", taPerson.getOrgId());
                queryWrapper.eq("person_id", taPerson.getPersonId());
                queryWrapper.eq("is_first_time", 1);
                List<TaPersonFromRecord> taPersonFromRecords = taPersonFromRecordMapper.selectList(queryWrapper);
                if (taPersonFromRecords.size() > 0) {
                    QueryWrapper<TdWxDict> tdWxDictQueryWrapper = new QueryWrapper<>();
                    tdWxDictQueryWrapper.eq("scene_id", taPersonFromRecords.get(0).getSceneId());
                    TdWxDict tdWxDict = tdWxDictMapper.selectOne(tdWxDictQueryWrapper);
                    taPerson.setPersonFrom(null != tdWxDict ? tdWxDict.getSceneAlias() : "");
                }
            }
        }
        return taPerson;
    }

    @Override
    public IPage<TaRecommendCustomer> getCustomersIRecommended(int pageNumber, int pageSize, String customerId, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {

        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
        // todo
        // 此处可能不是 person_id 而是 recommend_person
        IPage<TaRecommendCustomer> page = new Page<>(pageNumber, pageSize);
//        queryWrapper.eq("recommend_person",customerId);
////        queryWrapper.eq("building_id",building);
//        queryWrapper.eq("status", CommConstant.VERIFY_AGREE);
//        queryWrapper.eq("org_id", orgId);
        return taRecommendCustomerMapper.getCustomersIRecommended(page, customerId, CommConstant.STATUS_NORMAL, orgId, taPersonBuildingList);
    }

    @Override
    public TaRecommendCustomer newByPerson(TaPerson person) {
        // 没有手机号, 暂时不生成客户信息
        String phone = StringUtils.ifNull(person.getTel(), person.getPhone());
        if (StringUtils.isEmpty(phone)) {
            return null;
        }

        // 已经存在的, 随机返回一条记录
        List<TaRecommendCustomer> custs = getCustomerByPhone(phone, person.getOrgId());
        if (null != custs && custs.size() > 0) {
            return custs.get(0);
        }

        TaRecommendCustomer cust = new TaRecommendCustomer();
        cust.setName(StringUtils.ifNull(person.getName(), person.getNickname()));
        cust.setSex(null == person.getSex() ? str2Int(person.getGender()) : person.getSex());
        cust.setPhone(phone);
        cust.setPicture(StringUtils.ifNull(person.getPhoto(), person.getAvatarurl()));
        cust.setCountry(person.getCountry());
        cust.setCity(person.getCity());
        cust.setProvince(person.getProvince());
        // 审核同意
        cust.setVerifyStatus(CommConstant.VERIFY_AGREE);
        // 报备状态
        cust.setStatus(CommConstant.CUSTOMER_REPORT);
        // 当前日期
        cust.setReportDate(LocalDateTime.now());

        if (taRecommendCustomerMapper.insert(cust) > 0) {
            return cust;
        } else {
            log.error("依据人员新增推荐客户失败");
            return null;
        }
    }

    @Override
    public ResponseBean batchConsultantAssist(TaUser taUser, Integer orgId) {
        Integer failNum = 0;
        if (CollectionUtils.isNotEmpty(taUser.getCustomerIds())) {
            for (TaRecommendCustomer taRecommendCustomer : taUser.getCustomerIds()) {
                ResponseBean responseBean = consultantAssist(taUser, taRecommendCustomer.getCustomerId(), orgId);
                if (responseBean.getCode() != 1000) {
                    failNum++;
                }
            }
        }
        JSONObject obj = new JSONObject();
        obj.put("failNum", failNum);
        obj.put("totalNum", taUser.getCustomerIds().size());
        return ResponseBean.success(obj);
    }

    @Override
    public ResponseBean consultantAssist(TaUser taUser, String customerId, Integer orgId) {
        logger.info("公客分配置业顾问 接收参数，taUser={}，customerId={}，orgId={}",
                JSONObject.toJSONString(taUser), customerId, orgId);

        ResponseBean responseBean = new ResponseBean();

        // 1.校验置业顾问
        QueryWrapper<TaUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", taUser.getUserId());
        TaUser userInfo = taUserMapper.selectOne(queryWrapper);

        QueryWrapper<TaPersonBuilding> taPersonBuildingQueryWrapper = new QueryWrapper();
        taPersonBuildingQueryWrapper.eq("user_id", taUser.getUserId());
        taPersonBuildingQueryWrapper.eq(!StringUtils.isEmpty(taUser.getBuildingId()), "building_id", taUser.getBuildingId());
        TaPersonBuilding taPersonBuilding = taPersonBuildingMapper.selectOne(taPersonBuildingQueryWrapper);

        if (null == userInfo || CommConstant.STATUS_NORMAL != userInfo.getStatus()) {
            responseBean.addError("置业顾问不存在或已被注销");
            return responseBean;
        }

        // 2.根据customerId获取personId
        QueryWrapper<TaRecommendCustomer> customerQueryWrapper = new QueryWrapper<>();
        customerQueryWrapper.eq("customer_id", customerId);
        customerQueryWrapper.nested(q -> q.isNull("realty_consultant").or().eq("realty_consultant", ""));
//        customerQueryWrapper.isNull("realty_consultant");
        TaRecommendCustomer customerInfo = taRecommendCustomerMapper.selectOne(customerQueryWrapper);
        if (customerInfo == null) {
            logger.info("公客分配置业顾问 customerInfo为空");
            responseBean.addError("分配客户失败");
            return responseBean;
        }

        // 3.判断是否有buildingId,有则直接更新数据
        if (!StringUtils.isEmpty(customerInfo.getBuildingId())) {
            logger.info("公客分配置业顾问 customer={}", JSONObject.toJSONString(customerInfo));
            customerInfo.setRealtyConsultant(userInfo.getUserId().toString());
            responseBean.addSuccess(taRecommendCustomerMapper.updateById(customerInfo));
            return responseBean;
        }

        // 4.校验公客是否已经是分配项目下的私客
        QueryWrapper<TaRecommendCustomer> customerQueryWrapper2 = new QueryWrapper<>();
        customerQueryWrapper2.eq("org_id", orgId);
        customerQueryWrapper2.eq("person_id", customerInfo.getPersonId());
        customerQueryWrapper2.eq("building_id", taPersonBuilding.getBuildingId());
        customerQueryWrapper2.eq("status", CommConstant.CUSTOMER_REPORT);
        customerQueryWrapper2.eq("verify_status", CommConstant.VERIFY_AGREE);
        customerQueryWrapper2.isNotNull("realty_consultant");
        TaRecommendCustomer customerInfo2 = taRecommendCustomerMapper.selectOne(customerQueryWrapper2);
        if (customerInfo2 != null) {
            logger.info("客户已在当前项目私客中，可以继续分配给其他项目");
            responseBean.addError("客户已在当前项目私客中，可以继续分配给其他项目");
            return responseBean;
        }

        // 5.无buildingId，新增一条私客数据
        TaPerson taPerson = taPersonMapper.getById(customerInfo.getPersonId());
        if (taPerson == null) {
            logger.info("公客分配置业顾问 taPerson为空");
            responseBean.addError("分配客户失败");
            return responseBean;
        }

        TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
        taRecommendCustomer.setOrgId(orgId);
        taRecommendCustomer.setName(taPerson.getNickname());
        taRecommendCustomer.setPicture(taPerson.getAvatarurl());
        taRecommendCustomer.setPhone(taPerson.getPhone());
        taRecommendCustomer.setSex(null == taPerson.getGender() ? null : ("1".equals(taPerson.getGender()) ? 1 : 2));
        taRecommendCustomer.setRealtyConsultant(userInfo.getUserId().toString());
        taRecommendCustomer.setBuildingId(taPersonBuilding.getBuildingId());
        TaBuilding building = taBuildingMapper.selectById(taPersonBuilding.getBuildingId());
        taRecommendCustomer.setIntention(building.getBuildingName());
        taRecommendCustomer.setReportRecommendStatus(CommConstant.VERIFY_AGREE);
        taRecommendCustomer.setCreateDate(LocalDateTime.now());
        taRecommendCustomer.setReportDate(LocalDateTime.now());
        taRecommendCustomer.setPersonId(taPerson.getPersonId());
        taRecommendCustomer.setEntryType(CommConstant.ENTRY_VERIFY);
        taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
        taRecommendCustomer.setStatus(CommConstant.CUSTOMER_REPORT);
        taRecommendCustomer.setPersonId(taPerson.getPersonId());
        taRecommendCustomer.setRecommendPerson(taPerson.getRecommendPerson());

        int row = taRecommendCustomerMapper.insert(taRecommendCustomer);
        if (row < 1) {
            responseBean.addError("分配客户失败");
            return responseBean;
        }
        responseBean.addSuccess(taRecommendCustomer);
        return responseBean;
    }

    private List<TaRecommendCustomer> getCustomerByPhone(String phone, Integer orgId) {
        QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("phone", phone);
        queryWrapper.gt("status", CommConstant.STATUS_DELETE);
        queryWrapper.orderByDesc("report_date");

        List<TaRecommendCustomer> custs = taRecommendCustomerMapper.selectList(queryWrapper);
        return custs;
    }

    private Integer str2Int(String str) {
        if (null == str) {
            return null;
        }

        try {
            return Integer.valueOf(str);
        } catch (Exception e) {
            return 0;
        }
    }


    @Override
    public List<ExcelRecommendCustomer> getRecCustomerExport(Integer orgId, Integer pageCode, Integer pageSize, List<TaPersonBuilding> taPersonBuildingList) {
        return taRecommendCustomerMapper.getRecCustomerExport(orgId, pageCode, pageSize, taPersonBuildingList);
    }

    @Override
    public Integer getRecCustomerExportCount(Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
        return taRecommendCustomerMapper.getRecCustomerExportCount(orgId, taPersonBuildingList);
    }


    @Override
    public Integer getRepCustomerReportCount(String building, String name, String tel, String consultName, String consultTel, String entryType, String verifyStatus, Integer sex, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
        return taRecommendCustomerMapper.getRepCustomerReportCount(building, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId, taPersonBuildingList);
    }

    @Override
    public List<ReporRecommendCustomer> getRepCustomerReportExport(String building, String name, String tel, String consultName, String consultTel, String entryType, String verifyStatus, Integer sex, Integer orgId, Integer pageCode, Integer pageSize, List<TaPersonBuilding> taPersonBuildingList) {
        return taRecommendCustomerMapper.getRepCustomerReportExport(building, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId, pageCode, pageSize, taPersonBuildingList);
    }


    @Override
    public Integer getIndependentAgentsCount(Integer orgId) {
        return taRecommendCustomerMapper.getIndependentAgentsCount(orgId);
    }

    @Override
    public List<AgentsRecommendCustomer> getIndependentAgentsExport(String name, String tel, String channelId, Integer orgId, Integer pageCode, Integer pageSize) {
        return taRecommendCustomerMapper.getIndependentAgentsExport(name, tel, channelId, orgId, pageCode, pageSize);
    }

    /**
     * 查询我的客户人数集合
     *
     * @param openid
     * @return
     */
    @Override
    public ResponseBean getMyCustStatistics(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> map = taRecommendCustomerMapper.getMyCustStatistics(taPerson.getPersonId(), taPerson.getUserId(), taPerson.getOrgId());
        return ResponseBean.success(map);
    }

    /**
     * 分页查询我的跟进客户集合
     *
     * @param pageNumber
     * @param pageSize
     * @param openid
     * @param name
     * @param phone
     * @param status
     * @param startReportDate
     * @param endReportDate
     * @param startArrivalDate
     * @param endArrivalDate
     * @return
     */
    @Override
    public ResponseBean getMyCustFollowOrClinch(Integer pageNumber, Integer pageSize, String openid, String type, String name, String phone, Integer status, String startReportDate, String endReportDate, String startArrivalDate, String endArrivalDate) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);

        IPage<TaRecommendCustomer> page = new Page<>();
        page.setCurrent(pageNumber);
        page.setSize(pageSize);

        //分页获取跟进客户status != 4的为跟进客户， status = 4的为成交客户 根据type区分  follow 跟进  clinch 成交
        IPage<TaRecommendCustomer> result = taRecommendCustomerMapper.getMyCustFollowOrClinch(page, taPerson.getPersonId(), taPerson.getUserId(), taPerson.getOrgId(), type, name, phone, status, startReportDate, endReportDate, startArrivalDate, endArrivalDate);
        return ResponseBean.success(result);
    }

    /**
     * 获取盘客工具下我的客户详情
     *
     * @param customerId
     * @param openid
     * @return
     */
    @Override
    public ResponseBean getMyCustDetail(String customerId, String openid) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.getMyCustDetailById(customerId);
        //添加跟进行为
        addCustomerFpllowUp(taPerson, taRecommendCustomer, "查看客户详情");
        return ResponseBean.success(taRecommendCustomer);
    }

    /**
     * 更新我的客户基本信息
     *
     * @param taRecommendCustomer
     * @param openid
     * @return
     */
    @Override
    public ResponseBean updateMyCust(TaRecommendCustomer taRecommendCustomer, String openid) {
        List<TaPerson> taPersons = getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = taPersons.get(0);
        taRecommendCustomerMapper.updateById(taRecommendCustomer);
        //添加跟进行为
        addCustomerFpllowUp(taPerson, taRecommendCustomer, "编辑客户信息");
        return ResponseBean.success(taRecommendCustomer);
    }

    //添加跟进行为
    private void addCustomerFpllowUp(TaPerson taPerson, TaRecommendCustomer taRecommendCustomer, String recordType) {
        TaCustomerFollowUpRecord taCustomerFollowUpRecord = new TaCustomerFollowUpRecord();
        taCustomerFollowUpRecord.setOrgId(taPerson.getOrgId());
        taCustomerFollowUpRecord.setCreateDate(LocalDateTime.now());
        taCustomerFollowUpRecord.setCustomerId(taRecommendCustomer.getCustomerId());
        taCustomerFollowUpRecord.setRecordType(recordType);
        taCustomerFollowUpRecord.setFollowerId(taPerson.getPersonId());
        taCustomerFollowUpRecord.setCustomerSex(taRecommendCustomer.getSex());
        customerFollowUpRecordMapper.insert(taCustomerFollowUpRecord);
    }

}
