package com.xinelu.manage.service.textmessage.impl;

import com.xinelu.common.annotation.DataScope;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.domain.entity.SysDictData;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.manage.domain.textmessage.TextMessage;
import com.xinelu.manage.domain.textmessagesuittask.TextMessageSuitTask;
import com.xinelu.manage.dto.textmessage.TextMessageDTO;
import com.xinelu.manage.dto.textmessage.TextMessageTaskDTO;
import com.xinelu.manage.mapper.textmessage.TextMessageMapper;
import com.xinelu.manage.service.textmessage.ITextMessageService;
import com.xinelu.manage.vo.textmessage.TextMessageTaskVO;
import com.xinelu.manage.vo.textmessage.TextMessageVO;
import com.xinelu.system.mapper.SysDictDataMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 短信模板信息Service业务层处理
 *
 * @author xinelu
 * @date 2024-02-28
 */
@Service
public class TextMessageServiceImpl implements ITextMessageService {
    @Resource
    private TextMessageMapper textMessageMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 查询短信模板信息
     *
     * @param id 短信模板信息主键
     * @return 短信模板信息
     */
    @Override
    public TextMessageTaskVO selectTextMessageById(Long id) {
        // 初始化返回TextMessageTaskVO
        TextMessageTaskVO textMessageTaskVO = new TextMessageTaskVO();
        // 根据id查询短信模板信息
        TextMessageVO vo = textMessageMapper.selectTextMessageInfoById(id);
        // 将wechatTemplateVO赋值给textMessageTaskVO
        BeanUtils.copyProperties(vo, textMessageTaskVO);
        // 获取到suitTaskTypeIds并赋值给textMessageTaskVO
        if (vo.getSuitTaskList() != null) {
            Long[] suitTaskTypeIds = vo.getSuitTaskList().stream().map(TextMessageSuitTask::getSuitTaskTypeId).toArray(Long[]::new);
            textMessageTaskVO.setSuitTaskTypeIds(suitTaskTypeIds);
        }
        return textMessageTaskVO;
    }

    /**
     * 查询短信模板信息列表
     *
     * @param textMessageDTO 短信模板信息
     * @return 短信模板信息
     */
    @DataScope(agencyAlias = "d", deptAlias = "tm")
    @Override
    public List<TextMessageTaskVO> selectTextMessageList(TextMessageDTO textMessageDTO) {
        List<TextMessageVO> voList = textMessageMapper.selectTextMessageList(textMessageDTO);
        // 转换 voList 到 TextMessageTaskVO 列表
        return voList.stream().map(vo -> {
            TextMessageTaskVO taskVO = new TextMessageTaskVO();
            // 复制属性
            BeanUtils.copyBeanProp(taskVO, vo);
            // 提取 suitTaskList 中的 typeName 字段并用逗号拼接
            String suitTaskTypeNames = (vo.getSuitTaskList() != null) ? vo.getSuitTaskList().stream()
                    .map(TextMessageSuitTask::getSuitTaskTypeName)
                    .collect(Collectors.joining(", ")) : "";
            taskVO.setSuitTaskTypeName(suitTaskTypeNames);
            return taskVO;
        }).collect(Collectors.toList());
    }

