package com.ruoyi.bst.areaJoin.service.impl;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.areaJoin.domain.AreaJoin;
import com.ruoyi.bst.areaJoin.domain.AreaJoinQuery;
import com.ruoyi.bst.areaJoin.domain.AreaJoinVO;
import com.ruoyi.bst.areaJoin.mapper.AreaJoinMapper;
import com.ruoyi.bst.areaJoin.service.AreaJoinService;
import com.ruoyi.bst.areaJoin.service.AreaJoinValidator;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.system.role.service.RoleService;

import lombok.extern.slf4j.Slf4j;

/**
 * 运营加盟Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-25
 */
@Service
@Slf4j
public class AreaJoinServiceImpl implements AreaJoinService
{
    @Autowired
    private AreaJoinMapper areaJoinMapper;

    @Autowired
    private AreaJoinValidator areaJoinValidator;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private RoleService roleService;

    /**
     * 查询运营加盟
     *
     * @param id 运营加盟主键
     * @return 运营加盟
     */
    @Override
    public AreaJoinVO selectAreaJoinById(Long id, boolean scope)
    {
        if (id == null) {
            return null;
        }
        AreaJoinQuery query = new AreaJoinQuery();
        query.setId(id);
        query.setScope(scope);
        return this.selectOne(query);
    }

    @Override
    public AreaJoinVO selectOne(AreaJoinQuery query) {
        PageHelper.startPage(1, 1);
        List<AreaJoinVO> list = areaJoinMapper.selectAreaJoinList(query);
        return CollectionUtils.firstElement(list);
    }

    @Override
    public AreaJoinVO selectByUserArea(Long userId, Long areaId) {
        if (userId == null || areaId == null) {
            return null;
        }
        AreaJoinQuery query = new AreaJoinQuery();
        query.setUserId(userId);
        query.setAreaId(areaId);
        return this.selectOne(query);
    }

    @Override
    public List<AreaJoinVO> selectListByAreaId(Long areaId, String type) {
        if (areaId == null || StringUtils.isBlank(type)) {
            return Collections.emptyList();
        }
        AreaJoinQuery query = new AreaJoinQuery();
        query.setAreaId(areaId);
        query.setType(type);
        return areaJoinMapper.selectAreaJoinList(query);
    }

    /**
     * 查询运营加盟列表
     *
     * @param areaJoin 运营加盟
     * @return 运营加盟
     */
    @Override
    public List<AreaJoinVO> selectAreaJoinList(AreaJoinQuery areaJoin)
    {
        return areaJoinMapper.selectAreaJoinList(areaJoin);
    }

    /**
     * 新增运营加盟
     *
     * @param areaJoin 运营加盟
     * @return 结果
     */
    @Override
    public int insertAreaJoin(AreaJoin areaJoin)
    {
        areaJoin.setCreateTime(DateUtils.getNowDate());

        Integer result = transactionTemplate.execute(status -> {
            int rows = areaJoinMapper.insertAreaJoin(areaJoin);

            if (rows > 0) {
                // 尝试修改用户角色
                this.tryUpdateUserRole(areaJoin);

                // 后校验
                areaJoinValidator.afterCheck(areaJoin.getId());
            }

            return rows;
        });

        return result == null ? 0 : result;
    }

    /**
     * 修改运营加盟
     *
     * @param areaJoin 运营加盟
     * @return 结果
     */
    @Override
    public int updateAreaJoin(AreaJoin areaJoin)
    {
        Integer result = transactionTemplate.execute(status -> {
            int rows = areaJoinMapper.updateAreaJoin(areaJoin);

            if (rows > 0) {
                // 尝试修改用户角色
                this.tryUpdateUserRole(areaJoin);

                // 后校验
                areaJoinValidator.afterCheck(areaJoin.getId());
            }

            return rows;
        });

        return result == null ? 0 : result;
    }

    /** 
     * 尝试修改用户角色
     * 
     * @param areaJoin
     */
    private void tryUpdateUserRole(AreaJoin areaJoin) {
        try {
            roleService.insertAuthUsers(RoleConstants.JOIN, Collections.singletonList(areaJoin.getUserId()));
        } catch (Exception e) {
            log.warn("尝试修改ID为{}的用户角色失败:{}", areaJoin.getUserId(), e);
        }
    }
    /**
     * 批量删除运营加盟
     *
     * @param ids 需要删除的运营加盟主键
     * @return 结果
     */
    @Override
    public int deleteAreaJoinByIds(Long[] ids)
    {
        return areaJoinMapper.deleteAreaJoinByIds(ids);
    }

    /**
     * 删除运营加盟信息
     *
     * @param id 运营加盟主键
     * @return 结果
     */
    @Override
    public int deleteAreaJoinById(Long id)
    {
        return areaJoinMapper.deleteAreaJoinById(id);
    }
}
