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.StringUtils;
import com.microservices.common.datascope.annotation.DataScope;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.zone.detail.domain.ZoneDetail;
import com.microservices.zone.detail.service.IZoneDetailService;
import com.microservices.zone.member.domain.ZoneMember;
import com.microservices.zone.member.domain.ZoneMemberLevel;
import com.microservices.zone.member.domain.vo.ZoneMemberLevelUpdateVo;
import com.microservices.zone.member.domain.vo.ZoneMemberSearchVo;
import com.microservices.zone.member.mapper.ZoneMemberLevelMapper;
import com.microservices.zone.member.mapper.ZoneMemberMapper;
import com.microservices.zone.member.service.IZoneMemberLevelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 特色专区会员身份Service业务层处理
 *
 * @author otto
 * @date 2023-05-26
 */
@Service
public class ZoneMemberLevelServiceImpl implements IZoneMemberLevelService {
    private static final Logger logger = LoggerFactory.getLogger(ZoneMemberLevelServiceImpl.class);
    @Autowired
    private ZoneMemberLevelMapper zoneMemberLevelMapper;
    @Autowired
    private ZoneMemberMapper zoneMemberMapper;
    @Autowired
    private IZoneDetailService zoneDetailService;

    /**
     * 查询特色专区会员身份
     *
     * @param id 特色专区会员身份主键
     * @return 特色专区会员身份
     */
    @Override
    public ZoneMemberLevel selectZoneMemberLevelById(Long id) {
        ZoneMemberLevel zoneMemberLevel = zoneMemberLevelMapper.selectZoneMemberLevelById(id);
        if (zoneMemberLevel == null) {
            throw new ServiceException("该特色专区会员身份不存在或无权限访问(特色专区会员身份id[" + id + "])");
        }
        zoneDetailService.checkZoneDataScope(zoneMemberLevel.getZoneId());
        return zoneMemberLevel;
    }

    /**
     * 查询特色专区会员身份列表
     *
     * @param zoneMemberLevel 特色专区会员身份
     * @return 特色专区会员身份
     */
    @Override
    @DataScope(deptAlias = "zml")
    public List<ZoneMemberLevel> selectZoneMemberLevelList(ZoneMemberLevel zoneMemberLevel) {
        return zoneMemberLevelMapper.selectZoneMemberLevelList(zoneMemberLevel);
    }

    /**
     * 新增特色专区会员身份
     *
     * @param zoneMemberLevel 特色专区会员身份
     * @return 结果
     */
    @Override
    public int insertZoneMemberLevel(ZoneMemberLevel zoneMemberLevel) {
        zoneDetailService.checkZoneDataScope(zoneMemberLevel.getZoneId());
        checkNameInZone(zoneMemberLevel.getZoneId(), zoneMemberLevel.getName());
        zoneMemberLevel.setCreateTime(DateUtils.getNowDate());
        ZoneDetail zoneDetail = zoneDetailService.selectZoneDetailById(zoneMemberLevel.getZoneId());
        zoneMemberLevel.setDeptId(zoneDetail.getDeptId());
        //设置排序值为当前最大的排序值+1
        Integer maxSort = zoneMemberLevelMapper.selectMaxSortByZoneId(zoneMemberLevel.getZoneId());
        if (maxSort == null) {
            maxSort = 1;
        } else {
            maxSort++;
        }
        zoneMemberLevel.setSort(maxSort);
        return zoneMemberLevelMapper.insertZoneMemberLevel(zoneMemberLevel);
    }

    /**
     * 检查该特色专区下是否已存在该名称的身份
     *
     * @param zoneId
     * @param name
     */
    private void checkNameInZone(Long zoneId, String name) {
        List<ZoneMemberLevel> zoneMemberLevelList = zoneMemberLevelMapper.selectZoneMemberLevelListByNameAndZoneId(name, zoneId);
        if (!zoneMemberLevelList.isEmpty()) {
            throw new ServiceException("该特色专区下会员身份名称已存在(特色专区会员身份名称[" + name + "])");
        }
    }

    /**
     * 修改特色专区会员身份
     *
     * @param zoneMemberLevelUpdateVo 特色专区会员身份
     * @return 结果
     */
    @Override
    public int updateZoneMemberLevel(ZoneMemberLevelUpdateVo zoneMemberLevelUpdateVo) {
        ZoneMemberLevel oldZoneMemberLevel = selectZoneMemberLevelById(zoneMemberLevelUpdateVo.getId());
        if (!StringUtils.isEmpty(zoneMemberLevelUpdateVo.getName()) && !zoneMemberLevelUpdateVo.getName().equals(oldZoneMemberLevel.getName())) {
            checkNameInZone(oldZoneMemberLevel.getZoneId(), zoneMemberLevelUpdateVo.getName());
        }
        ZoneMemberLevel zoneMemberLevel = zoneMemberLevelUpdateVo.toZoneMemberLevel();
        zoneMemberLevel.setUpdateTime(DateUtils.getNowDate());
        zoneMemberLevel.setUpdateBy(SecurityUtils.getUsername());
        if (zoneMemberLevelUpdateVo.getOrder() != null) {
            Integer setSort = setSortByOrder(oldZoneMemberLevel, zoneMemberLevelUpdateVo.getOrder());
            zoneMemberLevel.setSort(setSort);
        }
        return zoneMemberLevelMapper.updateZoneMemberLevel(zoneMemberLevel);
    }

