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.SysEmployee;
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.SysEmployeeMapper;
import org.dromara.system.service.ISysComplaintService;
import org.springframework.stereotype.Service;

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

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

    private final SysComplaintMapper baseMapper;
    private final SysEmployeeMapper employeeMapper;

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

    /**
     * 批量填充员工手机号
     */
    private void fillCustomerPhone(List<SysComplaintVo> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<Long> employeeIds = list.stream()
            .map(SysComplaintVo::getEmployeeId)
            .filter(id -> id != null)
            .distinct()
            .collect(Collectors.toList());
        if (employeeIds.isEmpty()) {
            return;
        }
        Map<Long, String> phoneMap = employeeMapper.selectList(
            Wrappers.lambdaQuery(SysEmployee.class)
                .select(SysEmployee::getId, SysEmployee::getPhone)
                .in(SysEmployee::getId, employeeIds)
        ).stream().collect(Collectors.toMap(SysEmployee::getId, SysEmployee::getPhone, (v1, v2) -> v2, HashMap::new));
        list.forEach(vo -> {
            if (vo.getEmployeeId() != null) {
                vo.setEmployeePhone(phoneMap.get(vo.getEmployeeId()));
            }
        });
    }

    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.getEmployeeName())) {
            List<Long> employeeIds = employeeMapper.selectList(
                Wrappers.lambdaQuery(SysEmployee.class)
                    .select(SysEmployee::getId)
                    .like(SysEmployee::getName, bo.getEmployeeName())
            ).stream().map(SysEmployee::getId).collect(Collectors.toList());
            if (employeeIds.isEmpty()) {
                employeeIds = List.of(0L);
            }
            lqw.in(SysComplaint::getEmployeeId, employeeIds);
        }
        lqw.orderByDesc(SysComplaint::getId);
        return lqw;
    }

    @Override
    public SysComplaintVo queryById(Long id) {
        SysComplaintVo vo = baseMapper.selectVoById(id);
        if (vo != null && vo.getEmployeeId() != null) {
            SysEmployee employee = employeeMapper.selectById(vo.getEmployeeId());
            if (employee != null) {
                vo.setEmployeePhone(employee.getPhone());
            }
        }
        return vo;
    }

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

    @Override
    public Boolean updateByBo(SysComplaintBo bo) {
        SysComplaint update = MapstructUtils.convert(bo, SysComplaint.class);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 分页查询当前员工的投诉建议列表（小程序端）
     * @Author: Trae
     */
    @Override
    public TableDataInfo<SysComplaintVo> queryMyPageList(Long employeeId, PageQuery pageQuery) {
        LambdaQueryWrapper<SysComplaint> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysComplaint::getEmployeeId, employeeId);
        lqw.orderByDesc(SysComplaint::getCreateTime);
        Page<SysComplaintVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

}
