package com.fs.crm.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.DataScope;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.CluesUtils;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyDeptMapper;
import com.fs.company.mapper.CompanyMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.crm.domain.*;
import com.fs.crm.dto.CrmCustomerAssignCompanyDTO;
import com.fs.crm.dto.CrmCustomerAssignUserDTO;
import com.fs.crm.enums.CustomerLogEnum;
import com.fs.crm.mapper.CrmCustomerAssignMapper;
import com.fs.crm.mapper.CrmCustomerLogsMapper;
import com.fs.crm.mapper.CrmCustomerMapper;
import com.fs.crm.mapper.CrmCustomerUserMapper;
import com.fs.crm.param.*;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.crm.service.ICrmMsgService;
import com.fs.crm.vo.*;
import com.fs.jpush.service.JpushService;
import com.fs.qwApi.param.QwCustomerDetailParam;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.service.ISysDictTypeService;
import lombok.Synchronized;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 客户Service业务层处理
 *
 * @author fs
 * @date 2022-12-21
 */
@Service
public class CrmCustomerServiceImpl implements ICrmCustomerService
{
    @Autowired
    private CrmCustomerMapper crmCustomerMapper;
    @Autowired
    private CrmCustomerLogsMapper logsMapper;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private CompanyDeptMapper companyDeptMapper;
    @Autowired
    private CrmCustomerUserMapper crmCustomerUserMapper;
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private ICrmMsgService msgService;
    @Autowired
    private CrmCustomerAssignMapper assignMapper;
    @Autowired
    private JpushService jpushService;

    @Autowired
    private ISysDictTypeService dictTypeService;
    /**
     * 查询客户
     *
     * @param customerId 客户ID
     * @return 客户
     */
    @Override
    public CrmCustomer selectCrmCustomerById(Long customerId)
    {
        return crmCustomerMapper.selectCrmCustomerById(customerId);
    }

    @Override
    public CrmCustomer selectCrmCustomerByMobile(CrmCustomer customer) {
        return crmCustomerMapper.selectCrmCustomerByMobile(customer);
    }


    /**
     *   根据userid和外部联系人id获取到客户详情
     */
    @Override
    public CrmCustomer getCustomerDetailsH5(QwCustomerDetailParam param) {
        return crmCustomerMapper.getCustomerDetailsH5(param);
    }
    /**
     * 查询客户列表
     *
     * @param crmCustomer 客户
     * @return 客户
     */
    @Override
    public List<CrmCustomer> selectCrmCustomerList(CrmCustomer crmCustomer)
    {
        return crmCustomerMapper.selectCrmCustomerList(crmCustomer);
    }

    /**
     * 新增客户
     *
     * @param crmCustomer 客户
     * @return 结果
     */
    @Override
    public int insertCrmCustomer(CrmCustomer crmCustomer)
    {
        if(crmCustomer.getCreateTime()==null){
            crmCustomer.setCreateTime(DateUtils.getNowDate());
        }
        return crmCustomerMapper.insertCrmCustomer(crmCustomer);
    }

    /**
     * 修改客户
     *
     * @param crmCustomer 客户
     * @return 结果
     */
    @Override
    public int updateCrmCustomer(CrmCustomer crmCustomer)
    {
        crmCustomer.setUpdateTime(DateUtils.getNowDate());
        return crmCustomerMapper.updateCrmCustomer(crmCustomer);
    }

