package com.microservices.zone.partners.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.partners.domain.ZonePartners;
import com.microservices.zone.partners.domain.ZonePartnersType;
import com.microservices.zone.partners.domain.vo.ZonePartnersTypeInputVo;
import com.microservices.zone.partners.domain.vo.ZonePartnersTypeUpdateVo;
import com.microservices.zone.partners.mapper.ZonePartnersMapper;
import com.microservices.zone.partners.mapper.ZonePartnersTypeMapper;
import com.microservices.zone.partners.service.IZonePartnersTypeService;
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;

/**
 * 特色专区合作伙伴分类Service业务层处理
 *
 * @author otto
 * @date 2023-06-20
 */
@Service
public class ZonePartnersTypeServiceImpl implements IZonePartnersTypeService {
    private static final Logger logger = LoggerFactory.getLogger(ZonePartnersTypeServiceImpl.class);

    @Autowired
    private ZonePartnersTypeMapper zonePartnersTypeMapper;
    @Autowired
    private ZonePartnersMapper zonePartnersMapper;

    @Autowired
    private IZoneDetailService zoneDetailService;

    /**
     * 查询特色专区合作伙伴分类
     *
     * @param id 特色专区合作伙伴分类主键
     * @return 特色专区合作伙伴分类
     */
    @Override
    public ZonePartnersType selectZonePartnersTypeById(Long id) {
        ZonePartnersType zonePartnersType = zonePartnersTypeMapper.selectZonePartnersTypeById(id);
        if (zonePartnersType == null) {
            throw new ServiceException("该合作伙伴分类不存在或无权限访问(合作伙伴分类id[" + id + "])");
        }
        zoneDetailService.checkZoneDataScope(zonePartnersType.getZoneId());
        return zonePartnersType;
    }

    /**
     * 查询特色专区合作伙伴分类列表
     *
     * @param zonePartnersType 特色专区合作伙伴分类
     * @return 特色专区合作伙伴分类
     */
    @Override
    @DataScope(deptAlias = "zpt")
    public List<ZonePartnersType> selectZonePartnersTypeList(ZonePartnersType zonePartnersType) {
        return zonePartnersTypeMapper.selectZonePartnersTypeList(zonePartnersType);
    }

    /**
     * 新增特色专区合作伙伴分类
     *
     * @param zonePartnersTypeInputVo 特色专区合作伙伴分类
     * @return 结果
     */
    @Override
    public int insertZonePartnersType(ZonePartnersTypeInputVo zonePartnersTypeInputVo) {
        ZoneDetail zoneDetail = zoneDetailService.selectZoneDetailById(zonePartnersTypeInputVo.getZoneId());
        ZonePartnersType zonePartnersTypeByName = zonePartnersTypeMapper.selectZonePartnersTypeByNameAndZoneId(zonePartnersTypeInputVo.getName(), zonePartnersTypeInputVo.getZoneId());
        if (zonePartnersTypeByName != null) {
            throw new ServiceException("该合作伙伴已存在(合作伙伴分类名称[" + zonePartnersTypeInputVo.getName() + "])");
        }
        ZonePartnersType zonePartnersType = zonePartnersTypeInputVo.toZonePartnersType();
        zonePartnersType.setCreateTime(DateUtils.getNowDate());
        zonePartnersType.setCreateBy(SecurityUtils.getUsername());
        //设置排序值为当前最大的排序值+1
        Integer maxSort = zonePartnersTypeMapper.selectMaxSortByZoneId(zonePartnersTypeInputVo.getZoneId());
        if (maxSort == null) {
            maxSort = 1;
        } else {
            maxSort++;
        }
        zonePartnersType.setSort(maxSort);
        zonePartnersType.setDeptId(zoneDetail.getDeptId());
        return zonePartnersTypeMapper.insertZonePartnersType(zonePartnersType);
    }

