package com.fs.company.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.company.domain.CompanyAiWorkflowServer;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyAiWorkflowServerMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.param.BindCidServerParam;
import com.fs.company.service.ICompanyAiWorkflowServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

/**
 * cid服务Service业务层处理
 *
 * @author fs
 * @date 2026-02-26
 */
@Service
@Slf4j
public class CompanyAiWorkflowServerServiceImpl extends ServiceImpl<CompanyAiWorkflowServerMapper, CompanyAiWorkflowServer> implements ICompanyAiWorkflowServerService {

    @Autowired
    CompanyAiWorkflowServerMapper companyAiWorkflowServerMapper;
    @Autowired
    CompanyUserMapper companyUserMapper;

    /**
     * 查询cid服务
     *
     * @param id cid服务主键
     * @return cid服务
     */
    @Override
    public CompanyAiWorkflowServer selectCompanyAiWorkflowServerById(Long id) {
        return baseMapper.selectCompanyAiWorkflowServerById(id);
    }

    /**
     * 查询cid服务列表
     *
     * @param companyAiWorkflowServer cid服务
     * @return cid服务
     */
    @Override
    public List<CompanyAiWorkflowServer> selectCompanyAiWorkflowServerList(CompanyAiWorkflowServer companyAiWorkflowServer) {
        return baseMapper.selectCompanyAiWorkflowServerList(companyAiWorkflowServer);
    }

    /**
     * 新增cid服务
     *
     * @param companyAiWorkflowServer cid服务
     * @return 结果
     */
    @Override
    public int insertCompanyAiWorkflowServer(CompanyAiWorkflowServer companyAiWorkflowServer) {
        companyAiWorkflowServer.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertCompanyAiWorkflowServer(companyAiWorkflowServer);
    }

    /**
     * 修改cid服务
     *
     * @param companyAiWorkflowServer cid服务
     * @return 结果
     */
    @Override
    public int updateCompanyAiWorkflowServer(CompanyAiWorkflowServer companyAiWorkflowServer) {
        return baseMapper.updateCompanyAiWorkflowServer(companyAiWorkflowServer);
    }

    /**
     * 批量删除cid服务
     *
     * @param ids 需要删除的cid服务主键
     * @return 结果
     */
    @Override
    public int deleteCompanyAiWorkflowServerByIds(Long[] ids) {
        return baseMapper.deleteCompanyAiWorkflowServerByIds(ids);
    }

    /**
     * 删除cid服务信息
     *
     * @param id cid服务主键
     * @return 结果
     */
    @Override
    public int deleteCompanyAiWorkflowServerById(Long id) {
        return baseMapper.deleteCompanyAiWorkflowServerById(id);
    }

    /**
     * 绑定cid服务
     *
     * @param param
     * @return
     */
    @Override
    @Transactional
    public R bindCidServer(BindCidServerParam param) {
        try {
            List<CompanyAiWorkflowServer> availableServerList = companyAiWorkflowServerMapper.getAvailableServerList();
            if (null != availableServerList && availableServerList.size() > 0) {
                Random random = new Random();
                int randomIndex = random.nextInt(availableServerList.size());
                CompanyAiWorkflowServer randomServer = availableServerList.get(randomIndex);
                CompanyAiWorkflowServer server = companyAiWorkflowServerMapper.selectServerForUpdate(randomServer.getId());
                if (server != null) {
                    CompanyUser updateUser = new CompanyUser();
                    updateUser.setUserId(param.getUserId());
                    updateUser.setCidServerId(server.getId());
                    companyUserMapper.updateCompanyUser(updateUser);
                    server.setCount(server.getCount() - 1);
                    companyAiWorkflowServerMapper.updateCompanyAiWorkflowServer(server);
                    return R.ok("绑定成功");
                } else {
                    return R.error("绑定失败，请稍后重试");
                }
            }
            return R.error("绑定失败，没有空闲服务");
        } catch (Exception ex) {
            log.error("bindCidServer内部错误", ex);
            throw new RuntimeException("内部错误");
        }
    }

    /**
     * 解绑cid服务
     * @param param
     * @return
     */
    @Override
    @Transactional
    public R unbindCidServer(BindCidServerParam param) {
        try {
            CompanyUser companyUser = companyUserMapper.selectCompanyUserByCompanyUserId(param.getUserId());
            if (null != companyUser && companyUser.getCidServerId() != null) {
                CompanyAiWorkflowServer server = companyAiWorkflowServerMapper.selectServerUnbindForUpdate(companyUser.getCidServerId());
                if (null != server) {
                    companyUserMapper.unbindCidServer(companyUser.getUserId());
                    server.setCount(server.getCount() + 1);
                    companyAiWorkflowServerMapper.updateCompanyAiWorkflowServer(server);
                    return R.ok("解绑成功");
                } else {
                    return R.error("解除绑定失败，请稍后重试");
                }
            } else {
                return R.error("解除绑定失败，请稍后重试");
            }
        } catch (Exception ex) {
            log.error("bindCidServer内部错误", ex);
            throw new RuntimeException("内部错误");
        }
    }
}
