package com.microservices.zone.member.service.impl;

import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.PageUtils;
import com.microservices.common.core.utils.html.EscapeUtil;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.datascope.annotation.DataScope;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.zone.detail.service.IZoneDetailService;
import com.microservices.zone.member.domain.points.ZonePointsApply;
import com.microservices.zone.member.domain.vo.ZonePointsApplyDetailVo;
import com.microservices.zone.member.domain.vo.ZonePointsApplyInputVo;
import com.microservices.zone.member.domain.vo.ZonePointsApplySearchVo;
import com.microservices.zone.member.domain.vo.ZonePointsApplyUpdateVo;
import com.microservices.zone.member.mapper.ZonePointsApplyMapper;
import com.microservices.zone.member.service.IZonePointsApplyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 积分申请表Service业务层处理
 *
 * @author otto
 */
@Service
public class ZonePointsApplyServiceImpl implements IZonePointsApplyService {
    @Autowired
    private ZonePointsApplyMapper zonePointsApplyMapper;

    @Autowired
    private IZoneDetailService zoneDetailService;

    @Value("${http.gitLinkUrl}")
    private String gitLinkUrl;

    /**
     * 查询积分申请
     *
     * @param id 积分申请主键
     * @return 积分申请
     */
    @Override
    public ZonePointsApply selectZonePointsApplyById(Long id) {
        ZonePointsApply zonePointsApply = zonePointsApplyMapper.selectZonePointsApplyById(id);
        if (zonePointsApply == null) {
            throw new ServiceException("该积分申请不存在或无权限访问(积分申请id[" + id + "])");
        }
        zoneDetailService.checkZoneDataScope(zonePointsApply.getZoneId());
        return zonePointsApply;
    }

    /**
     * 查询积分申请列表
     *
     * @param zonePointsApply 积分申请
     * @return 积分申请
     */
    @Override
    @DataScope(deptAlias = "zpa")
    public GenericsTableDataInfo<ZonePointsApplyDetailVo> selectZonePointsApplyList(ZonePointsApplySearchVo searchVo) {
        List<ZonePointsApply> list = zonePointsApplyMapper.selectZonePointsApplyList(searchVo);
        return PageUtils.toPage(list, this::toZonePointsApplyDetailVo);
    }

    private ZonePointsApplyDetailVo toZonePointsApplyDetailVo(ZonePointsApply zonePointsApply) {
        ZonePointsApplyDetailVo vo = new ZonePointsApplyDetailVo();
        BeanUtils.copyProperties(zonePointsApply, vo);
        if (zonePointsApply.getSysUser() != null) {
            String username = zonePointsApply.getSysUser().getUserName();
            vo.setUserName(username);
            vo.setGitLinkUserUrl(
                    EscapeUtil.removeExtraSlashOfUrl(
                            gitLinkUrl + "/" + username
                    ));
        }
        return vo;
    }

    /**
     * 新增积分申请
     *
     * @param inputVo 积分申请
     * @return 结果
     */
    @Override
    public int insertZonePointsApply(ZonePointsApplyInputVo inputVo) {
        ZonePointsApply zonePointsApply = inputVo.toZonePointsApply();
        zonePointsApply.setCreateTime(DateUtils.getNowDate());
        zonePointsApply.setCreateBy(SecurityUtils.getUsername());
        return zonePointsApplyMapper.insertZonePointsApply(zonePointsApply);
    }

    /**
     * 修改积分申请
     *
     * @param updateVo 积分申请
     * @return 结果
     */
    @Override
    public int updateZonePointsApply(ZonePointsApplyUpdateVo updateVo) {
        ZonePointsApply oldApply = selectZonePointsApplyById(updateVo.getId());
        ZonePointsApply zonePointsApply = updateVo.toZonePointsApply();
        zonePointsApply.setUpdateTime(DateUtils.getNowDate());
        zonePointsApply.setUpdateBy(SecurityUtils.getUsername());
        return zonePointsApplyMapper.updateZonePointsApply(zonePointsApply);
    }

    /**
     * 批量删除积分申请
     *
     * @param ids 需要删除的积分申请主键
     * @return 结果
     */
    @Override
    public int deleteZonePointsApplyByIds(Long[] ids) {
        int success = 0;
        for (Long id : ids) {
            success += deleteZonePointsApplyById(id);
        }
        return success;
    }

    /**
     * 删除积分申请信息
     *
     * @param id 积分申请主键
     * @return 结果
     */
    @Override
    public int deleteZonePointsApplyById(Long id) {
        selectZonePointsApplyById(id);
        return zonePointsApplyMapper.deleteZonePointsApplyById(id);
    }

    /**
     * 根据用户ID和专区ID查询积分申请列表
     *
     * @param userId 用户ID
     * @param zoneId 专区ID
     * @return 积分申请列表
     */
    @Override
    public List<ZonePointsApply> selectZonePointsApplyByUserIdAndZoneId(Long userId, Long zoneId) {
        return zonePointsApplyMapper.selectZonePointsApplyByUserIdAndZoneId(userId, zoneId);
    }

    /**
     * 检查用户是否有某类型的待处理申请（幂等校验）
     *
     * @param userId    用户ID
     * @param zoneId    专区ID
     * @param applyType 申请类型
     * @return true=已有待处理申请
     */
    @Override
    public boolean hasPendingApply(Long userId, Long zoneId, String applyType) {
        return zonePointsApplyMapper.countPendingByUserZoneAndType(userId, zoneId, applyType) > 0;
    }
}