    /**
     * 修改特色专区合作伙伴分类
     *
     * @param zonePartnersTypeUpdateVo 特色专区合作伙伴分类
     * @return 结果
     */
    @Override
    public int updateZonePartnersType(ZonePartnersTypeUpdateVo zonePartnersTypeUpdateVo) {
        ZonePartnersType oldZonePartnersType = selectZonePartnersTypeById(zonePartnersTypeUpdateVo.getId());
        if (StringUtils.isNotEmpty(zonePartnersTypeUpdateVo.getName())
                && !zonePartnersTypeUpdateVo.getName().equals(oldZonePartnersType.getName())) {
            ZonePartnersType zonePartnersTypeByName = zonePartnersTypeMapper.selectZonePartnersTypeByNameAndZoneId(
                    zonePartnersTypeUpdateVo.getName()
                    , oldZonePartnersType.getZoneId());
            if (zonePartnersTypeByName != null) {
                throw new ServiceException("该合作伙伴已存在(合作伙伴分类名称[" + zonePartnersTypeUpdateVo.getName() + "])");
            }
        }
        ZonePartnersType zonePartnersType = zonePartnersTypeUpdateVo.toZonePartnersType();
        zonePartnersType.setUpdateTime(DateUtils.getNowDate());
        zonePartnersType.setUpdateBy(SecurityUtils.getUsername());
        if (zonePartnersTypeUpdateVo.getOrder() != null) {
            Integer setSort = setSortByOrder(oldZonePartnersType, zonePartnersTypeUpdateVo.getOrder());
            zonePartnersType.setSort(setSort);
        }

        return zonePartnersTypeMapper.updateZonePartnersType(zonePartnersType);
    }

    private Integer setSortByOrder(ZonePartnersType zonePartnersType, Integer order) {
        int setSort;
        Long zoneId = zonePartnersType.getZoneId();
        Integer maxCount = zonePartnersTypeMapper.selectCountByZoneId(zoneId);
        //检查用户输入顺序是否合法
        if (order < 1 || order > maxCount) {
            throw new ServiceException(String.format("顺序最小为1，最大为%d(合作伙伴分类名称[%s])", maxCount, zonePartnersType.getName()));
        }
        //获取文章/栏目所在行
        ZonePartnersType theOrderContainSelf = zonePartnersTypeMapper.selectZonePartnersTypeByOrderAndZoneId(zonePartnersType, order, true);
        //当指定序号文章/栏目为当前文章/栏目时，不修改排序
        if (theOrderContainSelf != null && theOrderContainSelf.getId().equals(zonePartnersType.getId())) {
            return null;
        }

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

    }

    /**
     * 批量删除特色专区合作伙伴分类
     *
     * @param ids 需要删除的特色专区合作伙伴分类主键
     * @return 结果
     */
    @Override
    public int deleteZonePartnersTypeByIds(Long[] ids) {
        int success = 0;
        for (Long id : ids) {
            success += deleteZonePartnersTypeById(id);
        }
        return success;
    }

    /**
     * 删除特色专区合作伙伴分类信息
     *
     * @param id 特色专区合作伙伴分类主键
     * @return 结果
     */
    @Override
    public int deleteZonePartnersTypeById(Long id) {
        selectZonePartnersTypeById(id);
        ZonePartners zonePartnersSearch = new ZonePartners();
        zonePartnersSearch.setTypeId(id);
        List<ZonePartners> zonePartnersList = zonePartnersMapper.selectZonePartnersList(zonePartnersSearch);
        if (!zonePartnersList.isEmpty()) {
            throw new ServiceException("该分类下存在合作伙伴(分类Id[" + id + "])");
        }
        return zonePartnersTypeMapper.deleteZonePartnersTypeById(id);
    }

    @Override
    public ZonePartnersType selectDefaultZonePartnersType(Long zoneId) {
        ZonePartnersType zonePartnersType = zonePartnersTypeMapper
                .selectZonePartnersTypeByNameAndZoneId(ZoneConstants.DEFAULT_TYPE_NAME, zoneId);
        if (zonePartnersType == null) {
            ZonePartnersTypeInputVo zonePartnersTypeInputVo = new ZonePartnersTypeInputVo();
            zonePartnersTypeInputVo.setName(ZoneConstants.DEFAULT_TYPE_NAME);
            zonePartnersTypeInputVo.setZoneId(zoneId);
            insertZonePartnersType(zonePartnersTypeInputVo);
        }
        return zonePartnersType;
    }
}