    /**
     * 批量删除客户
     *
     * @param customerIds 需要删除的客户ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerByIds(Long[] customerIds)
    {
        return crmCustomerMapper.deleteCrmCustomerByIds(customerIds);
    }

    /**
     * 删除客户信息
     *
     * @param customerId 客户ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerById(Long customerId)
    {
        return crmCustomerMapper.deleteCrmCustomerById(customerId);
    }

    @Override
    public List<CrmFullCustomerListQueryVO> selectCrmFullCustomerListQuery(CrmFullCustomerListQueryParam param) {
        return crmCustomerMapper.selectCrmFullCustomerListQuery(param);
    }

    @Override
    public CrmCustomerQueryVO selectCrmFullCustomerQueryByCustomerId(Long customerId) {
        return crmCustomerMapper.selectCrmFullCustomerQueryByCustomerId(customerId);
    }

    @Override
    public String importLineCustomer(List<CrmLineCustomerImportParam> list, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder importMsg = new StringBuilder();
        for (CrmLineCustomerImportParam customer : list)
        {
            try
            {
                String regex = "^1[3456789]\\d{9}$";
                if(!customer.getMobile().matches(regex)){
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、客户 " + customer.getMobile() + " 导入失败：电话号码格式不正确";
                    failureMsg.append(msg);
                    continue;
                }
                CrmCustomer crmCustomer=new CrmCustomer();
                BeanUtils.copyProperties(customer,crmCustomer);
                crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
                crmCustomer.setIsDel(0);
                crmCustomer.setIsLine(1);
                crmCustomer.setIsReceive(0);
                crmCustomer.setStatus(0);

                ////当手动导入飞鱼平台线索时
                if(StringUtils.isEmpty(crmCustomer.getThirdAccount()) &&  CluesUtils.trafficSourceList.contains(crmCustomer.getTrafficSource())){
                    List<SysDictData> listSource=dictTypeService.selectDictDataByType("crm_customer_source");
                    SysDictData sysDictData = listSource.stream().filter(dictData -> dictData.getDictValue().equals(customer.getSource())).findAny().orElse(null);
                    if(sysDictData!=null && CluesUtils.accountMap.containsKey(sysDictData.getDictLabel())){
                        crmCustomer.setThirdAccount(CluesUtils.accountMap.get(sysDictData.getDictLabel()));
                    }
                }
                crmCustomer.setImportType(0);
                crmCustomer.setSource(Integer.parseInt(customer.getSource()));
                crmCustomer.setCreateTime(new Date());
                crmCustomerMapper.insertCrmCustomer(crmCustomer);
                successNum++;
                successMsg.append("<br/>" + successNum + "、客户 " + customer.getCustomerName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + customer.getCustomerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        importMsg.append(failureMsg.toString());
        importMsg.append(successMsg.toString());
        return importMsg.toString();
    }

    @Override
    public List<CrmCustomerListVO> selectCrmCustomerListVO(CrmCustomer crmCustomer) {
        List<CrmCustomerListVO> list = crmCustomerMapper.selectCrmCustomerListVO(crmCustomer);
//        for (CrmCustomerListVO listVO : list){
//            int duplicates = crmCustomerMapper.selectCrmCustomerMobileNum(listVO.getMobile());
//            if (duplicates > 1){
//                listVO.setCustomerName("[重}"+listVO.getCustomerName());
//            }
//        }
        return list;
    }


    @Override
    public List<CrmCustomerListVO> selectCrmCustomerListQueryParam(CrmCustomerListQueryParam crmCustomer) {
        return crmCustomerMapper.selectCrmCustomerListQueryParam(crmCustomer);
    }

    @Override
    public List<CrmMyCustomerListQueryVO> selectCrmMyCustomerListQuery(CrmMyCustomerListQueryParam param) {
        return crmCustomerMapper.selectCrmMyCustomerListQuery(param);
    }

    @Override
    @DataScope(deptAlias = "c",userAlias = "c")
    public List<CrmCustomerListQueryVO> selectCrmCustomerListQuery(CrmCustomerListQueryParam param) {
        if (param.getIsReceive() != null && param.getIsReceive() == 0){
            param.setIsLine(1);
        }
        return crmCustomerMapper.selectCrmCustomerListQuery(param);
    }

    @Override
    public List<CrmLineCustomerListQueryVO> selectCrmLineCustomerListQuery(CrmLineCustomerListQueryParam param) {
        List<CrmLineCustomerListQueryVO> list = crmCustomerMapper.selectCrmLineCustomerListQuery(param);
//        CrmCustomer customer = new CrmCustomer();
//        for (CrmLineCustomerListQueryVO listVO : list){
//            customer.setMobile(listVO.getMobile());
//            customer.setCompanyId(listVO.getCompanyId());
//            int duplicates = crmCustomerMapper.selectCrmCustomerMobileNum(customer);
//            if (duplicates > 1){
//                listVO.setCustomerName("[重}"+listVO.getCustomerName());
//            }
//        }
        return list;
    }

//    @Override
//    @Transactional
//    public R assignDept(CrmCustomeAssignParam param, String operName) {
//        CompanyDept companyDept=companyDeptMapper.selectCompanyDeptById(param.getDeptId());
//        CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(param.getCustomerId());
//        customer.setIsLine(0);
//        customer.setDeptId(companyDept.getDeptId());
//        customer.setUpdateTime(new Date());
//        crmCustomerMapper.updateCrmCustomer(customer);
//        //写日志
//        CrmCustomerLogs logs=new CrmCustomerLogs();
//        logs.setCustomerId(customer.getCustomerId());
//        logs.setCreateTime(new Date());
//        logs.setLogsType(CustomerLogEnum.ASSIGN_DEPT.getValue());
//        logs.setTitle(CustomerLogEnum.ASSIGN_DEPT.getDesc());
//        logs.setRemark(operName+"分配客户"+customer.getCustomerName()+"给部门"+companyDept.getDeptName());
//        logsMapper.insertCrmCustomerLogs(logs);
//        return R.ok();
//    }

    @Override
    @Transactional
    public R receive(CrmCustomeReceiveParam param, String operName) {
        CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(param.getCustomerId());
//        if(customer!=null&&customer.getStatus()==0){
//            return R.error("已锁定");
//        }
        if(customer!=null&&customer.getIsReceive()==1){
            return R.error("客户已认领");
        }
        //写入认领记录
        CrmCustomerUser crmCustomerUser=new CrmCustomerUser();
        crmCustomerUser.setCustomerId(customer.getCustomerId());
        crmCustomerUser.setCompanyId(param.getCompanyId());
        crmCustomerUser.setCompanyUserId(param.getCompanyUserId());
        crmCustomerUser.setStatus(1);
        crmCustomerUser.setCreateTime(new Date());
        crmCustomerUser.setStartTime(new Date());
        crmCustomerUser.setIsPool(0);
        //结束时间按规则配置 //配置入公海规则 TODO
        crmCustomerUserMapper.insertCrmCustomerUser(crmCustomerUser);
        customer.setReceiveUserId(param.getCompanyUserId());
        customer.setIsReceive(1);
        customer.setReceiveTime(new Date());
        customer.setCustomerUserId(crmCustomerUser.getCustomerUserId());
        customer.setDeptId(param.getDeptId());
        crmCustomerMapper.updateCrmCustomer(customer);
        //写日志
        CrmCustomerLogs logs=new CrmCustomerLogs();
        logs.setCustomerId(customer.getCustomerId());
        logs.setCreateTime(new Date());
        logs.setLogsType(CustomerLogEnum.RECEIVE.getValue());
        logs.setTitle(CustomerLogEnum.RECEIVE.getDesc());
        logs.setRemark(operName+"认领客户"+customer.getCustomerName());
        logs.setCompanyUserId(param.getCompanyUserId());
        logsMapper.insertCrmCustomerLogs(logs);
        msgService.insertCrmMsg(new CrmMsg(1,"认领客户","您认领了客户："+customer.getCustomerName(),customer.getCompanyId(),param.getCompanyUserId(),customer.getCustomerId()));

        CompanyUser companyUser=companyUserMapper.selectCompanyUserById(param.getCompanyUserId());
        if(StringUtils.isNotEmpty(companyUser.getJpushId())){
            Map<String, String> extrasMap=new HashMap<>();
            extrasMap.put("customerId",param.getCustomerId().toString());
            extrasMap.put("type","1");
            try {
                jpushService.sendRegisterIdPush("客户消息","您认领了一个客户",extrasMap,companyUser.getJpushId());
            } catch (APIConnectionException e) {
            } catch (APIRequestException e) {
            }
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R recover(CrmCustomeRecoverParam param, String operName) {
        CrmCustomerUser crmCustomerUser=crmCustomerUserMapper.selectCrmCustomerUserById(param.getCustomerUserId());
        CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(crmCustomerUser.getCustomerId());
//        if(customer!=null&&customer.getStatus()==0){
//            return R.error("已锁定");
//        }
        if(crmCustomerUser!=null&&crmCustomerUser.getIsPool()==1){
            return R.error("客户已在公海中");
        }
        crmCustomerUser.setIsPool(1);
        crmCustomerUser.setPoolTime(new Date());
        crmCustomerUserMapper.updateCrmCustomerUser(crmCustomerUser);
        customer.setIsPool(1);
        customer.setReceiveUserId(0L);
        customer.setIsReceive(0);
        customer.setPoolTime(new Date());
        customer.setCustomerUserId(0L);
        crmCustomerMapper.updateCrmCustomer(customer);
        //写日志
        CrmCustomerLogs logs=new CrmCustomerLogs();
        logs.setCustomerId(customer.getCustomerId());
        logs.setCreateTime(new Date());
        logs.setLogsType(CustomerLogEnum.RECOVER.getValue());
        logs.setTitle(CustomerLogEnum.RECOVER.getDesc());
        logs.setRemark(operName+"回收客户"+customer.getCustomerName());
        logs.setCompanyUserId(param.getCompanyUserId());
        logsMapper.insertCrmCustomerLogs(logs);
        msgService.insertCrmMsg(new CrmMsg(1,"回收客户","客户："+customer.getCustomerName()+"已回收",customer.getCompanyId(),param.getCompanyUserId(),customer.getCustomerId()));

        CompanyUser companyUser=companyUserMapper.selectCompanyUserById(param.getCompanyUserId());
        if(StringUtils.isNotEmpty(companyUser.getJpushId())){
            Map<String, String> extrasMap=new HashMap<>();
            extrasMap.put("customerId",customer.getCustomerId().toString());
            extrasMap.put("type","1");
            try {
                jpushService.sendRegisterIdPush("客户消息","您回收了一个客户",extrasMap,companyUser.getJpushId());
            } catch (APIConnectionException e) {
            } catch (APIRequestException e) {
            }
        }
        return R.ok();
    }

    @Override
    public R assignUser(CrmCustomeAssignUserParam param, String operName) {
        CompanyUser companyUser=companyUserMapper.selectCompanyUserById(param.getCompanyUserId());
        CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(param.getCustomerId());
//        if(customer!=null&&customer.getStatus()==0){
//            return R.error("已锁定");
//        }
        if(customer.getIsReceive()==0){
            //写入认领记录
            CrmCustomerUser crmCustomerUser=new CrmCustomerUser();
            crmCustomerUser.setCustomerId(customer.getCustomerId());
            crmCustomerUser.setCompanyId(companyUser.getCompanyId());
            crmCustomerUser.setCompanyUserId(param.getCompanyUserId());
            crmCustomerUser.setStatus(1);
            crmCustomerUser.setCreateTime(new Date());
            crmCustomerUser.setStartTime(new Date());
            crmCustomerUser.setIsPool(0);
            crmCustomerUserMapper.insertCrmCustomerUser(crmCustomerUser);

            customer.setReceiveUserId(param.getCompanyUserId());
            customer.setIsReceive(1);
            customer.setReceiveTime(new Date());
            customer.setCustomerUserId(crmCustomerUser.getCustomerUserId());
            customer.setDeptId(param.getDeptId());
            crmCustomerMapper.updateCrmCustomer(customer);
            //写日志
            CrmCustomerLogs logs=new CrmCustomerLogs();
            logs.setCustomerId(customer.getCustomerId());
            logs.setCreateTime(new Date());
            logs.setLogsType(CustomerLogEnum.RECEIVE.getValue());
            logs.setTitle(CustomerLogEnum.RECEIVE.getDesc());
            logs.setRemark(operName+"分配客户"+customer.getCustomerName()+"给"+companyUser.getNickName());
            logs.setCompanyUserId(param.getCompanyUserId());
            logsMapper.insertCrmCustomerLogs(logs);
            return R.ok();
        }
        else{
            CrmCustomerUser crmCustomerUser=crmCustomerUserMapper.selectCrmCustomerUserById(customer.getCustomerUserId());
            if(crmCustomerUser!=null){
                crmCustomerUser.setCompanyUserId(param.getCompanyUserId());
                crmCustomerUserMapper.updateCrmCustomerUser(crmCustomerUser);
                customer.setReceiveUserId(param.getCompanyUserId());
                customer.setDeptId(param.getDeptId());
                crmCustomerMapper.updateCrmCustomer(customer);
                //写日志
                CrmCustomerLogs logs=new CrmCustomerLogs();
                logs.setCustomerId(customer.getCustomerId());
                logs.setCreateTime(new Date());
                logs.setLogsType(CustomerLogEnum.ASSIGN_USER.getValue());
                logs.setTitle(CustomerLogEnum.ASSIGN_USER.getDesc());
                logs.setCompanyUserId(param.getCompanyUserId());
                logs.setRemark(operName+"分配客户"+customer.getCustomerName()+"给"+companyUser.getNickName());
                logsMapper.insertCrmCustomerLogs(logs);
                return R.ok();
            }
            else{
                return R.error("此客户未认领,不能分配");
            }
        }

    }

    @Override
    public Integer selectCrmCustomerCountByType(Long companyId, int type) {
        return crmCustomerMapper.selectCrmCustomerCountByType(companyId,type);
    }

    @Override
    public R editTags(CrmCustomerEditTagsParam param) {
        CrmCustomer map=new CrmCustomer();
        map.setCustomerId(param.getCustomerId());
        map.setTags(param.getTags());
        return crmCustomerMapper.updateCrmCustomer(map)>0?R.ok("操作成功"):R.error("操作失败");
    }

    @Override
    public Long selectCrmCustomerCount(int type, Long companyId) {
        return crmCustomerMapper.selectCrmCustomerCount(type,companyId);
    }

    @Override
    public List<JSONObject> selectCrmCustomerCounts(Map<String, Object> toMap) {
        return crmCustomerMapper.selectCrmCustomerCounts(toMap);
    }

    @Override
    public List<CrmCustomerStatisticsVO> selectCrmCustomerStatisticsList(CrmCustomerStatisticsParam param) {
        return crmCustomerMapper.selectCrmCustomerStatisticsList(param);
    }

    @Override
    public String importCompanyLineCustomer(List<CrmCompanyLineCustomerImportParam> list, String operName, Long companyId,Long companyUserId) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder importMsg = new StringBuilder();
        for (CrmCompanyLineCustomerImportParam customer : list)
        {
            try
            {
//                String regex = "^1[3456789]\\d{9}$";
//                if(!customer.getMobile().matches(regex)){
//                    failureNum++;
//                    String msg = "<br/>" + failureNum + "、客户 " + customer.getMobile() + " 导入失败：电话号码格式不正确";
//                    failureMsg.append(msg );
//                    continue;
//                }
                CrmCustomer crmCustomer=new CrmCustomer();
                BeanUtils.copyProperties(customer,crmCustomer);
                crmCustomer.setIsDel(0);
                crmCustomer.setIsLine(1);
                crmCustomer.setCompanyId(companyId);
                crmCustomer.setStatus(1);
                crmCustomer.setIsReceive(1);
                if(StringUtils.isNotEmpty(customer.getSource())){
                    try {
                        crmCustomer.setSource(Integer.parseInt(customer.getSource()));
                    }
                    catch (Exception e){
                    }
                }
                crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
                crmCustomer.setCreateTime(new Date());
                crmCustomer.setCreateUserId(companyUserId);
                crmCustomerMapper.insertCrmCustomer(crmCustomer);
                successNum++;
                successMsg.append("<br/>" + successNum + "、客户 " + customer.getCustomerName() + " 导入成功");
                //若存在归属员工编号 就将线索客户分配给该业务员  updated by qxj 2023年05月12日16:51:37
                if(StringUtils.isNotEmpty(customer.getOwnerCompanyUserCode())){
                    CompanyUser companyUser=companyUserMapper.selectUserByUserName(customer.getOwnerCompanyUserCode());
                    if(companyUser!=null){
                       Boolean isSuccess=assignUserAfterImport(operName,crmCustomer.getCustomerId(),companyUser);
                       if(isSuccess){
                           successMsg.append(" <br/> "+customer.getOwnerCompanyUserCode()+"客户分配成功");
                       }else{
                           successMsg.append(" <br/> "+customer.getOwnerCompanyUserCode()+"客户分配失败");
                       }
                    }
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + customer.getMobile() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //throw new CustomException(failureMsg.toString());
        }
        else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        importMsg.append(failureMsg.toString());
        importMsg.append(successMsg.toString());
        return importMsg.toString();
    }

    // 导入线索客户后给指定业务员分配客户 updated by qxj 2023年05月12日16:51:37
    public Boolean assignUserAfterImport(String operName,Long customerId, CompanyUser companyUser) {

          try{
              //CompanyUser companyUser=companyUserMapper.selectCompanyUserById(companyUserId);
              CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(customerId);

              //写入认领记录
              CrmCustomerUser crmCustomerUser=new CrmCustomerUser();
              crmCustomerUser.setCustomerId(customer.getCustomerId());
              crmCustomerUser.setCompanyId(companyUser.getCompanyId());
              crmCustomerUser.setCompanyUserId(companyUser.getUserId());
              crmCustomerUser.setStatus(1);
              crmCustomerUser.setCreateTime(new Date());
              crmCustomerUser.setStartTime(new Date());
              crmCustomerUser.setIsPool(0);
              crmCustomerUserMapper.insertCrmCustomerUser(crmCustomerUser);

              customer.setReceiveUserId(companyUser.getUserId());
              customer.setIsReceive(1);
              customer.setReceiveTime(new Date());
              customer.setIsLine(0);
              customer.setCustomerUserId(crmCustomerUser.getCustomerUserId());
              customer.setDeptId(companyUser.getDeptId());
              crmCustomerMapper.updateCrmCustomer(customer);

              //写日志
              CrmCustomerLogs logs=new CrmCustomerLogs();
              logs.setCustomerId(customer.getCustomerId());
              logs.setCreateTime(new Date());
              logs.setLogsType(CustomerLogEnum.RECEIVE.getValue());
              logs.setTitle(CustomerLogEnum.RECEIVE.getDesc());
              logs.setRemark(operName+"导入认领"+customer.getCustomerName());
              logs.setCompanyUserId(companyUser.getUserId());
              logsMapper.insertCrmCustomerLogs(logs);
              return true;

          }catch (Exception e){
              return  false;
          }
    }



    @Override
    public R assignToUser(String operUserName,Long operUserId,CrmCustomeAssignParam param) {
        //获取所有用户
        CrmCustomerAssign assign=new CrmCustomerAssign();
        assign.setStatus(0);
        Integer index=0;
        for(CrmCustomerAssignUserDTO userDTO:param.getUsers()){
            CompanyUser companyUser=companyUserMapper.selectCompanyUserById(userDTO.getCompanyUserId());
            for(int i=0;i<userDTO.getCount();i++){
                CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(param.getCustomerIds().get(index));
                CrmCustomerUser crmCustomerUser=new CrmCustomerUser();
                if(param.getAssignType().equals(2)){
                    crmCustomerUser.setCustomerId(param.getCustomerIds().get(index));
                    crmCustomerUser.setCompanyId(param.getCompanyId());
                    crmCustomerUser.setCompanyUserId(userDTO.getCompanyUserId());
                    crmCustomerUser.setStatus(1);
                    crmCustomerUser.setCreateTime(new Date());
                    crmCustomerUser.setStartTime(new Date());
                    crmCustomerUser.setIsPool(0);
                    crmCustomerUserMapper.insertCrmCustomerUser(crmCustomerUser);
                    assign.setAssignType(2);
                }
                else if(param.getAssignType().equals(3)){
                    if(customer!=null&&customer.getCustomerUserId()!=null){
                        crmCustomerUser=crmCustomerUserMapper.selectCrmCustomerUserById(customer.getCustomerUserId());
                        if(crmCustomerUser!=null){
                            crmCustomerUser.setCompanyUserId(userDTO.getCompanyUserId());
                            crmCustomerUserMapper.updateCrmCustomerUser(crmCustomerUser);
                        }
                    }
                    Long sourceUserId=customer.getReceiveUserId();
                    assign.setSourceUserId(sourceUserId);
                    assign.setAssignType(3);
                }
                else if(param.getAssignType().equals(4)){
                    crmCustomerUser.setCustomerId(param.getCustomerIds().get(index));
                    crmCustomerUser.setCompanyId(param.getCompanyId());
                    crmCustomerUser.setCompanyUserId(userDTO.getCompanyUserId());
                    crmCustomerUser.setStatus(1);
                    crmCustomerUser.setCreateTime(new Date());
                    crmCustomerUser.setStartTime(new Date());
                    crmCustomerUser.setIsPool(0);
                    crmCustomerUserMapper.insertCrmCustomerUser(crmCustomerUser);
                    assign.setAssignType(4);
                }
                //结束时间按规则配置
                CrmCustomer customerMap=new CrmCustomer();
                customerMap.setCustomerId(param.getCustomerIds().get(index));
                customerMap.setReceiveUserId(userDTO.getCompanyUserId());
                customerMap.setIsReceive(1);
                customerMap.setIsLine(0);
                customerMap.setReceiveTime(new Date());
                customerMap.setCustomerUserId(crmCustomerUser.getCustomerUserId());
                customerMap.setDeptId(companyUser.getDeptId());
                crmCustomerMapper.updateCrmCustomer(customerMap);
                //写日志
                CrmCustomerLogs logs=new CrmCustomerLogs();
                logs.setCustomerId(customer.getCustomerId());
                logs.setCreateTime(new Date());
                logs.setLogsType(CustomerLogEnum.RECEIVE.getValue());
                logs.setTitle(CustomerLogEnum.RECEIVE.getDesc());
                logs.setRemark(operUserName+"分配客户"+customer.getCustomerName());
                logs.setCompanyUserId(userDTO.getCompanyUserId());
                logsMapper.insertCrmCustomerLogs(logs);

                if(StringUtils.isNotEmpty(companyUser.getJpushId())){
                    Map<String, String> extrasMap=new HashMap<>();
                    extrasMap.put("customerId",customer.getCustomerId().toString());
                    extrasMap.put("type","1");
                    try {
                        jpushService.sendRegisterIdPush("客户消息","您收到 一个客户分配",extrasMap,companyUser.getJpushId());
                    } catch (APIConnectionException e) {
                    } catch (APIRequestException e) {
                    }
                }
                index++;
            }
        }

        assign.setCompanyId(param.getCompanyId());
        assign.setCustomerIds(StringUtils.join(param.getCustomerIds(), ","));
        assign.setCreateTime(new Date());
        assign.setCompanyUserId(operUserId);
        assign.setRemark("分配客户");
        assignMapper.insertCrmCustomerAssign(assign);
        return R.ok();
    }


    @Override
    @Transactional
    public R assignCompany(CrmCustomeAssignCompanyParam crmCustomer, String operUserName, Long operUserId) {
        if(crmCustomer.getCustomerIds().size()>0){
            List<String> customerIds=new ArrayList<>();
            Company company=companyMapper.selectCompanyById(crmCustomer.getCompanyId());
            for(Long id:crmCustomer.getCustomerIds()){
                CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(id);
                customer.setStatus(1);
                customer.setUpdateTime(new Date());
                customer.setCompanyId(crmCustomer.getCompanyId());
                crmCustomerMapper.updateCrmCustomer(customer);
                //写日志
                CrmCustomerLogs logs=new CrmCustomerLogs();
                logs.setCustomerId(customer.getCustomerId());
                logs.setCreateTime(new Date());
                logs.setLogsType(CustomerLogEnum.ASSIGN_COMPANY.getValue());
                logs.setTitle(CustomerLogEnum.ASSIGN_COMPANY.getDesc());
                logs.setRemark(operUserName+"分配客户"+customer.getCustomerName()+"给"+company.getCompanyName());
                logsMapper.insertCrmCustomerLogs(logs);
                customerIds.add(customer.getCustomerId().toString());
            }

            CrmCustomerAssign assign=new CrmCustomerAssign();
            assign.setCompanyId(crmCustomer.getCompanyId());
            assign.setCustomerIds( StringUtils.join(customerIds, ","));
            assign.setCreateTime(new Date());
            assign.setSysUserId(operUserId);
            assign.setAssignType(1);
            assign.setStatus(0);
            assign.setRemark("分配客户给"+company.getCompanyName());
            assignMapper.insertCrmCustomerAssign(assign);
            return R.ok("分配成功");
        }
        else {
            return R.error();
        }
    }

    @Override
    @Transactional
    public R assignCompanys(CrmCompanyAssignParam param, String operUserName, Long operUserId) {
        Integer index=0;
        for(CrmCustomerAssignCompanyDTO companyDTO:param.getCompanys()){
            List<String> customerIds=new ArrayList<>();
            Company company=companyMapper.selectCompanyById(companyDTO.getCompanyId());
            for(int i=0;i<companyDTO.getCount();i++){
                CrmCustomer customer=crmCustomerMapper.selectCrmCustomerById(param.getCustomerIds().get(index));
                customer.setStatus(1);
                customer.setUpdateTime(new Date());

                customer.setCompanyId(companyDTO.getCompanyId());
                crmCustomerMapper.updateCrmCustomer(customer);
                //写日志
                CrmCustomerLogs logs=new CrmCustomerLogs();
                logs.setCustomerId(customer.getCustomerId());
                logs.setCreateTime(new Date());
                logs.setLogsType(CustomerLogEnum.ASSIGN_COMPANY.getValue());
                logs.setTitle(CustomerLogEnum.ASSIGN_COMPANY.getDesc());
                logs.setRemark(operUserName+"分配客户"+customer.getCustomerName()+"给"+company.getCompanyName());
                logsMapper.insertCrmCustomerLogs(logs);
                customerIds.add(customer.getCustomerId().toString());
                index++;
            }
            CrmCustomerAssign assign=new CrmCustomerAssign();
            assign.setCompanyId(companyDTO.getCompanyId());
            assign.setCustomerIds( StringUtils.join(customerIds, ","));
            assign.setCreateTime(new Date());
            assign.setSysUserId(operUserId);
            assign.setAssignType(1);
            assign.setStatus(0);
            assign.setRemark("分配客户");
            assignMapper.insertCrmCustomerAssign(assign);
        }
        return R.ok("分配成功");
    }

    @Override
    public int updateCrmCustomerSource(CrmCustomerEditSourceParam param) {
        return crmCustomerMapper.updateCrmCustomerSource(param);
    }

    @Override
    public List<CrmCustomer> selectCrmCustomerListByIds(String customerIds) {
        return crmCustomerMapper.selectCrmCustomerListByIds(customerIds);
    }

    @Override
    @DataScope(deptAlias = "c",userAlias = "c")
    public List<CrmCustomerExportVO> selectCrmCustomerExportListQuery(CrmCustomerListQueryParam param) {
        return crmCustomerMapper.selectCrmCustomerExportListQuery(param);
    }

    @Override
    @DataScope(deptAlias = "c",userAlias = "c")
    public List<CrmCustomerExportVO> selectCrmCustomerExportListByIds(Long[] customerIds) {
        return crmCustomerMapper.selectCrmCustomerExportListByIds(customerIds);
    }

    @Override
    public List<CrmCustomer> selectCrmCustomerListBySearch(CrmCustomerSearchParam param) {
        return crmCustomerMapper.selectCrmCustomerListBySearch(param);
    }

    @Override
    public int check(String customerCode) {
        return crmCustomerMapper.check(customerCode);
    }

    @Override
    public int checkCrmThirdFeiyuClue(CrmThirdFeiyuCluesSearchParam param) {
        return crmCustomerMapper.checkCrmThirdFeiyuClue(param);
    }

    @Override
    public int updateBuyCount(Long customerId) {
        return crmCustomerMapper.updateBuyCount(customerId);
    }

    @Override
    @Transactional
    @Synchronized
    public String importVisitCustomer(List<CrmCustomerVisitImportParam> list,Long companyId) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder importSuccessMsg = new StringBuilder();
        StringBuilder importErrorMsg = new StringBuilder();
        StringBuilder importMsg = new StringBuilder();
        for (CrmCustomerVisitImportParam param : list){
            try {
                CrmCustomer customer = crmCustomerMapper.selectCrmByCode(param.getCustomerCode());
                if (StringUtils.isNull(customer))
                {
                    String msg = "<br/>" + failureNum + "、客户编码 " + param.getCustomerCode() + "不存在";
                    importErrorMsg.append(msg);
                    failureNum++;
                }else {
                    if (customer.getIsReceive()==1 && customer.getCompanyId().equals(companyId)){
                        CrmCustomer customer1 = new CrmCustomer();
                        customer1.setCustomerId(customer.getCustomerId());
                        customer1.setVisitStatus(param.getVisitStatus());
                        this.updateCrmCustomer(customer1);
                        successNum++;
                        importSuccessMsg.append("<br/>" + successNum + "、客户跟随阶段 " +param.getCustomerCode() + " 导入成功");
                    }else {
                        String msg = "<br/>" + failureNum + "、客户编码 " + param.getCustomerCode() + "导入错误，请检查客户编码 ";
                        importErrorMsg.append(msg);
                        failureNum++;
                    }
                }
            } catch (Exception e) {
                String msg = "<br/>" + failureNum + "、客户编码 " + param.getCustomerCode() + " 跟随阶段导入异常：";
                importErrorMsg.append(msg+e.getMessage());
                failureNum++;
            }
        }
        importMsg.insert(0, "导入完成！成功" + successNum + " 条，失败"+failureNum+"条。");
        importMsg.append(importErrorMsg.toString());
        importMsg.append(importSuccessMsg.toString());
        return importMsg.toString();
    }

   @Override
   public List<CrmCustomerListVO> selectCrmCustomer1(){
        return crmCustomerMapper.selectCrmCustomer1();
   }
}
