package bus.service.impl;

import bus.model.SnowflakeUtil;
import bus.model.dto.BBusInfoDto;
import bus.model.dto.BBusTrackInfoDto;
import bus.model.dto.BBusTrackTreeDto;
import bus.model.dto.page.BBusInfoPageDto;
import bus.model.vo.BBusInfoVo;
import bus.model.po.BBusInfoPo;
import bus.mapper.BBusInfoMapper;

import bus.service.BBusInfoService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orcas.common.sso.model.ExtInfo;
import com.orcas.iso.config.common.user.CurrentUserHolder;
import com.qzwisdom.qzframework.core.tool.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Program: bus
 * @Description: 描述
 * @Author: zy
 * @Date: 2025-03-01 09:44:24
 **/
@Service
public class BBusInfoServiceImpl extends ServiceImpl<BBusInfoMapper,BBusInfoPo> implements BBusInfoService {

    @Autowired
    private BBusInfoMapper bBusInfoMapper;
    @Resource
    private SnowflakeUtil snowflakeUtil;

	/**
     * 详情
     * @param id
     * @return
     */
    @Override
    public BBusInfoDto getDetailById(String id){
        BBusInfoPo bBusInfoPo = this.bBusInfoMapper.selectById(id);
        BBusInfoDto bBusInfoDto = BeanUtil.toBean(bBusInfoPo, BBusInfoDto.class);
        return bBusInfoDto;
    }

	/**
     * 保存
     * @param dto
     * @return
     */
    @Override
	public void save(BBusInfoDto dto){
        BBusInfoPo existingBus = this.bBusInfoMapper.selectOne(
                new QueryWrapper<BBusInfoPo>()
                        .eq("is_delete",0)
                        .eq("bus_no", dto.getBusNo())
        );
        if (existingBus != null) {
            throw new BusinessException("车牌号已存在，请检查后重试");
        }
        BBusInfoPo po = new BBusInfoPo();
        BeanUtils.copyProperties(dto,po);
        String driverPhone = po.getDriverPhone();
        boolean phone = PhoneUtil.isPhone(driverPhone);
        if(!phone){
            throw new BusinessException("手机号格式不正确");
        }
        ExtInfo extInfo = CurrentUserHolder.get();
        po.setId(snowflakeUtil.snowflakeId());
        po.setCreateTime(new Date());
        po.setUpdateTime(new Date());
        po.setCreatorId(extInfo.getUserId());
        po.setUpdaterId(extInfo.getUserId());
        po.setCreatorName(extInfo.getUserName());
        po.setUpdaterName(extInfo.getUserName());
		this.bBusInfoMapper.insert(po);
    }

    /**
    * 列表
    * @param dto
    * @return
    */
    @Override
    public List<BBusInfoDto> list(BBusInfoPageDto dto){
        return this.bBusInfoMapper.list(dto);
    }

	/**
     * 修改
     * @param dto
     * @return
     */
    @Override
    public void update(BBusInfoDto dto){
        BBusInfoPo existingBus = this.bBusInfoMapper.selectOne(
                new QueryWrapper<BBusInfoPo>()
                        .eq("bus_no", dto.getBusNo())
                        .eq("is_delete",0)
                        .ne("id", dto.getId())
        );
        if (existingBus != null) {
            throw new BusinessException("车牌号已存在，请检查后重试");
        }
        BBusInfoPo po = new BBusInfoPo();
        BeanUtils.copyProperties(dto,po);
        String driverPhone = po.getDriverPhone();
        boolean phone = PhoneUtil.isPhone(driverPhone);
        if(!phone){
            throw new BusinessException("手机号格式不正确");
        }
        ExtInfo extInfo = CurrentUserHolder.get();
        po.setUpdateTime(new Date());
        po.setUpdaterId(extInfo.getUserId());
        po.setUpdaterName(extInfo.getUserName());
		bBusInfoMapper.updateById(po);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public void delete(String id){
		bBusInfoMapper.deleteById(id);
    }

    /**
     * 获取车辆状态树型数据
     *
     * @return
     */
    @Override
    public List<BBusTrackTreeDto> getTreeList() {
        // 查询所有未删除的车辆信息
        List<BBusInfoPo> busList = this.bBusInfoMapper.selectList(
                new QueryWrapper<BBusInfoPo>()
                        .eq("is_delete", 0)
        );
        // 按状态分组
        Map<String, List<BBusInfoPo>> busGroups = busList.stream()
                .collect(Collectors.groupingBy(BBusInfoPo::getStatus));

        // 构建树形结构
        List<BBusTrackTreeDto> treeList = new ArrayList<>();

        // 添加状态分组节点
        busGroups.forEach((status, buses) -> {
            BBusTrackTreeDto statusNode = new BBusTrackTreeDto();
            statusNode.setStatus(status);
            // 添加子节点（车辆）
            List<BBusInfoDto> children = buses.stream()
                    .map(bus -> {
                        BBusInfoDto busNode = new BBusInfoDto();
                        busNode.setId(bus.getId());
                        busNode.setBusNo(bus.getBusNo());
                        busNode.setBusName(bus.getBusName());
                        busNode.setStatus(bus.getStatus());
                        return busNode;
                    })
                    .collect(Collectors.toList());

            statusNode.setList(children);
            treeList.add(statusNode);
        });

        return treeList;
    }

    /**
     * 根据车辆ID获取车辆追踪信息
     *
     * @param busId
     * @return
     */
    @Override
    public BBusTrackInfoDto getTrackInfo(String busId) {

        return null;
    }
}
