package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
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 lombok.extern.slf4j.Slf4j;
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.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.web.domain.FoodIngredientStock;
import org.dromara.web.domain.bo.FoodIngredientStockBo;
import org.dromara.web.domain.vo.FoodIngredientStockVo;
import org.dromara.web.domain.vo.FoodStockBalanceVo;
import org.dromara.web.mapper.FoodIngredientStockMapper;
import org.dromara.web.service.IFoodIngredientStockService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 食材出入库Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FoodIngredientStockServiceImpl implements IFoodIngredientStockService {

    private final FoodIngredientStockMapper baseMapper;

    private final SysUserMapper userMapper;

    /**
     * 查询食材出入库
     *
     * @param id 主键
     * @return 食材出入库
     */
    @Override
    public FoodIngredientStockVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询食材出入库列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 食材出入库分页列表
     */
    @Override
    public TableDataInfo<FoodIngredientStockVo> queryPageList(FoodIngredientStockBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FoodIngredientStock> lqw = buildQueryWrapper(bo);
        Page<FoodIngredientStockVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<FoodIngredientStockVo> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            Set<Long> userList = CollUtil.newHashSet();
            records.forEach(v->{
                userList.add(v.getCreateBy());
            });
            Map<Long, String> userMap = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class)
                .select(SysUser::getUserId, SysUser::getUserName)
                .in(SysUser::getUserId, userList)).stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> k2.getUserName(), (k1, k2) -> k1));
            records.forEach(v->{
               v.setCreateByName(userMap.get(v.getCreateBy()));
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的食材出入库列表
     *
     * @param bo 查询条件
     * @return 食材出入库列表
     */
    @Override
    public List<FoodIngredientStockVo> queryList(FoodIngredientStockBo bo) {
        LambdaQueryWrapper<FoodIngredientStock> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FoodIngredientStock> buildQueryWrapper(FoodIngredientStockBo bo) {
        Map<String, Object> params = bo.getParams();
        List<Date> dateList = bo.getDateRange();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = null;
        String endTime = null;

        if (dateList != null && dateList.size() == 2) {
            startTime = sdf.format(dateList.get(0)) + " 00:00:00";  // 开始时间
            endTime = sdf.format(dateList.get(1)) + " 23:59:59";    // 结束时间
        }
        LambdaQueryWrapper<FoodIngredientStock> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(FoodIngredientStock::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getType()), FoodIngredientStock::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitType()), FoodIngredientStock::getVisitType, bo.getVisitType());
        if (StringUtils.isNotBlank(bo.getSearchValue())) {
            lqw.and(wrapper -> wrapper.like(FoodIngredientStock::getFoodName, bo.getSearchValue()).or().like(FoodIngredientStock::getInvoiceNumber, bo.getSearchValue()));
        }
        if (bo.getMainClass()!=null) {
            lqw.and(wrapper -> wrapper.eq(FoodIngredientStock::getMainClass, bo.getMainClass()).or().eq(FoodIngredientStock::getSubClass, bo.getMainClass()));
        }
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            lqw.between(FoodIngredientStock::getCreateTime, startTime, endTime);
        }
        return lqw;
    }

    /**
     * 新增食材出入库
     *
     * @param boList 食材出入库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(List<FoodIngredientStockBo> boList) {
        boolean flag =false;
        if (CollUtil.isNotEmpty(boList)) {
            FoodIngredientStockBo bo=null;
            for (int i = 0; i < boList.size(); i++) {
                bo = boList.get(i);
                FoodIngredientStock add = MapstructUtils.convert(bo, FoodIngredientStock.class);
                validEntityBeforeSave(add);
                 flag = baseMapper.insert(add) > 0;
                if (flag) {
                    bo.setId(add.getId());
                }

            }

        }
        return flag;
    }

    /**
     * 修改食材出入库
     *
     * @param bo 食材出入库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(FoodIngredientStockBo bo) {
        FoodIngredientStock update = MapstructUtils.convert(bo, FoodIngredientStock.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public TableDataInfo<FoodStockBalanceVo> queryStockBalancePage(FoodIngredientStockBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();

        // 计算正确的offset
        int offset = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        Integer count = baseMapper.queryStockBalanceCount(bo.getMainClass(), bo.getSearchValue());
        List<FoodStockBalanceVo> balanceVoList = baseMapper.queryStockBalance(bo.getMainClass(), bo.getSearchValue(), offset, pageQuery.getPageSize());
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(balanceVoList);
        tableDataInfo.setTotal(count);
        return tableDataInfo;
    }

    @Override
    public TableDataInfo<FoodStockBalanceVo> queryStockBalance(FoodIngredientStockBo bo ) {
        Map<String, Object> params = bo.getParams();

        Integer count = baseMapper.queryStockBalanceCount(bo.getMainClass(), bo.getSearchValue());
        List<FoodStockBalanceVo> balanceVoList = baseMapper.queryStockBalance(bo.getMainClass(), bo.getSearchValue(), null,null);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(balanceVoList);
        tableDataInfo.setTotal(count);
        return tableDataInfo;
    }

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

    /**
     * 校验并批量删除食材出入库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
