package com.fs.sop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.annotation.DataSource;
import com.fs.common.enums.DataSourceType;
import com.fs.common.utils.PubFun;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.qw.vo.QwSopTempSetting;
import com.fs.sop.domain.QwSopTempContent;
import com.fs.sop.domain.QwSopTempDay;
import com.fs.sop.domain.QwSopTempRules;
import com.fs.sop.mapper.QwSopTempContentMapper;
import com.fs.sop.mapper.QwSopTempDayMapper;
import com.fs.sop.mapper.QwSopTempRulesMapper;
import com.fs.sop.service.IQwSopTempContentService;
import com.fs.sop.service.IQwSopTempDayService;
import com.fs.sop.service.IQwSopTempRulesService;
import com.fs.sop.vo.QwSopTempContentVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * sop任务模板规则Service业务层处理
 *
 * @author fs
 * @date 2025-02-06
 */
@Service
@AllArgsConstructor
public class QwSopTempRulesServiceImpl extends ServiceImpl<QwSopTempRulesMapper, QwSopTempRules> implements IQwSopTempRulesService {

    private static final Logger log = LoggerFactory.getLogger(QwSopTempRulesServiceImpl.class);
    private final IQwSopTempContentService qwSopTempContentService;
    private final IQwSopTempDayService qwSopTempDayService;

    @Autowired
    QwSopTempRulesMapper qwSopTempRulesMapper;
    @Autowired
    QwSopTempDayMapper dayMapper;

    @Autowired
    QwSopTempContentMapper contentMapper;

    /**
     * 查询sop任务模板规则
     *
     * @param id sop任务模板规则主键
     * @return sop任务模板规则
     */
    @Override
    public QwSopTempRules selectQwSopTempRulesById(String id) {
        return baseMapper.selectQwSopTempRulesById(id);
    }

    /**
     * 查询sop任务模板规则列表
     *
     * @param qwSopTempRules sop任务模板规则
     * @return sop任务模板规则
     */
    @Override
    public List<QwSopTempRules> selectQwSopTempRulesList(QwSopTempRules qwSopTempRules) {
        return baseMapper.selectQwSopTempRulesList(qwSopTempRules);
    }

    /**
     * 新增sop任务模板规则
     *
     * @param qwSopTempRules sop任务模板规则
     * @return 结果
     */
    @Override
    public int insertQwSopTempRules(QwSopTempRules qwSopTempRules) {
        return baseMapper.insertQwSopTempRules(qwSopTempRules);
    }

    /**
     * 修改sop任务模板规则
     *
     * @param qwSopTempRules sop任务模板规则
     * @return 结果
     */
    @Override
    public int updateQwSopTempRules(QwSopTempRules qwSopTempRules) {
        return baseMapper.updateQwSopTempRules(qwSopTempRules);
    }

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

    /**
     * 删除sop任务模板规则信息
     *
     * @param id sop任务模板规则主键
     * @return 结果
     */
    @Override
    public int deleteQwSopTempRulesById(String id) {
        return baseMapper.deleteQwSopTempRulesById(id);
    }

