package com.fs.crm.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.crm.domain.*;
import com.fs.crm.dto.CrmCustomerAssignUserDTO;
import com.fs.crm.enums.CustomerLogEnum;
import com.fs.crm.mapper.*;
import com.fs.crm.param.CrmCustomeAssignParam;
import com.fs.crm.param.CrmCustomerAssistDeLParam;
import com.fs.crm.param.CrmCustomerAssistOperationParam;
import com.fs.crm.vo.CrmCustomerAssistVo;
import com.fs.jpush.service.JpushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.crm.service.ICrmCustomerAssistService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户员工协作Service业务层处理
 *
 * @author fs
 * @date 2025-05-27
 */
@Service
public class CrmCustomerAssistServiceImpl implements ICrmCustomerAssistService
{
    @Autowired
    private CrmCustomerAssistMapper crmCustomerAssistMapper;
    @Autowired
    private CrmCustomerContactsMapper crmCustomerContactsMapper;
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private CrmCustomerMapper crmCustomerMapper;
    @Autowired
    private CrmCustomerUserMapper crmCustomerUserMapper;
    @Autowired
    private CrmCustomerLogsMapper logsMapper;
    @Autowired
    private JpushService jpushService;

    /**
     * 查询客户员工协作
     *
     * @param id 客户员工协作ID
     * @return 客户员工协作
     */
    @Override
    public CrmCustomerAssist selectCrmCustomerAssistById(Long id)
    {
        return crmCustomerAssistMapper.selectCrmCustomerAssistById(id);
    }

    /**
     * 查询客户员工协作列表
     *
     * @param crmCustomerAssist 客户员工协作
     * @return 客户员工协作
     */
    @Override
    public List<CrmCustomerAssist> selectCrmCustomerAssistList(CrmCustomerAssist crmCustomerAssist)
    {
        return crmCustomerAssistMapper.selectCrmCustomerAssistList(crmCustomerAssist);
    }

    /**
     * 新增客户员工协作
     *
     * @param crmCustomerAssist 客户员工协作
     * @return 结果
     */
    @Override
    public int insertCrmCustomerAssist(CrmCustomerAssist crmCustomerAssist)
    {
        crmCustomerAssist.setCreateTime(DateUtils.getNowDate());
        return crmCustomerAssistMapper.insertCrmCustomerAssist(crmCustomerAssist);
    }

    /**
     * 修改客户员工协作
     *
     * @param crmCustomerAssist 客户员工协作
     * @return 结果
     */
    @Override
    public int updateCrmCustomerAssist(CrmCustomerAssist crmCustomerAssist)
    {
        return crmCustomerAssistMapper.updateCrmCustomerAssist(crmCustomerAssist);
    }

    /**
     * 批量删除客户员工协作
     *
     * @param ids 需要删除的客户员工协作ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerAssistByIds(Long[] ids)
    {
        return crmCustomerAssistMapper.deleteCrmCustomerAssistByIds(ids);
    }

    /**
     * 删除客户员工协作信息
     *
     * @param id 客户员工协作ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerAssistById(Long id)
    {
        return crmCustomerAssistMapper.deleteCrmCustomerAssistById(id);
    }

    @Override
    @Transactional
    public int removeByCustomer(CrmCustomerAssistDeLParam param) {
        if (param.getCustomerIds() == null || param.getCustomerIds().isEmpty()) {
            return 0;
        }
        //计算分佣
        delComputeRate(param);
        return crmCustomerAssistMapper.removeByCustomer(param);
    }

    /**
     *  删除协作人分配佣金
     * @param param
     */
    private void delComputeRate(CrmCustomerAssistDeLParam param) {
        List<Long> customerIds = param.getCustomerIds();
        Long companyUserId = param.getCompanyUserId();
        customerIds.forEach(customerId -> {
            List<CrmCustomerAssist> assistList = crmCustomerAssistMapper.selectByCustomerId(customerId);
            if (assistList != null && !assistList.isEmpty()) {
                int i = assistList.size() - 1; //-1因为需要删除一个协作者
                if (i>0){
                    //+1因为还有原所属人
                    int rate = BigDecimal.valueOf(100).divide(BigDecimal.valueOf(i+1), 2, BigDecimal.ROUND_HALF_UP).intValue();
                    int num = 0;
                    for (int t = 0; t < i + 1; t++) {
                        num += rate;
                    }
                    int specialRate;
                    if (num > 100) {
                        //如果小于100 那就是原所属人分配多的佣金
                        specialRate = rate-(num - 100);
                    } else {
                        specialRate = 0;
                    }
                    int index = 0;
                    List<CrmCustomerAssist> newAssistList = assistList.stream().filter(temp -> !Objects.equals(temp.getCompanyUserId(), companyUserId)).collect(Collectors.toList());
                    for (CrmCustomerAssist crmCustomerAssist : newAssistList) {
                        //更新
                        if (specialRate > 0 && index == newAssistList.size()-1){
                            crmCustomerAssist.setRate(specialRate);
                        }else {
                            crmCustomerAssist.setRate(rate);
                        }
                        crmCustomerAssistMapper.updateCrmCustomerAssist(crmCustomerAssist);
                        index++;
                    }
                }
            }
        });
    }

