
package com.tmerclub.cloud.im.service.impl;

import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.im.dto.ImMsgBizSkillsDTO;
import com.tmerclub.cloud.im.mapper.ImMsgBizSkillsMapper;
import com.tmerclub.cloud.im.service.ImMsgBizSkillsService;
import com.tmerclub.cloud.im.vo.ImMsgBizSkillsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 客服自动回复表
 *
 * @author tmerclub
 * @date 2023-03-23 17:43:40
 */
@Service
public class ImMsgBizSkillsServiceImpl implements ImMsgBizSkillsService {

    @Autowired
    private ImMsgBizSkillsMapper imMsgBizSkillsMapper;

    @Override
    public PageVO<ImMsgBizSkillsVO> page(PageDTO pageDTO, ImMsgBizSkillsDTO imMsgBizSkillsDTO, Long shopId) {
        return PageUtil.doPage(pageDTO, () -> imMsgBizSkillsMapper.list(imMsgBizSkillsDTO, shopId));
    }

    @Override
    public ImMsgBizSkillsVO getById(Long id) {
        return imMsgBizSkillsMapper.getById(id);
    }

    @Override
    public void save(ImMsgBizSkillsVO imMsgBizSkills) {
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setStatus(1);
        imMsgBizSkills.setCreateTime(new Date());
        imMsgBizSkills.setUpdateTime(new Date());
        imMsgBizSkillsMapper.save(imMsgBizSkills);
    }

    @Override
    public void update(ImMsgBizSkillsVO imMsgBizSkills) {
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setUpdateTime(new Date());
        imMsgBizSkillsMapper.update(imMsgBizSkills);
    }

    @Override
    public void deleteById(Long id) {
        imMsgBizSkillsMapper.deleteById(id);
    }

    @Override
    public List<ImMsgBizSkillsVO> getByShopId(Long shopId) {
        return imMsgBizSkillsMapper.getByShopId(shopId);
    }

    private void checkSkills(ImMsgBizSkillsVO imMsgBizSkills) {
        ImMsgBizSkillsVO selectOne = imMsgBizSkillsMapper.selectByShopIdAndKey(imMsgBizSkills.getShopId(), imMsgBizSkills.getKeywords());
        if (Objects.nonNull(selectOne)) {
            if (imMsgBizSkills.getId() != null && Objects.equals(imMsgBizSkills.getId(), selectOne.getId())) {
                // 更新操作直接返回
                return;
            }
            throw new LuckException("关键字重复");
        }
    }
}