    /**
     * 新增短信模板信息
     *
     * @param textMessageTaskDTO 短信模板信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTextMessage(TextMessageTaskDTO textMessageTaskDTO) {
        // 检查短信模板名称是否已存在
        if (textMessageMapper.countByTextMessageTaskDTO(textMessageTaskDTO) > 0) {
            throw new ServiceException("短信模板编号已存在");
        }

        // 设置创建者和创建时间
        String currentUsername = SecurityUtils.getUsername();
        LocalDateTime currentTime = LocalDateTime.now();
        textMessageTaskDTO.setCreateBy(currentUsername);
        textMessageTaskDTO.setCreateTime(currentTime);

        // 将textMessageTaskDTO对象的属性复制到textMessage对象
        TextMessage textMessage = new TextMessage();
        BeanUtils.copyProperties(textMessageTaskDTO, textMessage);

        // 插入textMessage记录并检查结果
        if (textMessageMapper.insertTextMessage(textMessage) <= 0) {
            throw new ServiceException("新增短信模板失败");
        }

        // 批量创建TextMessageSuitTask对象并插入
        List<TextMessageSuitTask> tasks = new ArrayList<>();
        for (Long suitTaskTypeId : textMessageTaskDTO.getSuitTaskTypeIds()) {
            TextMessageSuitTask task = createTextMessageSuitTask(suitTaskTypeId, textMessage.getId(), currentUsername, currentTime);
            tasks.add(task);
        }

        // 批量插入TextMessageSuitTask记录并检查结果
        if (!tasks.isEmpty() && textMessageMapper.insertTextMessageSuitTasks(tasks) != tasks.size()) {
            throw new ServiceException("新增短信模板适用任务类型失败");
        }

        // 返回成功插入的记录数
        return 1;
    }

    private TextMessageSuitTask createTextMessageSuitTask(Long suitTaskTypeId, Long textMessageId, String createdBy, LocalDateTime createdAt) {
        SysDictData sysDictData = sysDictDataMapper.selectDictDataById(suitTaskTypeId);
        TextMessageSuitTask task = new TextMessageSuitTask();
        task.setMessageId(textMessageId);
        task.setSuitTaskTypeId(suitTaskTypeId);
        task.setSuitTaskTypeName(sysDictData.getDictLabel());
        task.setCreateBy(createdBy);
        task.setCreateTime(createdAt);
        return task;
    }

    /**
     * 修改短信模板信息
     *
     * @param textMessageTaskDTO 短信模板信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTextMessage(TextMessageTaskDTO textMessageTaskDTO) {
        // 检查除当前记录之外是否存在同名的短信模板名称
        if (textMessageMapper.countByTextMessageNameExcludingId(textMessageTaskDTO.getId(), textMessageTaskDTO.getDepartmentId(), textMessageTaskDTO.getTextMessageName()) > 0) {
            throw new ServiceException("短信模板名称已存在");
        }

        // 设置修改者和修改时间
        String editUsername = SecurityUtils.getUsername();
        LocalDateTime editTime = LocalDateTime.now();
        textMessageTaskDTO.setUpdateBy(editUsername);
        textMessageTaskDTO.setUpdateTime(editTime);

        // 将textMessageTaskDTO对象的属性复制到textMessage对象
        TextMessage textMessage = new TextMessage();
        BeanUtils.copyProperties(textMessageTaskDTO, textMessage);

        // 插入textMessage记录并检查结果
        if (textMessageMapper.updateTextMessage(textMessage) <= 0) {
            throw new ServiceException("修改短信模板失败");
        }
        // 根据id先删除之前存储的适用模板类型
        textMessageMapper.deleteTextMessageSuitTask(textMessageTaskDTO.getId());
        // 批量创建TextMessageSuitTask对象并插入
        List<TextMessageSuitTask> tasks = new ArrayList<>();
        for (Long suitTaskTypeId : textMessageTaskDTO.getSuitTaskTypeIds()) {
            TextMessageSuitTask task = createTextMessageSuitTask(suitTaskTypeId, textMessage.getId(), editUsername, editTime);
            tasks.add(task);
        }

        // 批量插入TextMessageSuitTask记录并检查结果
        if (!tasks.isEmpty() && textMessageMapper.insertTextMessageSuitTasks(tasks) != tasks.size()) {
            throw new ServiceException("修改短信模板适用任务类型失败");
        }
        // 返回成功插入的记录数
        return 1;
    }


    /**
     * 批量删除短信模板信息
     *
     * @param ids 需要删除的短信模板信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTextMessageByIds(Long[] ids) {
        // 删除短信模板记录并检查结果
        if (textMessageMapper.deleteTextMessageByIds(ids) <= 0) {
            throw new ServiceException("删除短信模板失败");
        }
        // 删除短信模板适用任务类型记录并检查结果
        if (textMessageMapper.deleteTextMessageSuitTasks(ids) < 0) {
            throw new ServiceException("删除短信模板适用任务类型失败");
        }
        // 返回成功删除的记录数
        return 1;
    }

    /**
     * 删除短信模板信息信息
     *
     * @param id 短信模板信息主键
     * @return 结果
     */
    @Override
    public int deleteTextMessageById(Long id) {
        return textMessageMapper.deleteTextMessageById(id);
    }

    /**
     * 查询话术变量
     */
    @Override
    public AjaxResult selectTextMessageVariable(Long id) {
        TextMessage textMessage = textMessageMapper.selectTextMessageById(id);
        if (Objects.isNull(textMessage) || StringUtils.isBlank(textMessage.getVariables())) {
            return AjaxResult.success();
        }
        List<String> variables = Arrays.asList(textMessage.getVariables().split("\\|"));
        Map<String, String> variablehMap = new HashMap<>();
        for (String variable : variables) {
            variablehMap.put(variable, null);
        }
        return AjaxResult.success(variablehMap);
    }
}