    /**
     *  添加协作人分配佣金
     * @param param
     */
    private Integer addComputeRate(CrmCustomerAssist param) {
        Long customerId = param.getCustomerId();
        List<CrmCustomerAssist> assistList = crmCustomerAssistMapper.selectByCustomerId(customerId);
        if (assistList != null) {
            int i = assistList.size() + 2; //+2因为还有原所属人和添加协作者
            int rate = BigDecimal.valueOf(100).divide(BigDecimal.valueOf(i), 2, BigDecimal.ROUND_HALF_UP).intValue();
            int num = 0;
            for (int t = 0; t < i ; t++) {
                num += rate;
            }
            int specialRate;
            if (num > 100) {
                specialRate = rate-(num - 100);
            } else {
                //如果小于100 那就是原所属人分配多的佣金
                specialRate = 0;
            }
            for (CrmCustomerAssist crmCustomerAssist : assistList) {
                //更新
                crmCustomerAssist.setRate(rate);
                crmCustomerAssistMapper.updateCrmCustomerAssist(crmCustomerAssist);
            }
            if (specialRate > 0){
                return specialRate;
            } else {
                return rate;
            }
        }
        return 50;
    }

    @Override
    @Transactional
    public R assistToUser(String opeUserName, Long opeUserId, CrmCustomeAssignParam param) {
        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 = crmCustomerUserMapper.selectCrmCustomerUserById(customer.getCustomerUserId());
                if (Objects.equals(crmCustomerUser.getCompanyUserId(), userDTO.getCompanyUserId())) {
                    return R.error("不能选择自己来协作!");
                }
                //查询协作客户
                CrmCustomerAssist customerAssist = new CrmCustomerAssist();
                customerAssist.setCustomerId(customer.getCustomerId());
                customerAssist.setCompanyUserId(userDTO.getCompanyUserId());
                List<CrmCustomerAssist> tempList = crmCustomerAssistMapper.selectCrmCustomerAssistList(customerAssist);
                if (tempList != null && !tempList.isEmpty()) {
                    return R.error("销售:" + companyUser.getNickName() + "(" + userDTO.getCompanyUserId() + ")已拥有改该协作客户:" + customer.getCustomerName());
                }
                customerAssist.setCompanyId(param.getCompanyId());
                customerAssist.setCompanyUserName(companyUser.getNickName());
                customerAssist.setCreateTime(new Date());
                //分配佣金
                Integer rate = addComputeRate(customerAssist);
                customerAssist.setRate(rate);
                crmCustomerAssistMapper.insertCrmCustomerAssist(customerAssist);
                //写日志
                CrmCustomerLogs logs = new CrmCustomerLogs();
                logs.setCustomerId(customer.getCustomerId());
                logs.setCreateTime(new Date());
                logs.setLogsType(CustomerLogEnum.ASSIST_USER.getValue());
                logs.setTitle(CustomerLogEnum.ASSIST_USER.getDesc());
                logs.setRemark(opeUserName + "为客户" + customer.getCustomerName() + "添加协作人:" + companyUser.getNickName());
                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++;
            }
        }
        return R.ok();
    }

    @Override
    public List<CrmCustomerAssistVo> selectByCustomerIds(List<Long> customerIds) {
        if (customerIds != null && !customerIds.isEmpty()) {
            //如果超过10个建议用多线程
            ArrayList<CrmCustomerAssistVo> vos = new ArrayList<>(customerIds.size());
            customerIds.forEach(customerId->{
                CrmCustomerAssistVo vo = new CrmCustomerAssistVo();
                List<CrmCustomerAssist> assists = crmCustomerAssistMapper.selectByCustomerId(customerId);
                vo.setCustomerId(customerId);
                vo.setAssistList(assists);
                vos.add(vo);
            });
            return vos;
        }
        return null;
    }

    @Override
    public int allOperation(List<CrmCustomerAssistOperationParam> params,Long companyId,Long companyUserId) {
        AtomicInteger count = new AtomicInteger();
        params.forEach(param->{
            String operation = param.getOperation();
            switch (operation){
                case "ADD":
                    if (!Objects.equals(companyUserId, param.getCompanyUserId())){
                        param.setCompanyId(companyId);
                        crmCustomerAssistMapper.insertCrmCustomerAssist(param);
                    }
                    break;
                case "DELETE":
                    crmCustomerAssistMapper.deleteCrmCustomerAssistById(param.getId());
                    break;
                case "UPDATE":
                    param.setCompanyId(companyId);
                    crmCustomerAssistMapper.updateCrmCustomerAssist(param);
                    break;
                default:
                    break;
            }
            count.getAndIncrement();
        });
        return count.get();
    }
    @Override
    public List<CrmCustomerContacts> selectCrmCustomerContactsList(CrmCustomerContacts crmCustomerContacts)
    {
        return crmCustomerContactsMapper.selectCrmCustomerContactsList(crmCustomerContacts);
    }
}