    private Integer setSortByOrder(ZoneMemberLevel zoneMemberLevel, Integer order) {
        int setSort;
        Long zoneId = zoneMemberLevel.getZoneId();
        Long id = zoneMemberLevel.getId();
        String name = zoneMemberLevel.getName();
        Integer maxCount = zoneMemberLevelMapper.selectCountByZoneId(zoneId);
        //检查用户输入顺序是否合法
        if (order < 1 || order > maxCount) {
            throw new ServiceException(String.format("顺序最小为1，最大为%d(会员身份[%s])", maxCount, name));
        }
        //获取所在行
        ZoneMemberLevel theOrderContainSelf = zoneMemberLevelMapper.selectZoneMemberLevelByOrderAndZoneId(zoneMemberLevel, order, true);
        //当指定序号为当前数据时，不修改排序
        if (theOrderContainSelf != null && theOrderContainSelf.getId().equals(id)) {
            return null;
        }

        if (order == 1 || order.equals(maxCount)) {
            int minSort = zoneMemberLevelMapper.selectMinSortByZoneId(zoneId);
            int maxSort = zoneMemberLevelMapper.selectMaxSortByZoneId(zoneId);
            //当用户输入顺序为1时，数据顺序调整为最小值-1
            if (order == 1) {
                setSort = (minSort - 1);
            } else {
                //当用户输入顺序为列表总数时，文章顺序调整为最小值-1.栏目顺序调整为最大值+1
                setSort = (maxSort + 1);
            }
        } else {
            //获取指定序号的文章/栏目(不包含当前文章/栏目)
            ZoneMemberLevel theOrderData = zoneMemberLevelMapper.selectZoneMemberLevelByOrderAndZoneId(
                    zoneMemberLevel, order, false);
            if (theOrderData == null) {
                throw new ServiceException(String.format("指定顺序不存在(名称[%s]，顺序[%d])", name, order));
            }
            //计算用户上一个序号对应的排序值(不包含当前文章/栏目)
            ZoneMemberLevel theLastOrderData = zoneMemberLevelMapper.selectZoneMemberLevelByOrderAndZoneId(
                    zoneMemberLevel, order - 1, false);
            Integer theLastSort = theLastOrderData.getSort();
            if (theOrderData.getSort() - theLastSort > 1) {
                setSort = theLastSort + 1;
            } else {
                setSort = theOrderData.getSort();
                //需要将大于等于该sort的所有数据项sort+1
                Integer updateCount = zoneMemberLevelMapper.batchUpdateSortIncreased(zoneId, setSort);
                logger.info("批量增加大于指定排序的排序值，共计更新{}条", updateCount);
            }
        }
        return setSort;
    }

    /**
     * 批量删除特色专区会员身份
     *
     * @param ids 需要删除的特色专区会员身份主键
     * @return 结果
     */
    @Override
    public int deleteZoneMemberLevelByIds(Long[] ids) {
        int success = 0;
        for (Long id:ids){
            success += deleteZoneMemberLevelById(id);
        }
        return success;
    }

    /**
     * 删除特色专区会员身份信息
     *
     * @param id 特色专区会员身份主键
     * @return 结果
     */
    @Override
    public int deleteZoneMemberLevelById(Long id) {
        selectZoneMemberLevelById(id);
        ZoneMemberSearchVo zoneMemberSearchVo = new ZoneMemberSearchVo();
        zoneMemberSearchVo.setMemberLevelId(id);
        List<ZoneMember> zoneMemberList = zoneMemberMapper.selectZoneMemberList(zoneMemberSearchVo);
        if (zoneMemberList != null && !zoneMemberList.isEmpty()) {
            String names = zoneMemberList.stream().map(ZoneMember::getName).collect(Collectors.joining(","));
            throw new ServiceException("该会员身份已被会员绑定(特色专区会员身份id[" + id + "]，会员名称[" + names + "])");
        }
        return zoneMemberLevelMapper.deleteZoneMemberLevelById(id);
    }

    @Override
    public ZoneMemberLevel selectZoneMemberLevelByIdAndZoneId(Long memberLevelId, Long zoneId) {
        ZoneMemberLevel zoneMemberLevel = zoneMemberLevelMapper.selectZoneMemberLevelByIdAndZoneId(memberLevelId, zoneId);
        if (zoneMemberLevel == null) {
            throw new ServiceException("该特色专区下不存在该会员身份或无权限访问(特色专区会员身份id[" + memberLevelId + "]，特色专区id[" + zoneId + "])");
        }
        return zoneMemberLevel;
    }
}
