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.PageUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.datascope.annotation.DataScope;
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.ZonePartnersOverviewVo;
import com.microservices.zone.partners.domain.vo.ZonePartnersUpdateVo;
import com.microservices.zone.partners.mapper.ZonePartnersMapper;
import com.microservices.zone.partners.service.IZonePartnersService;
import com.microservices.zone.partners.service.IZonePartnersTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 特色专区合作伙伴Service业务层处理
 *
 * @author otto
 * @date 2023-06-07
 */
@Service
public class ZonePartnersServiceImpl implements IZonePartnersService {
    private static final Logger logger = LoggerFactory.getLogger(ZonePartnersServiceImpl.class);
    @Autowired
    private ZonePartnersMapper zonePartnersMapper;
    @Autowired
    private IZoneDetailService zoneDetailService;
    @Autowired
    private IZonePartnersTypeService zonePartnersTypeService;

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

    /**
     * 查询特色专区合作伙伴列表
     *
     * @param zonePartners 特色专区合作伙伴
     * @return 特色专区合作伙伴
     */
    @Override
    @DataScope(deptAlias = "zp")
    public GenericsTableDataInfo<ZonePartners> selectZonePartnersList(ZonePartners zonePartnersSearch) {
        List<ZonePartners> zonePartnersList = zonePartnersMapper.selectZonePartnersList(zonePartnersSearch);
        for (ZonePartners zonePartners : zonePartnersList) {
            if (zonePartners.getTypeId() == null) {
                ZonePartnersType defaultZonePartnersType = zonePartnersTypeService.selectDefaultZonePartnersType(zonePartners.getZoneId());
                zonePartners.setTypeId(defaultZonePartnersType.getId());
                zonePartnersMapper.updateZonePartners(zonePartners);
            }
        }
        return PageUtils.toPage(zonePartnersList);
    }


    /**
     * 新增特色专区合作伙伴
     * 
     * @param zonePartners 特色专区合作伙伴
     * @return 结果
     */
    @Override
    public int insertZonePartners(ZonePartners zonePartners) {
        ZoneDetail zoneDetail = zoneDetailService.selectZoneDetailById(zonePartners.getZoneId());
        zonePartners.setDeptId(zoneDetail.getDeptId());
        zonePartners.setCreateTime(DateUtils.getNowDate());
        if (zonePartners.getTypeId() == null) {
            ZonePartnersType defaultZonePartnersType = zonePartnersTypeService.selectDefaultZonePartnersType(zonePartners.getZoneId());
            zonePartners.setTypeId(defaultZonePartnersType.getId());
        } else {
            zonePartnersTypeService.selectZonePartnersTypeById(zonePartners.getTypeId());
        }
        //设置排序值为当前最大的排序值+1
        Integer maxSort = zonePartnersMapper.selectMaxSortByZoneId(zonePartners);
        if (maxSort == null) {
            maxSort = 1;
        } else {
            maxSort++;
        }
        zonePartners.setSort(maxSort);
        return zonePartnersMapper.insertZonePartners(zonePartners);
    }

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

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

    /**
     * 修改特色专区合作伙伴
     *
     * @param zonePartnersUpdateVo 特色专区合作伙伴
     * @return 结果
     */
    @Override
    public int updateZonePartners(ZonePartnersUpdateVo zonePartnersUpdateVo) {
        ZonePartners oldZonePartners = selectZonePartnersById(zonePartnersUpdateVo.getId());
        ZonePartners zonePartners = zonePartnersUpdateVo.toZonePartners();
        zonePartners.setUpdateTime(DateUtils.getNowDate());
        if (zonePartnersUpdateVo.getTypeId() == null) {
            ZonePartnersType defaultZonePartnersType = zonePartnersTypeService.selectDefaultZonePartnersType(oldZonePartners.getZoneId());
            zonePartnersUpdateVo.setTypeId(defaultZonePartnersType.getId());
        }
        if (zonePartnersUpdateVo.getOrder() != null) {
            Integer setSort = setSortByOrder(oldZonePartners, zonePartnersUpdateVo.getOrder());
            zonePartners.setSort(setSort);
        }
        return zonePartnersMapper.updateZonePartners(zonePartners);
    }

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

    /**
     * 删除特色专区合作伙伴信息
     *
     * @param id 特色专区合作伙伴主键
     * @return 结果
     */
    @Override
    public int deleteZonePartnersById(Long id) {
        selectZonePartnersById(id);
        return zonePartnersMapper.deleteZonePartnersById(id);
    }

    @Override
    @DataScope(deptAlias = "zp")
    public Integer selectZonePartnersCount(ZonePartners zonePartners) {
        return zonePartnersMapper.selectZonePartnersCount(zonePartners);
    }

    @Override
    public List<ZonePartnersOverviewVo> selectZonePartnersOverviewList(Long zoneId) {
        List<ZonePartnersOverviewVo> zonePartnersOverviewVoList = new ArrayList<>();
        ZonePartnersType zonePartnersTypeSearch = new ZonePartnersType();
        zonePartnersTypeSearch.setZoneId(zoneId);
        List<ZonePartnersType> zonePartnersTypeList = zonePartnersTypeService.selectZonePartnersTypeList(zonePartnersTypeSearch);
        for (ZonePartnersType zonePartnersType : zonePartnersTypeList) {
            ZonePartnersOverviewVo zonePartnersOverviewVo = zonePartnersType.toZonePartnersOverviewVo();
            ZonePartners zonePartnersSearch = new ZonePartners();
            zonePartnersSearch.setZoneId(zoneId);
            zonePartnersSearch.setTypeId(zonePartnersType.getId());
            List<ZonePartners> zonePartnersList = zonePartnersMapper.selectZonePartnersList(zonePartnersSearch);
            zonePartnersOverviewVo.setZonePartnersList(zonePartnersList);
            zonePartnersOverviewVoList.add(zonePartnersOverviewVo);
        }

        return zonePartnersOverviewVoList;
    }
}
