package org.dromara.talk.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.dromara.talk.domain.bo.TalkAgentBo;
import org.dromara.talk.domain.vo.TalkAgentVo;
import org.dromara.talk.domain.TalkAgent;
import org.dromara.talk.mapper.TalkAgentMapper;
import org.dromara.talk.service.ITalkAgentService;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Collection;
import java.util.UUID;

/**
 * 客服配置Service业务层处理
 *
 * @author Lion Li
 *  2026-01-27
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TalkAgentServiceImpl implements ITalkAgentService {

    private final TalkAgentMapper baseMapper;

    /**
     * 查询客服配置
     *
     * @param id 主键
     * @return 客服配置
     */
    @Override
    public TalkAgentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询客服配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 客服配置分页列表
     */
    @Override
    public TableDataInfo<TalkAgentVo> queryPageList(TalkAgentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TalkAgent> lqw = buildQueryWrapper(bo);
        Page<TalkAgentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的客服配置列表
     *
     * @param bo 查询条件
     * @return 客服配置列表
     */
    @Override
    public List<TalkAgentVo> queryList(TalkAgentBo bo) {
        LambdaQueryWrapper<TalkAgent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TalkAgent> buildQueryWrapper(TalkAgentBo bo) {
        LambdaQueryWrapper<TalkAgent> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TalkAgent::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), TalkAgent::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), TalkAgent::getGender, bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatarUrl()), TalkAgent::getAvatarUrl, bo.getAvatarUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getGreetingMessage()), TalkAgent::getGreetingMessage, bo.getGreetingMessage());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TalkAgent::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getTtsVcn()), TalkAgent::getTtsVcn, bo.getTtsVcn());
        lqw.eq(bo.getTtsSpeed() != null, TalkAgent::getTtsSpeed, bo.getTtsSpeed());
        lqw.eq(bo.getTtsPitch() != null, TalkAgent::getTtsPitch, bo.getTtsPitch());
        lqw.eq(bo.getTtsVolume() != null, TalkAgent::getTtsVolume, bo.getTtsVolume());
        lqw.eq(bo.getTtsBgs() != null, TalkAgent::getTtsBgs, bo.getTtsBgs());
        return lqw;
    }

    /**
     * 新增客服配置
     *
     * @param bo 客服配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TalkAgentBo bo) {
        TalkAgent add = MapstructUtils.convert(bo, TalkAgent.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改客服配置
     *
     * @param bo 客服配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TalkAgentBo bo) {
        TalkAgent update = MapstructUtils.convert(bo, TalkAgent.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 校验并批量删除客服配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 上传客服头像
     *
     * @param file 上传的文件
     * @return 文件访问路径
     * @throws IOException IO异常
     */
    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null && originalFilename.contains(".")
            ? originalFilename.substring(originalFilename.lastIndexOf("."))
            : "";

        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID() + extension;

        String uploadDir = System.getProperty("user.dir") + File.separator + "uploads" + File.separator + "avatars" + File.separator;
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File destFile = new File(uploadDir + fileName);
        file.transferTo(destFile);

        return "/uploads/avatars/" + fileName;
    }

    /**
     * 改变客服状态（带并发控制）
     * 使用乐观锁机制确保状态更新的原子性
     *
     * @param id        客服ID
     * @param newStatus 新状态
     * @return 是否修改成功
     */
    @Override
    public Boolean changeAgentStatus(Long id, String newStatus) {
        // 查询当前客服信息
        TalkAgent agent = baseMapper.selectById(id);
        if (agent == null) {
            log.warn("客服不存在: id={}", id);
            return false;
        }

        // 如果要设置为对话中状态，需要检查当前状态
        if ("2".equals(newStatus)) {
            // 只有状态为0（正常）的客服才能被设置为对话中
            if (!"0".equals(agent.getStatus())) {
                log.warn("客服状态不允许转换为对话中: id={}, currentStatus={}", id, agent.getStatus());
                return false;
            }

            // 使用条件更新确保原子性：只有当状态仍为0时才更新为2
            int updated = baseMapper.update(null,
                Wrappers.<TalkAgent>lambdaUpdate()
                    .eq(TalkAgent::getId, id)
                    .eq(TalkAgent::getStatus, "0")  // 条件：当前状态必须为0
                    .set(TalkAgent::getStatus, "2")  // 更新为2
            );

            if (updated == 0) {
                log.warn("客服状态更新失败，可能已被其他用户占用: id={}", id);
                return false;
            }

            log.info("客服状态已更新为对话中: id={}", id);
            return true;
        }

        // 其他状态转换直接更新
        agent.setStatus(newStatus);
        boolean result = baseMapper.updateById(agent) > 0;
        if (result) {
            log.info("客服状态已更新: id={}, newStatus={}", id, newStatus);
        }
        return result;
    }

    /**
     * 根据用户ID查询客服
     *
     * @param userId 用户ID
     * @return 客服配置
     */
    @Override
    public TalkAgentVo queryByUserId(Long userId) {
        LambdaQueryWrapper<TalkAgent> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkAgent::getUserId, userId);
        return baseMapper.selectVoOne(lqw);
    }
}
