package org.dromara.zhishu.service.impl;

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.dromara.zhishu.domain.ExcelTask;
import org.dromara.zhishu.domain.Printer;
import org.dromara.zhishu.domain.TLogistics;
import org.dromara.zhishu.domain.bo.TLogisticsBo;
import org.dromara.zhishu.domain.vo.ExcelTaskVo;
import org.dromara.zhishu.domain.vo.TDepotVo;
import org.dromara.zhishu.domain.vo.TLogisticsVo;
import org.dromara.zhishu.mapper.TLogisticsMapper;
import org.dromara.zhishu.service.IFastMailService;
import org.dromara.zhishu.service.ITLogisticsService;
import org.springframework.stereotype.Service;


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

/**
 * 物流管理Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-22
 */
@RequiredArgsConstructor
@Service
public class TLogisticsServiceImpl implements ITLogisticsService {

    private final TLogisticsMapper baseMapper;

    /**
     * 查询物流管理
     *
     * @param id 主键
     * @return 物流管理
     */
    @Override
    public TLogisticsVo queryById(Long id){
        TLogisticsVo vo = baseMapper.selectByLId(id);
        return vo;
    }

    /**
     * 分页查询物流管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 物流管理分页列表
     */
    @Override
    public TableDataInfo<TLogisticsVo> queryPageList(TLogisticsBo bo, PageQuery pageQuery) {
        Long userId;
        if (bo.getUserId() != null){
            userId = bo.getUserId();
        }else{
            userId = LoginHelper.getUserId();
        }

        bo.setUserId(userId);
        LambdaQueryWrapper<TLogistics> lqw = buildQueryWrapper(bo);
        // 物流类型转换
        if(bo.getShipping()!=null){
            if(bo.getShipping().equals("物流")){
                bo.setShipping("1");
            }else if(bo.getShipping().equals("快递")){
                bo.setShipping("0");
            }
        }
        Page<TLogisticsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的物流管理列表
     *
     * @param bo 查询条件
     * @return 物流管理列表
     */
    @Override
    public List<TLogisticsVo> queryList(TLogisticsBo bo) {
        // 获取当前用户id
        Long userId;
        if (bo.getUserId() != null){
            userId = bo.getUserId();
        }else{
            userId = LoginHelper.getUserId();
        }
        // 获取白名单
        if (userId != 1) {
            bo.setCreateBy(userId);
        }

        LambdaQueryWrapper<TLogistics> lqw = buildQueryWrapper(bo);
        List<TLogisticsVo> vo=baseMapper.selectVoList(lqw);
        for (int i = 0; i < vo.size(); i++) {
            Long depotId = vo.get(i).getWarehouseId();
            if (depotId != null) {
                TDepotVo vo1=  baseMapper.selectDepotName(depotId);
                vo.get(i).setWarehouseName(vo1.getName()+vo1.getUnit());
            }
        }
        return vo;
    }

    private LambdaQueryWrapper<TLogistics> buildQueryWrapper(TLogisticsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TLogistics> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TLogistics::getId);
//        管理员可以查看所有信息
//        if (bo.getUserId()  != null && !Long.valueOf(1).equals(bo.getUserId()))  {
//            lqw.eq(TLogistics::getCreateBy,  bo.getUserId());
//        }
        lqw.eq(bo.getCreateBy() != null, TLogistics::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getUserId()!=null, TLogistics::getCreateBy, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), TLogistics::getTemplateName, bo.getTemplateName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryProvince()), TLogistics::getDeliveryProvince, bo.getDeliveryProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryCity()), TLogistics::getDeliveryCity, bo.getDeliveryCity());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryArea()), TLogistics::getDeliveryArea, bo.getDeliveryArea());
        lqw.eq(StringUtils.isNotBlank(bo.getShippingRange()), TLogistics::getShippingRange, bo.getShippingRange());
        lqw.eq(bo.getWarehouseId() != null, TLogistics::getWarehouseId, bo.getWarehouseId());
        return lqw;
    }

    /**
     * 新增物流管理
     *
     * @param bo 物流管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TLogisticsBo bo) {
        TLogistics add = MapstructUtils.convert(bo, TLogistics.class);
        validEntityBeforeSave(add);
        String are = baseMapper.selectByArea(bo.getDeliveryArea(), bo.getDeliveryCity());
        String city = baseMapper.selectByCity(bo.getDeliveryCity(), bo.getDeliveryProvince());
        String province = baseMapper.selectByProvince(bo.getDeliveryProvince());
        add.setDeliveryProvince(province);
        add.setDeliveryCity(city);
        add.setDeliveryArea(are);
        if (city == null) {
            add.setDeliveryAddress(province + "/" + are);
        } else {
            add.setDeliveryAddress(province + "/" + city + "/" + are);
        }
        add.setStatus("1");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
        }
        return flag;
    }

    /**
     * 修改物流管理
     *
     * @param bo 物流管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TLogisticsBo bo) {
        TLogistics update = MapstructUtils.convert(bo, TLogistics.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public List<TLogisticsVo> queryNameList() {
        //获取当前用户id
        Long userId = LoginHelper.getUserId();
        //通过userid查询所有仓库id
//        List<Long> depotIds = baseMapper.selectDepotId(userId);
        List<TLogisticsVo>  list = baseMapper.selectUserId(userId);
//        List<TLogisticsVo> list=new ArrayList<>();
//        if(depotIds.isEmpty()){
//            return list;
//        }else{
//            list= baseMapper.nameList(depotIds);
//        }
        return list;
    }

    @Override
    public  List<TLogisticsVo> getList(Long userId){
        return baseMapper.selectUserId(userId);
    }

    @Override
    public List<TLogisticsVo> queryNameListByXcx(Long userId) {
        return baseMapper.selectUserId(userId);
    }
}
