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.ZoneMemberType;
import com.microservices.zone.member.domain.vo.ZoneMemberSearchVo;
import com.microservices.zone.member.domain.vo.ZoneMemberTypeUpdateVo;
import com.microservices.zone.member.mapper.ZoneMemberMapper;
import com.microservices.zone.member.mapper.ZoneMemberTypeMapper;
import com.microservices.zone.member.service.IZoneMemberTypeService;
import com.microservices.zone.utils.ZoneConstants;
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-16
 */
@Service
public class ZoneMemberTypeServiceImpl implements IZoneMemberTypeService {
    private static final Logger logger = LoggerFactory.getLogger(ZoneMemberTypeServiceImpl.class);
    @Autowired
    private ZoneMemberTypeMapper zoneMemberTypeMapper;
    @Autowired
    private ZoneMemberMapper zoneMemberMapper;
    @Autowired
    private IZoneDetailService zoneDetailService;

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

    /**
     * 查询特色专区会员类别列表
     *
     * @param zoneMemberType 特色专区会员类别
     * @return 特色专区会员类别
     */
    @Override
    @DataScope(deptAlias = "zmt")
    public List<ZoneMemberType> selectZoneMemberTypeList(ZoneMemberType zoneMemberType) {
        return zoneMemberTypeMapper.selectZoneMemberTypeList(zoneMemberType);
    }

    /**
     * 新增特色专区会员类别
     *
     * @param zoneMemberType 特色专区会员类别
     * @return 结果
     */
    @Override
    public int insertZoneMemberType(ZoneMemberType zoneMemberType) {
        zoneDetailService.checkZoneDataScope(zoneMemberType.getZoneId());
        checkNameInZone(zoneMemberType.getZoneId(), zoneMemberType.getName());
        ZoneDetail zoneDetail = zoneDetailService.selectZoneDetailById(zoneMemberType.getZoneId());
        zoneMemberType.setDeptId(zoneDetail.getDeptId());
        zoneMemberType.setCreateTime(DateUtils.getNowDate());
        zoneMemberType.setCreateBy(SecurityUtils.getUsername());
        //设置排序值为当前最大的排序值+1
        Integer maxSort = zoneMemberTypeMapper.selectMaxSortByZoneId(zoneMemberType.getZoneId());
        if (maxSort == null) {
            maxSort = 1;
        } else {
            maxSort++;
        }
        zoneMemberType.setSort(maxSort);
        return zoneMemberTypeMapper.insertZoneMemberType(zoneMemberType);
    }

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

    /**
     * 修改特色专区会员类别
     *
     * @param zoneMemberTypeUpdateVo 特色专区会员类别
     * @return 结果
     */
    @Override
    public int updateZoneMemberType(ZoneMemberTypeUpdateVo zoneMemberTypeUpdateVo) {
        ZoneMemberType oldZoneMemberType = selectZoneMemberTypeById(zoneMemberTypeUpdateVo.getId());
        if (!StringUtils.isEmpty(zoneMemberTypeUpdateVo.getName()) && !zoneMemberTypeUpdateVo.getName().equals(oldZoneMemberType.getName())) {
            checkNameInZone(oldZoneMemberType.getZoneId(), zoneMemberTypeUpdateVo.getName());
        }
        ZoneMemberType zoneMemberType = zoneMemberTypeUpdateVo.toZoneMemberType();
        zoneMemberType.setUpdateTime(DateUtils.getNowDate());
        zoneMemberType.setUpdateBy(SecurityUtils.getUsername());
        if (zoneMemberTypeUpdateVo.getOrder() != null) {
            Integer setSort = setSortByOrder(oldZoneMemberType, zoneMemberTypeUpdateVo.getOrder());
            zoneMemberType.setSort(setSort);
        }
        return zoneMemberTypeMapper.updateZoneMemberType(zoneMemberType);
    }

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

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

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

    /**
     * 删除特色专区会员类别信息
     *
     * @param id 特色专区会员类别主键
     * @return 结果
     */
    @Override
    public int deleteZoneMemberTypeById(Long id) {
        selectZoneMemberTypeById(id);
        ZoneMemberSearchVo zoneMemberSearchVo = new ZoneMemberSearchVo();
        zoneMemberSearchVo.setMemberTypeId(id);
        zoneMemberSearchVo.setIsAudit(ZoneConstants.MEMBER_AUDIT_PASS);
        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 zoneMemberTypeMapper.deleteZoneMemberTypeById(id);
    }

    @Override
    public ZoneMemberType selectZoneMemberTypeByIdAndZoneId(Long memberTypeId, Long zoneId) {
        ZoneMemberType zoneMemberType = zoneMemberTypeMapper.selectZoneMemberTypeByIdAndZoneId(memberTypeId, zoneId);
        if (zoneMemberType == null) {
            throw new ServiceException("该特色专区下不存在该会员类别或无权限访问(特色专区会员类别id[" + memberTypeId + "]，特色专区id[" + zoneId + "])");
        }
        return zoneMemberType;
    }
}