    @Override
    public void deleteByTempId(String id) {
        baseMapper.deleteByTempId(id);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void insertBatch(List<QwSopTempRules> rulesList) {

        super.saveBatch(rulesList);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTempRules> listByTempId(String id) {
        List<QwSopTempDay> dayList = qwSopTempDayService.list(new QueryWrapper<QwSopTempDay>().eq("temp_id", id).orderByAsc("day_num"));
        if (dayList.isEmpty()) return Collections.emptyList();
        Map<Long, Integer> collect = dayList.stream().collect(Collectors.toMap(QwSopTempDay::getId, QwSopTempDay::getDayNum));
        List<QwSopTempRules> rulesList = list(new QueryWrapper<QwSopTempRules>().in("day_id", PubFun.listToNewList(dayList, QwSopTempDay::getId)));
        rulesList.forEach(r -> {
            r.setDayNum(collect.get(r.getDayId()));
        });
        List<QwSopTempContent> ts = qwSopTempContentService.list(new QueryWrapper<QwSopTempContent>().in("rules_id", PubFun.listToNewList(rulesList, QwSopTempRules::getId)));
        Map<Long, List<QwSopTempContent>> map = PubFun.listToMapByGroupList(ts, QwSopTempContent::getRulesId);
        rulesList.stream().filter(e -> map.containsKey(e.getId())).forEach(e -> e.setSettingList(map.get(e.getId())));
        return rulesList;
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTempDay> listByTempIdAll(String id) {
        List<QwSopTempRules> rulesList = listByTempId(id);
        List<QwSopTempDay> list = qwSopTempDayService.listByTempId(id);
        Map<Long, List<QwSopTempRules>> ruleMap = PubFun.listToMapByGroupList(rulesList, QwSopTempRules::getDayId);
        list.forEach(e -> {
            e.setList(ruleMap.get(e.getId()));
        });
        return list;
    }

    @Override
    public List<QwSopTempRules> listByTempIdAndNameAndDayNum(String id, Integer dayNum) {
        return baseMapper.listByTempIdAndNameAndDayNum(id, dayNum);
    }

    @Override
    public void deleteByIdList(List<String> ids) {
        baseMapper.deleteByIdList(ids);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void saveList(List<QwSopTempRules> list) {
        super.saveBatch(list);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTempRules> listByDayId(Long id) {
        return list(new QueryWrapper<QwSopTempRules>().eq("day_id", id));
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void removeByIds(List<Long> id) {
        super.removeByIds(id);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void removeByDayId(Long id) {
        remove(new QueryWrapper<QwSopTempRules>().eq("day_id", id));
    }

    @Override
    public void updateRulesDayNumIsNull() {
        List<QwSopTempRules> rules = qwSopTempRulesMapper.rulesNull();
        log.info("时间为空的有：{}", rules.size());
        for (QwSopTempRules rule : rules) {
            QwSopTempDay day = dayMapper.info(rule.getDayId());
            if (day != null) {
                QwSopTempRules rules1 = new QwSopTempRules();
                rules1.setDayNum(day.getDayNum());
                rules1.setId(rule.getId());
                qwSopTempRulesMapper.updateQwSopTempRules(rules1);
            }
        }

    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTempRules> listById(List<Long> rulesIds) {
        return list(new QueryWrapper<QwSopTempRules>().in("id", rulesIds));
    }

    @Autowired
    FsUserCourseVideoMapper videoMapper;

    @Override
    public void updateSiFenTemp() {
        List<QwSopTempContentVO> contents = contentMapper.updateSiFenTemp();
        for (QwSopTempContentVO content : contents) {
            if (content.getVideoId() == null) {
                continue;
            }
            QwSopTempContent content1 = new QwSopTempContent();
            FsUserCourseVideo video = videoMapper.selectFsUserCourseVideoByVideoId(content.getVideoId());
            QwSopTempSetting.Content.Setting settingMap = new QwSopTempSetting.Content.Setting();
            QwSopTempSetting.Content.Setting setting = JSON.parseObject(content.getContent(), QwSopTempSetting.Content.Setting.class);
            settingMap.setContentType("4");
            settingMap.setMiniprogramAppid("wx73f85f8d62769119");
            settingMap.setMiniprogramPicUrl(setting.getLinkImageUrl());
            settingMap.setMiniprogramTitle(video.getTitle());
            String contentJson = JSON.toJSONString(settingMap);
            content1.setId(content.getId());
            content1.setContentType(4);
            content1.setContent(contentJson);
            contentMapper.updateQwSopTempContent(content1);
        }
    }

    @Override
    public List<QwSopTempRules> listByCourseId(Long courseId) {
//        return list(new QueryWrapper<QwSopTempRules>().eq("course_id", courseId));
        return qwSopTempRulesMapper.listByCourseId(courseId);
    }

    @Override
    public List<QwSopTempRules> listByCourseIdAndTempId(Long courseId, String tempId) {
        return qwSopTempRulesMapper.listByCourseIdAndTempId(courseId,tempId);
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void removeByTempIds(Collection<String> tempIds) {
        this.remove(new QueryWrapper<QwSopTempRules>().in("temp_id", tempIds));
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public List<QwSopTempRules> selectListByDayId(Long id) {
        return list(new QueryWrapper<QwSopTempRules>().eq("day_id", id));
    }

    @Override
    @DataSource(DataSourceType.SOP)
    public void removeByWrapper(LambdaQueryWrapper<QwSopTempRules> wrapper) {
        this.remove(wrapper);
    }
}
