package com.fs.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fs.common.utils.DateUtils;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.course.domain.FsCourseFinishTemp;
import com.fs.course.mapper.FsCourseFinishTempMapper;
import com.fs.course.service.IFsCourseFinishTempService;
import com.fs.course.vo.FsCourseFinishTempListVO;
import com.fs.course.vo.FsCourseFinishTempVO;
import com.fs.fastGpt.domain.FastGptChatReplaceWords;
import com.fs.fastGpt.mapper.FastGptChatReplaceWordsMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.vo.QwSopCourseFinishTempSetting;
import com.fs.qw.vo.QwUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * 完课模板Service业务层处理
 *
 * @author fs
 * @date 2024-12-19
 */
@Service
public class FsCourseFinishTempServiceImpl implements IFsCourseFinishTempService
{
    @Autowired
    private FsCourseFinishTempMapper fsCourseFinishTempMapper;

    @Autowired
    private FastGptChatReplaceWordsMapper fastGptChatReplaceWordsMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    /**
     * 查询完课模板
     *
     * @param id 完课模板主键
     * @return 完课模板
     */
    @Override
    public FsCourseFinishTemp selectFsCourseFinishTempById(Long id)
    {
        return fsCourseFinishTempMapper.selectFsCourseFinishTempById(id);
    }

    @Override
    public FsCourseFinishTempVO selectFsCourseFinishTempByIdVO(Long id) {
        FsCourseFinishTempVO fsCourseFinishTemp = fsCourseFinishTempMapper.selectFsCourseFinishTempByIdVO(id);

        String companyUserIds = fsCourseFinishTemp.getCompanyUserIds();
        List<String> qwUserIdsList = Arrays.asList(companyUserIds.split(","));

        List<QwUserVO> qwUserByIds = qwUserMapper.getQwUserByIdsNoCropId(qwUserIdsList);
        fsCourseFinishTemp.setUserSelectList(qwUserByIds);

        return fsCourseFinishTemp;
    }

    /**
     * 查询完课模板列表
     *
     * @param fsCourseFinishTemp 完课模板
     * @return 完课模板
     */
    @Override
    public List<FsCourseFinishTemp> selectFsCourseFinishTempList(FsCourseFinishTemp fsCourseFinishTemp)
    {
        return fsCourseFinishTempMapper.selectFsCourseFinishTempList(fsCourseFinishTemp);
    }

    /**
     * 新增完课模板
     *
     * @param fsCourseFinishTemp 完课模板
     * @return 结果
     */
    @Override
    public int insertFsCourseFinishTemp(FsCourseFinishTemp fsCourseFinishTemp)
    {
        fsCourseFinishTemp.setCreateTime(DateUtils.getNowDate());

        //清理一下违禁词
        fsCourseFinishTemp.setSetting(JSON.toJSONString(processAndReplaceCrouseContent(fsCourseFinishTemp.getSetting())));
        fsCourseFinishTemp.setChatSetting(JSON.toJSONString(processAndReplaceCrouseContent(fsCourseFinishTemp.getChatSetting())));

        return fsCourseFinishTempMapper.insertFsCourseFinishTemp(fsCourseFinishTemp);
    }


    //处理一下违禁词(完课版)
    private List<QwSopCourseFinishTempSetting.Setting>  processAndReplaceCrouseContent(String settingParam){

        List<FastGptChatReplaceWords> words = fastGptChatReplaceWordsMapper.selectAllFastGptChatReplaceWords();
        List<QwSopCourseFinishTempSetting.Setting> list = JSONArray.parseArray(settingParam,QwSopCourseFinishTempSetting.Setting.class);

        //循环内容
        list.forEach(item -> {
            if ("1".equals(item.getContentType())){
                replaceContent(item.getContentType(), item.getValue(), item::setValue, words); // 替换 value
            }

            if ("3".equals(item.getContentType())){
                replaceContent(item.getContentType(), item.getLinkTitle(), item::setLinkTitle, words); // 替换 linkTitle
                replaceContent(item.getContentType(), item.getLinkDescribe(), item::setLinkDescribe, words); // 替换 linkTitle
            }

        });
        return list;
    }
    // 提取通用替换逻辑的方法
    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()));
                }
            }
        }
    }

    /**
     * 修改完课模板
     *
     * @param fsCourseFinishTemp 完课模板
     * @return 结果
     */
    @Override
    public int updateFsCourseFinishTemp(FsCourseFinishTemp fsCourseFinishTemp)
    {
        fsCourseFinishTemp.setUpdateTime(DateUtils.getNowDate());
        //清理一下违禁词
        fsCourseFinishTemp.setSetting(JSON.toJSONString(processAndReplaceCrouseContent(fsCourseFinishTemp.getSetting())));

        return fsCourseFinishTempMapper.updateFsCourseFinishTemp(fsCourseFinishTemp);
    }

    /**
     * 批量删除完课模板
     *
     * @param ids 需要删除的完课模板主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseFinishTempByIds(Long[] ids)
    {
        return fsCourseFinishTempMapper.deleteFsCourseFinishTempByIds(ids);
    }

    /**
     * 删除完课模板信息
     *
     * @param id 完课模板主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseFinishTempById(Long id)
    {
        return fsCourseFinishTempMapper.deleteFsCourseFinishTempById(id);
    }

    @Override
    public void deleteByParentIds(Long[] ids) {
        fsCourseFinishTempMapper.deleteByParentIds(ids);
    }

//    @Override
//    public void updateFsCourseFinishTempByCompanyUserId() {
//        List<FsCourseFinishTemp> fsCourseFinishTemps = fsCourseFinishTempMapper.selectFsCourseFinishTempByCompanyList();
//        fsCourseFinishTemps.forEach(item -> {
//            List<String> qwUserList = new ArrayList<>();
//            if (!StringUtil.strIsNullOrEmpty(item.getCompanyUserIds())) {
//                // 分割 companyUserIds 并清理空格
//                Arrays.stream(item.getCompanyUserIds().split("\\s*,\\s*"))
//                        .forEach(userId -> {
//                            if (!StringUtil.strIsNullOrEmpty(userId)){
//                                CompanyUser companyUser = companyUserMapper.selectCompanyUserById(Long.valueOf(userId.trim()));
//                                if (companyUser != null && !StringUtil.strIsNullOrEmpty(companyUser.getQwUserId())) {
//                                    // 分割 qwUserId 并清理空格
//                                    List<String> cleanedQwUserIds = Arrays.stream(companyUser.getQwUserId().split("\\s*,\\s*"))
//                                            .map(String::trim)
//                                            .filter(s -> !s.isEmpty())  // 过滤空字符串
//                                            .collect(Collectors.toList());
//                                    qwUserList.addAll(cleanedQwUserIds);
//                                }
//                            }
//                        });
//                String join = String.join(",", qwUserList);
//                item.setCompanyUserIds(join);
//                fsCourseFinishTempMapper.updateFsCourseFinishTemp(item);
//
//            }
//        });
//    }


    @Override
    public List<FsCourseFinishTempListVO> selectFsCourseFinishTempListVO(FsCourseFinishTemp fsCourseFinishTemp) {
        return fsCourseFinishTempMapper.selectFsCourseFinishTempListVO(fsCourseFinishTemp);
    }
}
