package org.dromara.zhishu.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.FilterSetBo;
import org.dromara.zhishu.domain.vo.FilterSetVo;
import org.dromara.zhishu.domain.FilterSet;
import org.dromara.zhishu.mapper.FilterSetMapper;
import org.dromara.zhishu.service.IFilterSetService;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 过滤设置Service业务层处理
 *
 * @author yxy
 * @date 2025-04-14
 */
@RequiredArgsConstructor
@Service
public class FilterSetServiceImpl implements IFilterSetService {

    private final FilterSetMapper baseMapper;

    /**
     * 查询过滤设置
     *
     * @param id 主键
     * @return 过滤设置
     */
    @DS("taskSlave")
    @Override
    public FilterSetVo queryById(Long id){
        FilterSetVo vo = baseMapper.selectVoById(id);
        return vo;
    }

    /**
     * 分页查询过滤设置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 过滤设置分页列表
     */
    @DS("taskSlave")
    @Override
    public TableDataInfo<FilterSetVo> queryPageList(FilterSetBo bo, PageQuery pageQuery) {

        // 获取当前用户id
        Long userId = LoginHelper.getUserId();
        bo.setCreateBy(userId);
//        if (userId != 1) {
//            bo.setCreateBy(userId);
//        }

        LambdaQueryWrapper<FilterSet> lqw = buildQueryWrapper(bo);
        Page<FilterSetVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @DS("taskSlave")
    @Override
    public List<FilterSetVo> selectVoListByBo(FilterSetBo bo) {
        // 获取当前用户id
        Long userId = LoginHelper.getUserId() == null ? 1L : LoginHelper.getUserId();
        bo.setCreateBy(userId);
        return baseMapper.selectVoListByBo(bo);
    }

    @DS("taskSlave")
    @Override
    public int deleteTrueById(Long id){
        return baseMapper.deleteTrueById(id);
    }

    /**
     * 查询符合条件的过滤设置列表
     *
     * @param bo 查询条件
     * @return 过滤设置列表
     */
    @DS("taskSlave")
    @Override
    public List<FilterSetVo> queryList(FilterSetBo bo) {
        // 获取当前用户id
        Long userId = LoginHelper.getUserId();
        if (userId != 1) {
            bo.setCreateBy(userId);
        }
        LambdaQueryWrapper<FilterSet> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FilterSet> buildQueryWrapper(FilterSetBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FilterSet> lqw = Wrappers.lambdaQuery();
//        lqw.orderByAsc(FilterSet::getId);
        lqw.orderByDesc(FilterSet::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getFilterType()), FilterSet::getFilterType, bo.getFilterType());
        lqw.eq(StringUtils.isNotBlank(bo.getLimitationType()), FilterSet::getLimitationType, bo.getLimitationType());
        lqw.eq(StringUtils.isNotBlank(bo.getAddWay()), FilterSet::getAddWay, bo.getAddWay());
        lqw.like(StringUtils.isNotBlank(bo.getAddTxt()), FilterSet::getAddTxt, bo.getAddTxt());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), FilterSet::getStatus, bo.getStatus());
        // 处理 sort 条件
        if (StringUtils.isNotEmpty(bo.getSort())) {
            String[] sortArray = bo.getSort().split(",");
            List<String> sortList = Arrays.stream(sortArray)
                    .filter(StringUtils::isNotEmpty)
                    .map(String::trim)
                    .collect(Collectors.toList());

            // 使用 FIND_IN_SET，更稳定
            for (String sortValue : sortList) {
                lqw.apply("FIND_IN_SET({0}, sort) > 0", sortValue);
            }
        }



        lqw.eq(bo.getCreateBy() != null, FilterSet::getCreateBy, bo.getCreateBy());
        return lqw;
    }

    /**
     * 新增过滤设置
     *
     * @param bo 过滤设置
     * @return 是否新增成功
     */
    @DS("taskSlave")
    @Override
    public Boolean insertByBo(FilterSetBo bo) {
        Long userId = LoginHelper.getUserId() == null ? 1L : LoginHelper.getUserId();

        bo.setCreateBy(userId);
        bo.setCreateTime(DateUtils.getNowDate());
        bo.setUpdateBy(userId);
        bo.setUpdateTime(DateUtils.getNowDate());

        FilterSet add = MapstructUtils.convert(bo, FilterSet.class);
        add.setSort(bo.getSort());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改过滤设置
     *
     * @param bo 过滤设置
     * @return 是否修改成功
     */
    @DS("taskSlave")
    @Override
    public Boolean updateByBo(FilterSetBo bo) {
        FilterSet update = MapstructUtils.convert(bo, FilterSet.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FilterSet entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除过滤设置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @DS("taskSlave")
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long id : ids){
            baseMapper.deleteTrueById(id);
        }
        return true;
    }
}
