package com.fs.sop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.annotation.DataSource;
import com.fs.common.enums.DataSourceType;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.PubFun;
import com.fs.fastGpt.domain.FastGptChatReplaceWords;
import com.fs.fastGpt.mapper.FastGptChatReplaceWordsMapper;
import com.fs.qw.vo.SortDayVo;
import com.fs.sop.domain.QwSopTemp;
import com.fs.sop.domain.QwSopTempContent;
import com.fs.sop.domain.QwSopTempDay;
import com.fs.sop.domain.QwSopTempRules;
import com.fs.sop.mapper.QwSopTempMapper;
import com.fs.sop.params.QwSopShareTempParam;
import com.fs.sop.service.*;
import com.fs.sop.vo.VoiceVo;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * sop模板Service业务层处理
 *
 * @author fs
 * @date 2024-09-26
 */
@Service
@AllArgsConstructor
public class QwSopTempServiceImpl implements IQwSopTempService
{
    private final QwSopTempMapper qwSopTempMapper;
    private final FastGptChatReplaceWordsMapper fastGptChatReplaceWordsMapper;
    private final IQwSopTempRulesService qwSopTempRulesService;
    private final IQwSopTempDayService qwSopTempDayService;
    private final IQwSopTempContentService qwSopTempContentService;
    private final IQwSopTempVoiceService qwSopTempVoiceService;
    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 查询sop模板
     *
     * @param id sop模板主键
     * @return sop模板
     */
    @Override
    public QwSopTemp selectQwSopTempById(String id){
//        QwSopTemp qwSopTemp = qwSopTempMapper.selectQwSopTempById(id);
        QwSopTemp qwSopTemp = qwSopTempMapper.selectQwSopTempById(id);
        List<QwSopTempDay> qwSopTempDays = qwSopTempDayService.listByTempId(id);
        qwSopTemp.setList(qwSopTempDays);
//        List<QwSopTempRules> rulesList = qwSopTempRulesService.listByTempId(id);
//        if(!rulesList.isEmpty()){
//            Map<Integer, List<QwSopTempRules>> ruleDayMap = PubFun.listToMapByGroupList(rulesList, QwSopTempRules::getDayNum);
//            qwSopTemp.setRules(ruleDayMap.values().stream().map(qwSopTempRules -> {
//                Map<String, Object> map = new HashMap<>();
//                QwSopTempRules rules = qwSopTempRules.get(0);
//                map.put("name", rules.getName());
//                map.put("id", rules.getTempId());
//                map.put("dayNum", rules.getDayNum());
////                map.put("content", qwSopTempRules);
//                return map;
//            }).collect(Collectors.toList()));
//        }else{
//            qwSopTemp.setRules(new ArrayList<>());
//        }
        return qwSopTemp;
    }

    /**
     * 查询sop模板列表
     *
     * @param qwSopTemp sop模板
     * @return sop模板
     */
    @Override
    public List<QwSopTemp> selectQwSopTempList(QwSopTemp qwSopTemp)
    {
        return qwSopTempMapper.selectQwSopTempList(qwSopTemp);
    }

