package com.fs.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.company.domain.CompanyVoiceRoboticCallLogCallphone;
import com.fs.company.domain.CompanyVoiceRoboticCallees;
import com.fs.company.service.ICompanyVoiceRoboticCalleesService;
import com.fs.crm.domain.CrmCustomerProperty;
import com.fs.crm.domain.CrmCustomerPropertyTemplate;
import com.fs.crm.mapper.CrmCustomerPropertyMapper;
import com.fs.crm.param.CrmCustomerAiTagParam;
import com.fs.crm.service.ICrmCustomerPropertyService;
import com.fs.crm.service.ICrmCustomerPropertyTemplateService;
import com.fs.crm.utils.CrmCustomerAiTagUtil;
import com.fs.crm.vo.CrmCustomerAiTagVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CrmCustomerPropertyServiceImpl extends ServiceImpl<CrmCustomerPropertyMapper, CrmCustomerProperty> implements ICrmCustomerPropertyService {

    @Autowired
    private ICrmCustomerPropertyTemplateService propertyTemplateService;
    @Autowired
    private ICompanyVoiceRoboticCalleesService companyVoiceRoboticCalleesService;

    @Override
    public CrmCustomerProperty selectCrmCustomerPropertyById(Long id) {
        return baseMapper.selectCrmCustomerPropertyById(id);
    }

    @Override
    public List<CrmCustomerProperty> selectCrmCustomerPropertyList(CrmCustomerProperty crmCustomerProperty) {
        return baseMapper.selectCrmCustomerPropertyList(crmCustomerProperty);
    }

    @Override
    public int insertCrmCustomerProperty(CrmCustomerProperty crmCustomerProperty) {
        crmCustomerProperty.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertCrmCustomerProperty(crmCustomerProperty);
    }

    @Override
    public int updateCrmCustomerProperty(CrmCustomerProperty crmCustomerProperty) {
        crmCustomerProperty.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateCrmCustomerProperty(crmCustomerProperty);
    }

    @Override
    public int deleteCrmCustomerPropertyByIds(Long[] ids) {
        return baseMapper.deleteCrmCustomerPropertyByIds(ids);
    }

    @Override
    public int deleteCrmCustomerPropertyById(Long id) {
        return baseMapper.deleteCrmCustomerPropertyById(id);
    }

    @Override
    public List<CrmCustomerProperty> selectCrmCustomerPropertyByCustomerId(Long customerId) {
        return baseMapper.selectCrmCustomerPropertyByCustomerId(customerId);
    }

    @Override
    public int addCustomerProperty(Long customerId, Long propertyId, String propertyName, String propertyValue, String propertyValueType, String tradeType, String createBy) {
        CrmCustomerProperty property = new CrmCustomerProperty();
        property.setCustomerId(customerId);
        property.setPropertyId(propertyId);
        property.setPropertyName(propertyName);
        property.setPropertyValue(propertyValue);
        property.setPropertyValueType(propertyValueType);
        property.setTradeType(tradeType);
        property.setCreateBy(createBy);
        property.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertCrmCustomerProperty(property);
    }

    @Override
    public int addOrUpdateCustomerProperty(Long customerId, Long propertyId, String propertyName, String propertyValue, String propertyValueType, String tradeType, String createBy) {
        CrmCustomerProperty existProperty = baseMapper.selectByCustomerIdAndPropertyId(customerId, propertyId);
        if (existProperty != null) {
            existProperty.setPropertyValue(propertyValue);
            existProperty.setPropertyName(propertyName);
            existProperty.setPropertyValueType(propertyValueType);
            existProperty.setTradeType(tradeType);
            existProperty.setUpdateBy(createBy);
            existProperty.setUpdateTime(DateUtils.getNowDate());
            return baseMapper.updateCrmCustomerProperty(existProperty);
        } else {
            return addCustomerProperty(customerId, propertyId, propertyName, propertyValue, propertyValueType, tradeType, createBy);
        }
    }

    public int addOrUpdateCustomerPropertyWithExtra(Long customerId, Long propertyId, String propertyName, String propertyValue, String propertyValueType, String tradeType, String intention, Integer likeRatio, String createBy) {
        String autoIntention = calculateIntentionByLikeRatio(likeRatio, intention);

        CrmCustomerProperty existProperty = baseMapper.selectByCustomerIdAndPropertyId(customerId, propertyId);
        if (existProperty != null) {
            existProperty.setPropertyValue(propertyValue);
            existProperty.setPropertyName(propertyName);
            existProperty.setPropertyValueType(propertyValueType);
            existProperty.setTradeType(tradeType);
            existProperty.setIntention(autoIntention);
            existProperty.setLikeRatio(likeRatio);
            existProperty.setUpdateBy(createBy);
            existProperty.setUpdateTime(DateUtils.getNowDate());
            return baseMapper.updateCrmCustomerProperty(existProperty);
        } else {
            CrmCustomerProperty property = new CrmCustomerProperty();
            property.setCustomerId(customerId);
            property.setPropertyId(propertyId);
            property.setPropertyName(propertyName);
            property.setPropertyValue(propertyValue);
            property.setPropertyValueType(propertyValueType);
            property.setTradeType(tradeType);
            property.setIntention(autoIntention);
            property.setLikeRatio(likeRatio);
            property.setCreateBy(createBy);
            property.setCreateTime(DateUtils.getNowDate());
            return baseMapper.insertCrmCustomerProperty(property);
        }
    }

    private String calculateIntentionByLikeRatio(Integer likeRatio, String intention) {
        if (likeRatio == null) {
            return intention;
        }

        if (likeRatio >= 80) {
            return "high";
        } else if (likeRatio >= 50) {
            return "medium";
        } else if (likeRatio >= 20) {
            return "low";
        } else {
            return "none";
        }
    }

    @Override
    public int batchAddCustomerProperties(Long customerId, List<CrmCustomerProperty> properties) {
        int count = 0;
        for (CrmCustomerProperty property : properties) {
            property.setCustomerId(customerId);
            property.setCreateTime(DateUtils.getNowDate());
            if (property.getPropertyId() != null) {
                CrmCustomerProperty existProperty = baseMapper.selectByCustomerIdAndPropertyId(customerId, property.getPropertyId());
                if (existProperty != null) {
                    existProperty.setPropertyValue(property.getPropertyValue());
                    existProperty.setPropertyName(property.getPropertyName());
                    existProperty.setPropertyValueType(property.getPropertyValueType());
                    existProperty.setTradeType(property.getTradeType());
                    existProperty.setUpdateBy(property.getCreateBy());
                    existProperty.setUpdateTime(DateUtils.getNowDate());
                    count += baseMapper.updateCrmCustomerProperty(existProperty);
                    continue;
                }
            }
            count += baseMapper.insertCrmCustomerProperty(property);
        }
        return count;
    }

    @Override
    public int addPropertyByTemplateId(Long customerId, Long propertyTemplateId, String propertyValue, String createBy) {
        CrmCustomerPropertyTemplate template = propertyTemplateService.selectCrmCustomerPropertyTemplateById(propertyTemplateId);
        if (template == null) {
            return 0;
        }
        return addCustomerProperty(customerId, propertyTemplateId, template.getName(), propertyValue, template.getValueType(), template.getTradeType(), createBy);
    }

    @Override
    public int addOrUpdatePropertyByTemplateId(Long customerId, Long propertyTemplateId, String propertyValue, String createBy) {
        CrmCustomerPropertyTemplate template = propertyTemplateService.selectCrmCustomerPropertyTemplateById(propertyTemplateId);
        if (template == null) {
            return 0;
        }
        return addOrUpdateCustomerProperty(customerId, propertyTemplateId, template.getName(), propertyValue, template.getValueType(), template.getTradeType(), createBy);
    }

    @Override
    public int batchAddPropertiesByTemplateIds(Long customerId, Map<Long, String> propertyMap, String createBy) {
        int count = 0;
        for (Map.Entry<Long, String> entry : propertyMap.entrySet()) {
            Long templateId = entry.getKey();
            String propertyValue = entry.getValue();
            int result = addOrUpdatePropertyByTemplateId(customerId, templateId, propertyValue, createBy);
            if (result > 0) {
                count++;
            }
        }
        return count;
    }

    @Override
    @Async
    public void addPropertyByCallLog(CompanyVoiceRoboticCallLogCallphone companyVoiceRoboticCallLogCallphone) {
        CompanyVoiceRoboticCallees companyVoiceRoboticCallees = companyVoiceRoboticCalleesService.selectCompanyVoiceRoboticCalleesById(companyVoiceRoboticCallLogCallphone.getCallerId());
        log.info("获取电话记录：{}", companyVoiceRoboticCallees);
        CrmCustomerAiTagParam param = new CrmCustomerAiTagParam();
        param.setLogId(companyVoiceRoboticCallLogCallphone.getLogId());
        param.setCustomerId(companyVoiceRoboticCallees.getUserId());
        param.setTradeType("3");
        param.setJson(companyVoiceRoboticCallLogCallphone.getContentList());
        log.info("传输数据：{}", param);
        try {
            List<CrmCustomerAiTagVo> tag = CrmCustomerAiTagUtil.getCrmCustomerAiTag(param);
            log.info("解析数据：{}", tag);
            List<Long> ids = PubFun.listToNewList(tag, e -> Long.parseLong(e.getId()));
            List<CrmCustomerProperty> propertyList = tag.stream().map(e -> {
                CrmCustomerProperty property = new CrmCustomerProperty();
                property.setCustomerId(e.getCustomerId());
                property.setPropertyId(Long.parseLong(e.getId()));
                property.setPropertyName(e.getName());
                property.setPropertyValue(e.getValue());
                property.setPropertyValueType("String");
                property.setTradeType("3");
                property.setIntention("medium");
                property.setLikeRatio(50);
                return property;
            }).collect(Collectors.toList());
            remove(new LambdaQueryWrapper<CrmCustomerProperty>()
                    .eq(CrmCustomerProperty::getCustomerId, companyVoiceRoboticCallees.getUserId())
                    .in(CrmCustomerProperty::getPropertyId, ids)
            );
            saveBatch(propertyList);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
