package com.fs.company.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.company.domain.CompanyConfig;
import com.fs.company.domain.CompanyVoiceRobotic;
import com.fs.company.mapper.CompanyVoiceRoboticMapper;
import com.fs.company.param.EntryCustomerParam;
import com.fs.company.service.ICompanyConfigService;
import com.fs.company.service.ICompanyVoiceRoboticService;
import com.fs.company.service.IGeneralCustomerEntryService;
import com.fs.company.util.CryptoUtil;
import com.fs.company.util.PhoneNumberUtil;
import com.fs.config.ai.AiHostProper;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.domain.CrmCustomerPropertyTemplate;
import com.fs.crm.dto.CrmCustomerAiAutoTagVo;
import com.fs.crm.mapper.CrmCustomerMapper;
import com.fs.crm.service.ICrmCustomerPropertyTemplateService;
import com.fs.crm.utils.CrmCustomerAiTagUtil;
import com.fs.crm.vo.CrmCustomerAiTagVo;
import com.fs.fastgptApi.param.ChatParam;
import com.fs.fastgptApi.service.ChatService;
import com.fs.hisapi.util.MapUtil;
import com.fs.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author MixLiu
 * @date 2026/3/17 15:49
 * @description
 */
@Service
@Slf4j
public class GeneralCustomerEntryServiceImpl implements IGeneralCustomerEntryService {

    @Autowired
    @Qualifier("crmCustomerExecutor")
    Executor customerExecutor;
    @Autowired
    CrmCustomerMapper crmCustomerMapper;
    @Autowired
    CompanyVoiceRoboticMapper companyVoiceRoboticMapper;
    @Autowired
    ICompanyVoiceRoboticService companyVoiceRoboticService;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    ICompanyConfigService companyConfigService;
    /**
     * 录入客户
     *
     * @param param
     * @return
     */
    //@Override
//    public R entryCustomer(String param) {
//        try {
//            String decryptParam = CryptoUtil.decrypt(param);
//            if (StringUtils.isBlank(decryptParam)) {
//                return R.error("参数错误");
//            }
//            List<EntryCustomerParam> list = JSONObject.parseArray(decryptParam, EntryCustomerParam.class);
//            CompletableFuture.runAsync(() -> handleList(list), customerExecutor);
//        } catch (Exception ex) {
//            log.error("录入客户异常", ex);
//        }
//        return R.ok().put("result", "录入成功");
//    }

    @Override
    @Async("crmCustomerExecutor")
    public String entryCustomer(EntryCustomerParam param) {
        handleData(param);
        return "success";
    }

    /**
     * 处理外部来源客户数据
     *
     * @param list
     */
    public void handleList(List<EntryCustomerParam> list) {
        list.forEach(a -> {
            handleData(a);
        });
    }

