package com.ruoyi.info.quicklink.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.quicklink.domain.QuickLink;
import com.ruoyi.info.quicklink.domain.bo.QuickLinkBo;
import com.ruoyi.info.quicklink.domain.vo.QuickLinkVo;
import com.ruoyi.info.quicklink.enums.ResourceModel;
import com.ruoyi.info.quicklink.exception.QuiclLinkExceptionEnum;
import com.ruoyi.info.quicklink.mapper.QuickLinkMapper;
import com.ruoyi.info.quicklink.service.IQuickLinkService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 金刚区Service业务层处理
 *
 * @author wuchao
 * @date 2023-12-20
 */
@RequiredArgsConstructor
@Service
public class QuickLinkServiceImpl implements IQuickLinkService {

    private final QuickLinkMapper baseMapper;

    /**
     * 查询金刚区分页
     *
     * @param bo 金刚区
     * @return 金刚区
     */
    @Override
    public TableDataInfo<QuickLinkVo> queryPageList(QuickLinkBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<QuickLink> lqw = buildQueryWrapper(bo);
        Page<QuickLinkVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询金刚区列表
     *
     * @param bo 金刚区
     * @return 金刚区
     */
    @Override
    public List<QuickLinkVo> queryList(QuickLinkBo bo) {
        LambdaQueryWrapper<QuickLink> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<QuickLink> buildQueryWrapper(QuickLinkBo bo) {
        LambdaQueryWrapper<QuickLink> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), QuickLink::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getIcon()), QuickLink::getIcon, bo.getIcon());
        lqw.eq(ObjectUtil.isNotNull(bo.getSequence()), QuickLink::getSequence, bo.getSequence());
        lqw.eq(ObjectUtil.isNotNull(bo.getLocationCode()), QuickLink::getLocationCode, bo.getLocationCode());
        lqw.eq(ObjectUtil.isNotNull(bo.getStatus()), QuickLink::getStatus, bo.getStatus());
        lqw.ge(ObjectUtil.isNotNull(bo.getCreateTimeStart()), QuickLink::getCreateTime, bo.getCreateTimeStart());
        lqw.le(ObjectUtil.isNotNull(bo.getCreateTimeEnd()), QuickLink::getCreateTime, bo.getCreateTimeEnd());

        lqw.orderByAsc(QuickLink::getSequence);
        lqw.orderByDesc(QuickLink::getCreateTime);
        return lqw;
    }

    @Override
    public List<QuickLinkVo> queryListForApi(String locationCode) {
        List<QuickLinkVo> list = this.baseMapper.selectVoList(new LambdaQueryWrapper<QuickLink>()
            .eq(QuickLink::getLocationCode, locationCode)
            .eq(QuickLink::getStatus, true)
            .orderByAsc(QuickLink::getSequence)
            .orderByDesc(QuickLink::getCreateTime)
        );
        return list;
    }

    /**
     * 查询金刚区
     *
     * @param id 金刚区主键
     * @return 金刚区
     */
    @Override
    public QuickLinkVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 详情金刚区
     *
     * @param id 金刚区主键
     * @return 金刚区
     */
    @Override
    public QuickLink loadById(Long id, Boolean tw) {
        QuickLink info = this.baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(info) && tw) {
            throw new ServiceException("金刚区不存在");
        }
        return info;
    }

    /**
     * 新增金刚区
     *
     * @param bo 金刚区
     * @return 结果
     */
    @Override
    public Boolean insertByBo(QuickLinkBo bo) {
        QuickLink add = BeanUtil.toBean(bo, QuickLink.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改金刚区
     *
     * @param bo 金刚区
     * @return 结果
     */
    @Override
    public Boolean updateByBo(QuickLinkBo bo) {
        QuickLink quickLink = this.loadById(bo.getId(), true);
        QuickLink update = BeanCopyUtils.copy(bo, quickLink);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(QuickLink entity) {
        //TODO 做一些数据校验,如唯一约束
        switch (entity.getJumpType()) {
            case OUTER:
                entity.setInnerPageCode(null);
                entity.setResourceModel(ResourceModel.NO);
                entity.setResourceModelId(null);
                entity.setResourceModelTitle(null);

                if (StringUtils.isEmpty(entity.getOutsideAddress())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.OUTER_ADDRESS_EMPTY);
                }
                break;
            case INNER:
                entity.setOutsideAddress(null);
                entity.setResourceModel(ResourceModel.NO);
                entity.setResourceModelId(null);
                entity.setResourceModelTitle(null);

                if (StringUtils.isEmpty(entity.getInnerPageCode())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.INNER_PAGE_CODE_EMPTY);
                }
                break;
            case INNER_RESOURCE:
                entity.setInnerPageCode(null);
                entity.setOutsideAddress(null);

                if (ObjectUtil.isNull(entity.getResourceModel())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_EMPTY);
                }
                if (ObjectUtil.isNull(entity.getResourceModelId())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_ID_EMPTY);
                }
                if (ObjectUtil.isNull(entity.getResourceModelTitle())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_TITLE_EMPTY);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 批量删除金刚区
     *
     * @param ids 需要删除的金刚区主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long id) {
        QuickLink quickLink = this.loadById(id, true);
        this.baseMapper.update(null, new LambdaUpdateWrapper<QuickLink>()
                .eq(QuickLink::getId, quickLink.getId())
                .set(QuickLink::getStatus, !quickLink.getStatus())
        );
    }

}
