package org.dromara.system.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
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.system.domain.TblCarSchedule;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.TblGoodsOrderBo;
import org.dromara.system.domain.vo.TblGoodsOrderVo;
import org.dromara.system.domain.TblGoodsOrder;
import org.dromara.system.mapper.TblGoodsOrderMapper;
import org.dromara.system.service.ITblGoodsOrderService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 寄货订单Service业务层处理
 *
 * @author Lion Li
 * @date 2024-04-01
 */
@RequiredArgsConstructor
@Service
public class TblGoodsOrderServiceImpl implements ITblGoodsOrderService {

    private final TblGoodsOrderMapper baseMapper;

    /**
     * 查询寄货订单
     */
    @Override
    public TblGoodsOrderVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询寄货订单列表
     */
    @Override
    public TableDataInfo<TblGoodsOrderVo> queryPageList(TblGoodsOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TblGoodsOrder> lqw = buildQueryWrapper(bo);
        Page<TblGoodsOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询寄货订单列表
     */
    @Override
    public List<TblGoodsOrderVo> queryList(TblGoodsOrderBo bo) {
        LambdaQueryWrapper<TblGoodsOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TblGoodsOrder> buildQueryWrapper(TblGoodsOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TblGoodsOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderId()), TblGoodsOrder::getOrderId, bo.getOrderId());
        lqw.eq(bo.getFromUserId() != null, TblGoodsOrder::getFromUserId, bo.getFromUserId());
        lqw.eq(bo.getGoodsType() != null, TblGoodsOrder::getGoodsType, bo.getGoodsType());
        lqw.eq(bo.getStatus() != null, TblGoodsOrder::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getFromAddr()), TblGoodsOrder::getFromAddr, bo.getFromAddr());
//        lqw.eq(bo.getGotime() != null, TblGoodsOrder::getGotime, bo.getGotime());

        if(bo.getGotime() != null){
            String start= DateUtils.dateTime(bo.getGotime()) +" 00:00:00";
            String end= DateUtils.dateTime(bo.getGotime())+" 23:59:59";
            lqw.gt(bo.getGotime()!=null, TblGoodsOrder::getGotime, start);
            lqw.lt(bo.getGotime()!=null, TblGoodsOrder::getGotime, end);
        }




        lqw.eq(StringUtils.isNotBlank(bo.getGoodsWeight()), TblGoodsOrder::getGoodsWeight, bo.getGoodsWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getToAddr()), TblGoodsOrder::getToAddr, bo.getToAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), TblGoodsOrder::getPayType, bo.getPayType());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsDes()), TblGoodsOrder::getGoodsDes, bo.getGoodsDes());
//        lqw.eq(StringUtils.isNotBlank(bo.getExt1()), TblGoodsOrder::getExt1, bo.getExt1());
//        lqw.eq(StringUtils.isNotBlank(bo.getExt2()), TblGoodsOrder::getExt2, bo.getExt2());


        if(bo.getParams() != null&& bo.getParams().size()>0){
            if(bo.getParams().get("scheduleId")!=null){
                String datasql = (JSONUtil.toJsonStr(bo.getParams().get("scheduleId").toString().split(","))).replaceAll("\"","'");
                datasql = datasql.replaceAll("\\[","(");
                datasql = datasql.replaceAll("]",")");
                lqw.apply(StringUtils.format(" ext1->'$.schedule_id' in {}", datasql));

            }

            if(bo.getParams().get("start")!=null&&bo.getParams().get("end")!=null){
                String start= bo.getParams().get("start").toString();
                String end= bo.getParams().get("end").toString();
                lqw.gt( TblGoodsOrder::getCreateTime, start);
                lqw.lt( TblGoodsOrder::getCreateTime, end);
            }
            if(bo.getParams().get("phone")!=null){
                String datasql = "( select user_id from sys_user where phonenumber like '%"+bo.getParams().get("phone").toString()+"%')";
                lqw.apply(StringUtils.format(" from_user_id in {}", datasql));
            }
            if(bo.getParams().get("username")!=null){
                String datasql = "( select user_id from sys_user where nick_name like '%"+bo.getParams().get("username").toString()+"%')";
                lqw.apply(StringUtils.format(" from_user_id in {}", datasql));
            }
        }
        return lqw;
    }

    /**
     * 新增寄货订单
     */
    @Override
    public Boolean insertByBo(TblGoodsOrderBo bo) {
        TblGoodsOrder add = MapstructUtils.convert(bo, TblGoodsOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改寄货订单
     */
    @Override
    public Boolean updateByBo(TblGoodsOrderBo bo) {
        TblGoodsOrder update = MapstructUtils.convert(bo, TblGoodsOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 批量删除寄货订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Map<String, Object> queryByDate(Map<String, Object> bo) {
        return baseMapper.selectdatabydate(bo);
    }
}
