package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysComplaint;
import org.dromara.system.domain.SysCustomer;
import org.dromara.system.domain.bo.SysComplaintBo;
import org.dromara.system.domain.vo.SysComplaintVo;
import org.dromara.system.mapper.SysComplaintMapper;
import org.dromara.system.mapper.SysCustomerMapper;
import org.dromara.system.service.ISysComplaintService;
import org.springframework.stereotype.Service;

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

/**
 * 投诉建议 Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class SysComplaintServiceImpl implements ISysComplaintService {

    private final SysComplaintMapper baseMapper;
    private final SysCustomerMapper customerMapper;

    @Override
    public TableDataInfo<SysComplaintVo> queryPageList(SysComplaintBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysComplaint> lqw = buildQueryWrapper(bo);
        Page<SysComplaintVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysComplaint> buildQueryWrapper(SysComplaintBo bo) {
        LambdaQueryWrapper<SysComplaint> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getFeedbackType()), SysComplaint::getFeedbackType, bo.getFeedbackType());
        if (StringUtils.isNotBlank(bo.getCustomerName())) {
            List<Long> customerIds = customerMapper.selectList(
                Wrappers.lambdaQuery(SysCustomer.class)
                    .select(SysCustomer::getId)
                    .like(SysCustomer::getUserName, bo.getCustomerName())
            ).stream().map(SysCustomer::getId).collect(Collectors.toList());
            if (customerIds.isEmpty()) {
                customerIds = List.of(0L);
            }
            lqw.in(SysComplaint::getCustomerId, customerIds);
        }
        lqw.orderByDesc(SysComplaint::getId);
        return lqw;
    }

    @Override
    public Boolean insertByBo(SysComplaintBo bo) {
        SysComplaint add = MapstructUtils.convert(bo, SysComplaint.class);
        return baseMapper.insert(add) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteByIds(ids) > 0;
    }

}