    private static final String TRADE_TYPE = "trade_type";
    @Value("${crm.customer.ai.key:mygpt-tbQfq4ejR162mGJBCTTDUH9ecP1XCVuUfaOGTipnLjb1hP8x5prg}")
    private String appKey;
    private List<CrmCustomerAiTagVo> getAiTags(String chatRecord) throws JsonProcessingException {
        Map<String, Object> requestParam = new HashMap<>();
        List<CrmCustomerPropertyTemplate> crmCustomerPropertyTemplates = SpringUtils.getBean(ICrmCustomerPropertyTemplateService.class).getBaseMapper().selectList(new LambdaQueryWrapper<CrmCustomerPropertyTemplate>());
        List<SysDictData> sysDictData = sysDictDataMapper.selectDictDataByType(TRADE_TYPE);
        ArrayList<Map<String, String>> tags = new ArrayList<>();//标签模板及提示词
        crmCustomerPropertyTemplates.forEach(o -> {
            Map<String, String> tag = MapUtil.convertToMap(new CrmCustomerAiAutoTagVo(String.valueOf(o.getId()), o.getName(), o.getAiHint()));
            tags.add(tag);
        });
        StringBuilder history = new StringBuilder();
        List<Map<String, Object>> communication;
        ObjectMapper mapper = new ObjectMapper();
        try {
            communication =  mapper.readValue(chatRecord,
                    new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
            throw new RuntimeException("数据格式错误", e);
        }
        //对话内容删掉第一条（提示词）
        if (!communication.isEmpty())communication.remove(0);
        history.append("{");
        for (Map<String, Object> o :
                communication) {
            String role = (String) o.get("role");
            String content = (String) o.get("content");
            String roleTag = "user".equals(role) ? "user" : "ai";
            history.append(String.format("\"%s\":\"%s\",", roleTag, content));
        }
        history.deleteCharAt(history.length() - 1).append("}");
        HashMap<String, String> userInfo = new HashMap<String, String>();
        HashMap<String, String> aiInfo = new HashMap<>();
        aiInfo.put("name", "");
        aiInfo.put("sex", "");
        aiInfo.put("age", "");
        aiInfo.put("city", "");
        aiInfo.put("habits", "");
        aiInfo.put("describe", "");
        userInfo.put("name", "");
        userInfo.put("sex", "");
        userInfo.put("age", "");
        userInfo.put("city", "");
        userInfo.put("habits", "");
        userInfo.put("describe", "");
        requestParam.put("aiInfo", aiInfo);
        requestParam.put("likeRatio", "");
        requestParam.put("userInfo", userInfo);
        requestParam.put("history", history);
        requestParam.put("tags", tags);
        requestParam.put("tradeName", sysDictData.stream().map(SysDictData::getDictLabel).collect(Collectors.toList()));
        requestParam.put("tradeType", sysDictData.stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        requestParam.put("tagInfos", Collections.emptyList());
        requestParam.put("isRepository", "");
        requestParam.put("userContent", "");
        requestParam.put("aiContent", "");
        requestParam.put("likeRatio", "");

        String requestJson = mapper.writeValueAsString(requestParam);
        ChatParam param = new ChatParam();
        param.setChatId(UuidUtil.getTimeBasedUuid().toString());
        param.setStream(false);
        param.setDetail(true);
        ChatParam.Message message = new ChatParam.Message();
        List<ChatParam.Message> messageList = new ArrayList<ChatParam.Message>();
        message.setContent(requestJson);
        message.setRole("user");
        messageList.add(message);
        param.setMessages(messageList);
        ChatService chatService = SpringUtils.getBean(ChatService.class);
        AiHostProper aiHost = SpringUtils.getBean(AiHostProper.class);
        R aiResponse = chatService.initiatingTakeChat(param, aiHost.getAiApi(), appKey);
        if (aiResponse == null || !Integer.valueOf(200).equals(aiResponse.get("code"))) {
            throw new RuntimeException("AI响应异常: " +
                    (aiResponse != null ? aiResponse.get("msg") : "响应为空"));
        }

        List<Map<String, String>> tagInfos = CrmCustomerAiTagUtil.extractTagInfos(JSONUtil.toJsonStr(aiResponse));
        if (CollectionUtils.isEmpty(tagInfos)) {
            return Collections.emptyList();
        }

        List<CrmCustomerAiTagVo> collect = tagInfos.stream()
                .map(tag -> {
                    return new CrmCustomerAiTagVo()
                            .setValue(tag.get("value")).setName(tag.get("name"));
                })
                .collect(Collectors.toList());
        return collect;
    }
    /**
     * 处理单条数据
     * @param data
     */
    public void handleData(EntryCustomerParam data) {
        //客户数据校验
        Boolean b = validateCustomerData(data);
        if (!b) {
            log.error("客户数据校验失败,{}", data);
            return;
        }
        //客户数据解析，是否包含对话图 对话图解析标签&意向度标识 todo 庄旭组在研发此功能
        if (StringUtils.isNotBlank(data.getDialogue())) {
            try {
                List<CrmCustomerAiTagVo> aiTags = getAiTags(data.getDialogue());
                if(null != aiTags && !aiTags.isEmpty()){
                    String tags = data.getTags()==null?"":data.getTags();
                    StringBuilder sb = new StringBuilder(tags);
                    aiTags.forEach(a->{
                        sb.append(a.getName()).append(",");
                    });
                    if(sb.length() >0 &&  ',' == sb.charAt(sb.length()-1)){
                        data.setTags(sb.substring(0,sb.length()-1));
                    }
                    data.setTags(sb.toString());
                }
                //todo 意向度分析
            } catch (JsonProcessingException e) {
                log.error("导入用户标签数据解析异常", e);
            }
//            JSONObject jsonObject = analysisDialogue(data.getDialogue());
//            if (jsonObject != null) {
//                data.setIntention(jsonObject.getString("intention"));
//                data.setTags(jsonObject.getString("tags"));
//            }
        }
        //客户数据插入
        insertCrmCustomer(data);
        if(null != data.getCompanyId() && null != data.getSceneType()){
            //公司场景任务读取
            CompanyVoiceRobotic companySceneTasks = getCompanySceneTask(data);
            if(null != companySceneTasks){
                //场景任务存在 加入场景任务队列
                companyVoiceRoboticService.addNewExec4Task(companySceneTasks.getId(),data.getCustomerId(),data.getTraceId());
            }
        }
    }

    /**
     * 校验客户数据
     * @param param
     * @return
     */
    public Boolean validateCustomerData(EntryCustomerParam param) {
        boolean valid = PhoneNumberUtil.isValid(param.getMobile());
        if(!valid){
            log.error("手机号格式错误,{}", param.getMobile());
            return false;
        }
        //根据配置项是否允许重复手机号客户录入
        CompanyConfig config=companyConfigService.selectCompanyConfigByKey(param.getCompanyId(),"cId.config");
        if (null != config) {
            String configValue = config.getConfigValue();
            JSONObject configObj = JSONObject.parseObject(configValue);
            if(configObj.containsKey("allowRepeatCustomer") && null != configObj.getBoolean("allowRepeatCustomer") && !configObj.getBoolean("allowRepeatCustomer")){
                Long  customerId = crmCustomerMapper.selectCrmCustomerByCrmMobileAndCompanyId(param.getCompanyId(),param.getMobile());
                if( null != customerId && true){
                    log.error("手机号重复数据,{}", param.getMobile());
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 解析对话图 得到意向度以及标签
     *
     * @param dialogue
     * @return
     */
    public JSONObject analysisDialogue(String dialogue) {
        return null;
    }

    /**
     * 插入crmcustomer
     * @param data
     * @return
     */
    public void insertCrmCustomer(EntryCustomerParam data){
        CrmCustomer insertObj = new CrmCustomer();
        BeanUtils.copyProperties(data,insertObj);
        if(StringUtils.isBlank(insertObj.getCustomerName())){
            insertObj.setCustomerName("客户"+insertObj.getMobile().substring(7,11));
        }
        insertObj.setIsLine(1);
        if(null == insertObj.getCreateTime()){
            insertObj.setCreateTime(new Date());
        }
        crmCustomerMapper.insertCrmCustomer(insertObj);
        data.setCustomerId(insertObj.getCustomerId());
    }

    /**
     * 获取公司场景任务
     * @param data
     * @return
     */
    public CompanyVoiceRobotic getCompanySceneTask(EntryCustomerParam data){
        List<CompanyVoiceRobotic> companyVoiceRobotics = companyVoiceRoboticMapper.selectSceneTaskByCompanyIdAndType(data.getCompanyId(), data.getSceneType());
        if(null != companyVoiceRobotics && !companyVoiceRobotics.isEmpty()){
            List<CompanyVoiceRobotic> resList = companyVoiceRobotics.stream()
                    .filter(item -> verificationTime(item.getAvailableStartTime(), item.getAvailableEndTime()))
                    .collect(Collectors.toList());
            if(null !=  resList && !resList.isEmpty()){
                return resList.get(0);
            }
        }
        return null;
    }

    /**
     * 校验当前时间是否在指定时间区间内
     * 支持跨天凌晨区间（如22:00-06:00）
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return true-在区间内，false-不在区间内
     */
    public Boolean verificationTime(LocalTime start, LocalTime end) {
        if (start == null || end == null) {
            return false;
        }
        LocalTime now = LocalTime.now();
        if (!start.isAfter(end)) {
            return !now.isBefore(start) && !now.isAfter(end);
        }
        return !now.isBefore(start) || !now.isAfter(end);
    }

}