    /**
     * 新增sop模板
     *
     * @param qwSopTemp sop模板
     * @return 结果
     */
    @Override
    public int insertQwSopTemp(QwSopTemp qwSopTemp){
        qwSopTemp.setId(UUID.randomUUID().toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        qwSopTemp.setCreateTime(sdf.format(new Date()));
        return qwSopTempMapper.insert(qwSopTemp);
    }

    // 提取通用替换逻辑的方法
    private void replaceContent(String contentType, String content, Consumer<String> setter, List<FastGptChatReplaceWords> words) {
        if (contentType != null && content != null && !content.isEmpty()) {
            for (FastGptChatReplaceWords word : words) {
                if (content.contains(word.getContent())) {
                    // 如果包含目标字段，则替换
                    setter.accept(content.replace(word.getContent(), word.getChangeCount()));
                }
            }
        }
    }

    /**
     * 修改sop模板
     *
     * @param qwSopTemp sop模板
     * @return 结果
     */
    @Override
    public int updateQwSopTemp(QwSopTemp qwSopTemp){
        return qwSopTempMapper.updateQwSopTemp(qwSopTemp);
    }

    /**
     * 批量删除sop模板
     *
     * @param ids 需要删除的sop模板主键
     * @return 结果
     */
    @Override
    public int deleteQwSopTempByIds(String[] ids)
    {
        return qwSopTempMapper.deleteQwSopTempByIds(ids);
    }

    @Override
    public int shareQwSopTemp(QwSopShareTempParam param) {
        QwSopTemp qwSopTemp = qwSopTempMapper.selectQwSopTempById(param.getTempleId());
        Arrays.stream(param.getCompanyIds()).forEach(companyId -> {
            qwSopTemp.setCompanyId(companyId);
            copyTemplate(qwSopTemp);
        });
        return 1;
    }

    @Override
    public int updateQwSopTempByIds(String[] ids) {
        return qwSopTempMapper.updateQwSopTempByIds(ids);
    }

    /**
     * 删除sop模板信息
     *
     * @param id sop模板主键
     * @return 结果
     */
    @Override
    public int deleteQwSopTempById(String id)
    {
        return qwSopTempMapper.deleteQwSopTempById(id);
    }

    @Override
    public int addNew(QwSopTemp qwSopTemp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        qwSopTemp.setCreateTime(sdf.format(new Date()));
        qwSopTemp.setId(UUID.randomUUID().toString());
        return qwSopTempMapper.insertQwSopTemp(qwSopTemp);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public int update(QwSopTemp qwSopTemp) {
        QwSopTemp temp = qwSopTempMapper.selectById(qwSopTemp.getId());
        int i = qwSopTempMapper.updateById(qwSopTemp);
        if(!Objects.equals(temp.getGap(), qwSopTemp.getGap())){
            // 重新排序
            reorder(qwSopTemp.getId());
        }
        return i;
    }

    @Override
    public Map<String, Object> addOrUpdateSetting(QwSopTempDay day) {
        List<QwSopTempRules> list = day.getList();
        List<QwSopTempContent> collect = list.stream().flatMap(e -> e.getSettingList().stream()).collect(Collectors.toList());
        List<QwSopTempContent> voiceList = collect.stream().filter(e -> e.getContentType() == 7).collect(Collectors.toList());
        if(!voiceList.isEmpty()){
//            day.setVoice(1);
        }
        qwSopTempDayService.saveOrUpdate(day);
        qwSopTempRulesService.removeByDayId(day.getId());
        qwSopTempContentService.removeByDayId(day.getId());

        list.forEach(item-> item.setDayId(day.getId()));
        processAndReplaceContent(list);
        QwSopTempRules rules = list.get(0);
        String tempId = rules.getTempId();
        // 批量插入
        qwSopTempRulesService.insertBatch(list);
        // 处理添加列表设置ID
        list.forEach(e -> e.getSettingList().forEach(item -> {
            item.setRulesId(e.getId());
            item.setDayId(e.getDayId());
            item.setTempId(tempId);
        }));
        // 批量插入内容

        qwSopTempContentService.insertBatch(collect);
        reorder(day.getTempId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", day.getId());
        if(!voiceList.isEmpty()){
            rocketMQTemplate.syncSend("voice-generation", JSON.toJSONString(VoiceVo.builder().type(0).id(day.getId().toString()).build()));
        }
        return map;
    }

    private void processAndReplaceContent(List<QwSopTempRules> tempSettings){
        List<FastGptChatReplaceWords> words = fastGptChatReplaceWordsMapper.selectAllFastGptChatReplaceWords();
        //循环天
        tempSettings.forEach(settingList->{
            //循环单日
            settingList.getSettingList().forEach(item->{
                JSONObject obj = JSON.parseObject(item.getContent());
                List<String> list = Arrays.asList("linkTitle", "linkDescribe", "desc", "nickname", "value");
                list.stream().filter(obj::containsKey).forEach(key -> {
                    replaceContent(item.getContentType().toString(), obj.getString(key), val -> obj.put(key, val), words);
                });
                item.setContent(obj.toJSONString());
            });
        });
    }

    @Override
    public void delRules(Long id) {
        if(id == null) return;
        QwSopTempDay day = qwSopTempDayService.info(id);
        if(day == null) return;
        qwSopTempDayService.removeById(day.getId());
        qwSopTempContentService.removeByDayId(day.getId());
        reorder(day.getTempId());
    }
    @Override
    public QwSopTempDay selectRulesInfo(Long id) {
        QwSopTempDay day = qwSopTempDayService.info(id);
        List<QwSopTempRules> rulesList = qwSopTempRulesService.listByDayId(id);
        if(!rulesList.isEmpty()){
            List<QwSopTempContent> contentList = qwSopTempContentService.listByRulesIds(PubFun.listToNewList(rulesList, QwSopTempRules::getId));
            Map<Long, List<QwSopTempContent>> contentMap = PubFun.listToMapByGroupList(contentList, QwSopTempContent::getRulesId);
            rulesList.forEach(e -> {
                List<QwSopTempContent> contents = contentMap.get(e.getId());
                e.setSetting(contents.stream().map(c -> JSON.parseObject(c.getContent())).collect(Collectors.toList()));
            });
        }
        day.setList(rulesList);
        return day;
    }

    @Override
    public List<QwSopTemp> selectQwSopTempListNew(QwSopTemp qwSopTemp) {
        return qwSopTempMapper.selectQwSopTempListNew(qwSopTemp);
    }

    @Override
    public void copyTemplate(QwSopTemp qwSopTemp) {
        String oldId = qwSopTemp.getId();
        String newId = UUID.randomUUID().toString();
        qwSopTemp.setId(newId);
        qwSopTempMapper.insertQwSopTemp(qwSopTemp);
        List<QwSopTempDay> dayList = qwSopTempRulesService.listByTempIdAll(oldId);
        if(dayList.isEmpty()) return;
//        List<QwSopTempRules> rulesList = qwSopTempRulesService.listByTempId(oldId);
        dayList.forEach(day -> {
            day.setTempId(newId);
            if(day.getList() != null && !day.getList().isEmpty()){
                day.getList().forEach(e -> {
                    e.setTempId(newId);
                    if(e.getSettingList() != null && !e.getSettingList().isEmpty()){
                        e.getSettingList().forEach(item -> {
                            item.setTempId(newId);
                        });
                    }
                });
            }
        });
        qwSopTempDayService.insertBatch(dayList);
        dayList.forEach(e -> e.getList().forEach(item -> item.setDayId(e.getId())));
        List<QwSopTempRules> collect = dayList.stream().flatMap(e -> e.getList().stream()).collect(Collectors.toList());
        qwSopTempRulesService.insertBatch(collect);
        collect.forEach(e -> e.getSettingList().forEach(item -> {
            item.setRulesId(e.getId());
            item.setDayId(e.getDayId());
        }));
        qwSopTempContentService.insertBatch(collect.stream().flatMap(e ->e.getSettingList().stream()).collect(Collectors.toList()));
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTemp> listTemp() {
        return qwSopTempMapper.selectList(new QueryWrapper<>());
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void sortDay(List<SortDayVo> list) {
        Collection<QwSopTempDay> days = qwSopTempDayService.listByIds(PubFun.listToNewList(list, SortDayVo::getId));
        Map<Long, Integer> dayMap = list.stream().collect(Collectors.toMap(SortDayVo::getId, SortDayVo::getDayNum));
        if(days.stream().anyMatch(e -> !dayMap.containsKey(e.getId()))){
            throw new BaseException("数据错误！");
        }
        days.forEach(day -> day.setDayNum(dayMap.get(day.getId())));
        qwSopTempDayService.updateBatchById(days);
    }

    @Override
    public List<QwSopTempDay> dayList(String id) {
        return qwSopTempDayService.listByTempId(id);
    }


    @DataSource(DataSourceType.SOP)
    private void reorder(String tempId){
        QwSopTemp qwSopTemp = qwSopTempMapper.selectQwSopTempById(tempId);
        List<QwSopTempDay> days = qwSopTempDayService.listByTempId(tempId);
        if(days.isEmpty()) return;
        for (int i = 0; i < days.size(); i++) {
            QwSopTempDay entity = days.get(i);
            entity.setSorts(i);
            entity.setDayNum((entity.getSorts() * qwSopTemp.getGap()) + 1);
        }
        qwSopTempDayService.addOrUpdateBatch(days);
    }
}
