package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.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 com.ruoyi.oa.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaExpressBo;
import com.ruoyi.oa.domain.vo.OaExpressVo;
import com.ruoyi.oa.domain.OaExpress;
import com.ruoyi.oa.mapper.OaExpressMapper;
import com.ruoyi.oa.service.IOaExpressService;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 物流预览Service业务层处理
 *
 * @author hdka
 * @date 2025-07-20
 */
@RequiredArgsConstructor
@Service
public class OaExpressServiceImpl implements IOaExpressService {

    private final OaExpressMapper baseMapper;

    /**
     * 查询物流预览
     */
    @Override
    public OaExpressVo queryById(Long expressId){
        return baseMapper.selectVoByIdPlus(expressId);
    }

    /**
     * 查询物流预览列表
     */
    @Override
    public TableDataInfo<OaExpressVo> queryPageList(OaExpressBo bo, PageQuery pageQuery) {
        QueryWrapper<OaExpress> lqw = buildQueryWrapperPlus(bo);
        Page<OaExpressVo> result = baseMapper.selectVoPagePlus(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询物流预览列表
     */
    @Override
    public List<OaExpressVo> queryList(OaExpressBo bo) {
        LambdaQueryWrapper<OaExpress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }
    private LambdaQueryWrapper<OaExpress> buildQueryWrapper(OaExpressBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaExpress> lqw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(bo.getExpressCode())) {
            lqw.like(OaExpress::getExpressCode, bo.getExpressCode());
        }
        if (bo.getStatus() != null) {
            lqw.eq(OaExpress::getStatus, bo.getStatus());
        }
        if (StringUtils.isNotBlank(bo.getSupplyName())) {
            lqw.like(OaExpress::getSupplyName, bo.getSupplyName());
        }
        if (StringUtils.isNotBlank(bo.getSupplyPhone())) {
            lqw.eq(OaExpress::getSupplyPhone, bo.getSupplyPhone());
        }
        if (bo.getOwnerId() != null) {
            lqw.eq(OaExpress::getOwnerId, bo.getOwnerId());
        }
        if (StringUtils.isNotBlank(bo.getOwnerPhone())) {
            lqw.eq(OaExpress::getOwnerPhone, bo.getOwnerPhone());
        }
        if (bo.getPlanDate() != null) {
            lqw.eq(OaExpress::getPlanDate, bo.getPlanDate());
        }
        if (bo.getProjectId() != null) {
            lqw.eq(OaExpress::getProjectId, bo.getProjectId());
        }
        if (StringUtils.isNotBlank(bo.getExpressType())) {
            lqw.eq(OaExpress::getExpressType, bo.getExpressType());
        }
        return lqw;
    }

    private QueryWrapper<OaExpress> buildQueryWrapperPlus(OaExpressBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<OaExpress> qw = new QueryWrapper<>();
        // 设置表别名
        if (StringUtils.isNotBlank(bo.getExpressCode())) {
            qw.like("oe.express_code", bo.getExpressCode());
        }
        if (bo.getStatus() != null) {
            qw.eq("oe.status", bo.getStatus());
        }
        if (StringUtils.isNotBlank(bo.getSupplyName())) {
            qw.like("oe.supply_name", bo.getSupplyName());
        }
        if (StringUtils.isNotBlank(bo.getSupplyPhone())) {
            qw.eq("oe.supply_phone", bo.getSupplyPhone());
        }
        if (bo.getOwnerId() != null) {
            qw.eq("oe.owner_id", bo.getOwnerId());
        }
        if (StringUtils.isNotBlank(bo.getOwnerPhone())) {
            qw.eq("oe.owner_phone", bo.getOwnerPhone());
        }
        if (bo.getPlanDate() != null) {
            qw.eq("oe.plan_date", bo.getPlanDate());
        }
        if (bo.getProjectId() != null) {
            qw.eq("oe.project_id", bo.getProjectId());
        }
        if (StringUtils.isNotBlank(bo.getExpressType())) {
            qw.eq("oe.express_type", bo.getExpressType());
        }
        // 添加逻辑删除条件
        qw.eq("oe.del_flag", 0);

        return qw;
    }


    /**
     * 新增物流预览
     */
    @Override
    public Boolean insertByBo(OaExpressBo bo) {
        OaExpress add = BeanUtil.toBean(bo, OaExpress.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExpressId(add.getExpressId());
        }
        return flag;
    }

    /**
     * 修改物流预览
     */
    @Override
    public Boolean updateByBo(OaExpressBo bo) {
        OaExpress update = BeanUtil.toBean(bo, OaExpress.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    /**
     * 获取所有需要刷新的快递ID（示例：所有类型为SF且状态为1的快递单）
     */
    public List<Long> getAllSfExpressIdsToRefresh() {
        LambdaQueryWrapper<OaExpress> lqw = Wrappers.lambdaQuery();
        lqw.eq(OaExpress::getExpressType, "SF");
        lqw.eq(OaExpress::getStatus, 1L);
        List<OaExpress> list = baseMapper.selectList(lqw);
        return list.stream().map(OaExpress::getExpressId).collect(Collectors.toList());
    }

    @Override
    public Boolean getRefreshExpress(List<Long> expressIds) throws IOException {
        System.out.println("12313123123");
        for (Long expressId : expressIds) {
            OaExpressVo oaExpressVo = baseMapper.selectVoById(expressId);
            String expressType = oaExpressVo.getExpressType();
            System.out.println(expressType);
            if (expressType.equals("SF") && oaExpressVo.getStatus() ==1L) {

                // 校验为顺丰则进入此位置更新状态
                String result = SfRouteQueryUtil.queryRoute(oaExpressVo.getExpressCode(), oaExpressVo.getOwnerPhone() != null ? oaExpressVo.getOwnerPhone() : oaExpressVo.getSupplyPhone());
                OaExpressVo oaExpressVo1 = SfRouteQueryUtil.parseData(result);
                if (oaExpressVo1 != null) {
                    oaExpressVo.setLastUpdateTime(oaExpressVo1.getAcceptTime());
                    oaExpressVo.setLastStatus(oaExpressVo1.getFirstStatusName());
                }
            }
            if (expressType.equals("ZTO") && oaExpressVo.getStatus() ==1L) {
                // 校验为顺丰则进入此位置更新状态
                OaExpressVo oaExpressVo1 = ZtoTrackQueryUtil.queryTrack(oaExpressVo.getExpressCode(), oaExpressVo.getOwnerPhone() != null ? oaExpressVo.getOwnerPhone() : oaExpressVo.getSupplyPhone());
                if (oaExpressVo1 != null) {
                    oaExpressVo.setLastUpdateTime(oaExpressVo1.getAcceptTime());
                    oaExpressVo.setLastStatus(oaExpressVo1.getFirstStatusName());
                }
            }
            if (expressType.equals("Best") && oaExpressVo.getStatus() ==1L) {
                // 校验为顺丰则进入此位置更新状态
                OaExpressVo oaExpressVo1 = BestRouteQueryUtil.queryRoute(oaExpressVo.getExpressCode());

                if (oaExpressVo1 != null) {
                    oaExpressVo.setLastUpdateTime(oaExpressVo1.getAcceptTime());
                    oaExpressVo.setLastStatus(oaExpressVo1.getFirstStatusName());
                }
            }
            if (expressType.equals("YD") && oaExpressVo.getStatus() == 1L) {
                // 韵达快递轨迹查询
                String result = com.ruoyi.oa.utils.YdRouteQueryUtil.queryRoute(oaExpressVo.getExpressCode());
                OaExpressVo ydVo = YdRouteQueryUtil.parseData(result);
                if (ydVo != null) {
                    oaExpressVo.setLastUpdateTime(ydVo.getLastUpdateTime());
                    oaExpressVo.setLastStatus(ydVo.getLastStatus());
                }
            }
            if (expressType.equals("YT") && oaExpressVo.getStatus() == 1L) {
                // 圆通快递轨迹查询
                String result = com.ruoyi.oa.utils.YtRouteQueryUtil.queryRoute(oaExpressVo.getExpressCode());
                OaExpressVo ytVo = YtRouteQueryUtil.parseData(result);
                if (ytVo != null) {
                    oaExpressVo.setLastUpdateTime(ytVo.getLastUpdateTime());
                    oaExpressVo.setLastStatus(ytVo.getLastStatus());
                }
            }
            if (expressType.equals("STO") && oaExpressVo.getStatus() == 1L) {
                // 申通快递轨迹查询
                String result = StoRouteQueryUtil.queryRoute(Collections.singletonList(oaExpressVo.getExpressCode()));
                OaExpressVo stoVo = StoRouteQueryUtil.parseData(result);
                if (stoVo != null) {
                    oaExpressVo.setLastUpdateTime(stoVo.getAcceptTime());
                    oaExpressVo.setLastStatus(stoVo.getFirstStatusName());
                }
            }
            if (expressType.equals("SXJD") && oaExpressVo.getStatus() == 1L) {
                // 顺心捷达快递轨迹查询
                String result = SxjdRouteQueryUtil.queryRoute(oaExpressVo.getExpressCode());
                OaExpressVo sxjdVo = SxjdRouteQueryUtil.parseData(result);
                if (sxjdVo != null) {
                    oaExpressVo.setLastUpdateTime(sxjdVo.getLastUpdateTime());
                    oaExpressVo.setLastStatus(sxjdVo.getLastStatus());
                }
            }
            OaExpress add = BeanUtil.toBean(oaExpressVo, OaExpress.class);
            baseMapper.updateById(add);;
        }
        return  true;
    }
}
