/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.bizvehicle.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.bizexcessconfig.entity.BizExcessConfig;
import vip.xiaonuo.biz.modular.bizexcessconfig.service.BizExcessConfigService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.bizvehicle.entity.BizVehicle;
import vip.xiaonuo.biz.modular.bizvehicle.mapper.BizVehicleMapper;
import vip.xiaonuo.biz.modular.bizvehicle.param.BizVehicleAddParam;
import vip.xiaonuo.biz.modular.bizvehicle.param.BizVehicleEditParam;
import vip.xiaonuo.biz.modular.bizvehicle.param.BizVehicleIdParam;
import vip.xiaonuo.biz.modular.bizvehicle.param.BizVehiclePageParam;
import vip.xiaonuo.biz.modular.bizvehicle.service.BizVehicleService;
import vip.xiaonuo.common.util.CommonCryptogramUtil;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 车辆信息Service接口实现类
 *
 * @author fanzherong
 * @date  2025/04/08 09:26
 **/
@Service
public class BizVehicleServiceImpl extends ServiceImpl<BizVehicleMapper, BizVehicle> implements BizVehicleService {

    @Resource
    private BizExcessConfigService bizExcessConfigService;

    @Override
    public Page<BizVehicle> page(BizVehiclePageParam bizVehiclePageParam) {
        QueryWrapper<BizVehicle> queryWrapper = new QueryWrapper<BizVehicle>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizVehiclePageParam.getLicensePlate())){
            queryWrapper.like("bc.license_plate",bizVehiclePageParam.getLicensePlate());
        }
        if(ObjectUtil.isNotEmpty(bizVehiclePageParam.getDriverName())){
            queryWrapper.like("bc.driver_name",bizVehiclePageParam.getDriverName());
        }
        if(ObjectUtil.isNotEmpty(bizVehiclePageParam.getDriverMobile())){
            queryWrapper.like("bc.driver_mobile",bizVehiclePageParam.getDriverMobile());
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isEmpty(loginUserDataScope)) {
            queryWrapper.eq("bc.create_user", StpUtil.getLoginIdAsString());
        }
        queryWrapper.eq("bc.delete_flag","NOT_DELETE");
        queryWrapper.orderByDesc("bc.create_time");
        return this.getBaseMapper().getPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizVehicleAddParam bizVehicleAddParam) {
        checkParam(bizVehicleAddParam);
        BizVehicle bizVehicle = BeanUtil.toBean(bizVehicleAddParam, BizVehicle.class);
        if(ObjectUtil.isEmpty(bizVehicleAddParam.getDriverName())){
            bizVehicle.setDriverName(StpLoginUserUtil.getLoginUser().getName());
        }
        if(ObjectUtil.isEmpty(bizVehicleAddParam.getDriverMobile())){
            bizVehicle.setDriverMobile(CommonCryptogramUtil.doSm4CbcDecrypt(StpLoginUserUtil.getLoginUser().getPhone()));
        }
        this.save(bizVehicle);
    }

    public void checkParam(BizVehicleAddParam bizVehicleAddParam){
        if(ObjectUtil.isNotEmpty(bizVehicleAddParam.getLicensePlate())){
            bizVehicleAddParam.setLicensePlate(bizVehicleAddParam.getLicensePlate().toUpperCase().trim());
            //校验车牌号
            if(!isCarNumber(bizVehicleAddParam.getLicensePlate())){
                //throw new CommonException("车牌号：{}格式错误",bizVehicleAddParam.getLicensePlate());
            }
            //判断车牌号是否添加过
            long count = this.count(new QueryWrapper<BizVehicle>().lambda().
                    eq(BizVehicle::getLicensePlate, bizVehicleAddParam.getLicensePlate()).
                    eq(BizVehicle::getStatus, "1"));
            if(count>0){
                //throw new CommonException("车牌号：{}已经添加过！",bizVehicleAddParam.getLicensePlate());
            }
        }
        //校验司机电话
        if(ObjectUtil.isNotEmpty(bizVehicleAddParam.getDriverMobile())){
            if(!PhoneUtil.isMobile(bizVehicleAddParam.getDriverMobile())) {
                throw new CommonException("手机号码：{}格式错误", bizVehicleAddParam.getDriverMobile());
            }
        }
        long count = this.count(new QueryWrapper<BizVehicle>().lambda().
                eq(BizVehicle::getCreateUser, StpLoginUserUtil.getLoginUser().getId()).
                eq(BizVehicle::getStatus, "1"));
        if(count>0){
            throw new CommonException("已添加过启用得车辆信息");
        }
    }

    public void checkParam(BizVehicleEditParam bizVehicleEditParam,BizVehicle bizVehicle){
        if(ObjectUtil.isNotEmpty(bizVehicleEditParam.getLicensePlate())){
            bizVehicleEditParam.setLicensePlate(bizVehicleEditParam.getLicensePlate().toUpperCase().trim());
            //判断车牌号是否添加过
            if(!StringUtils.equals(bizVehicle.getLicensePlate(),bizVehicleEditParam.getLicensePlate())){
                //校验车牌号
                if(!isCarNumber(bizVehicleEditParam.getLicensePlate())){
                    throw new CommonException("车牌号：{}格式错误",bizVehicleEditParam.getLicensePlate());
                }
                long count = this.count(new QueryWrapper<BizVehicle>().lambda().
                        eq(BizVehicle::getLicensePlate, bizVehicleEditParam.getLicensePlate()).
                        eq(BizVehicle::getStatus, "1"));
                if(count>0){
                    throw new CommonException("车牌号：{}已经添加过！",bizVehicleEditParam.getLicensePlate());
                }
                long sum = this.count(new QueryWrapper<BizVehicle>().lambda().
                        eq(BizVehicle::getCreateUser, StpLoginUserUtil.getLoginUser().getId()).
                        eq(BizVehicle::getStatus, "1").
                        ne(BizVehicle::getLicensePlate,bizVehicle.getLicensePlate()));
                if(sum>0){
                    throw new CommonException("已添加过启用得车辆信息");
                }
            }
        }
        //校验司机电话
        if(ObjectUtil.isNotEmpty(bizVehicleEditParam.getDriverMobile())){
            if(!PhoneUtil.isMobile(bizVehicleEditParam.getDriverMobile())) {
                throw new CommonException("手机号码：{}格式错误", bizVehicleEditParam.getDriverMobile());
            }
        }
        //启用时校验修改状态
        if(!StringUtils.equals(bizVehicle.getStatus(),bizVehicleEditParam.getStatus())){
            if(StringUtils.equals(bizVehicleEditParam.getStatus(),"1")){
                long count = this.count(new QueryWrapper<BizVehicle>().lambda().
                        eq(BizVehicle::getLicensePlate, bizVehicleEditParam.getLicensePlate()).
                        eq(BizVehicle::getStatus, "1"));
                if(count>0){
                    throw new CommonException("车牌号：{}已经添加过！",bizVehicleEditParam.getLicensePlate());
                }
                long sum = this.count(new QueryWrapper<BizVehicle>().lambda().
                        eq(BizVehicle::getCreateUser, StpLoginUserUtil.getLoginUser().getId()).
                        eq(BizVehicle::getStatus, "1"));
                if(sum>0){
                    throw new CommonException("已添加过启用得车辆信息");
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizVehicleEditParam bizVehicleEditParam) {
        BizVehicle bizVehicle = this.queryEntity(bizVehicleEditParam.getId());
        checkParam(bizVehicleEditParam,bizVehicle);
        BeanUtil.copyProperties(bizVehicleEditParam, bizVehicle);
        if(ObjectUtil.isEmpty(bizVehicleEditParam.getDriverName())){
            bizVehicle.setDriverName(StpLoginUserUtil.getLoginUser().getName());
        }
        if(ObjectUtil.isEmpty(bizVehicleEditParam.getDriverMobile())){
            bizVehicle.setDriverMobile(CommonCryptogramUtil.doSm4CbcDecrypt(StpLoginUserUtil.getLoginUser().getPhone()));
        }
        this.updateById(bizVehicle);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizVehicleIdParam> bizVehicleIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizVehicleIdParamList, BizVehicleIdParam::getId));
    }

    @Override
    public BizVehicle detail(BizVehicleIdParam bizVehicleIdParam) {
        return this.queryEntity(bizVehicleIdParam.getId());
    }

    @Override
    public BizVehicle queryEntity(String id) {
        BizVehicle bizVehicle = this.getById(id);
        if(ObjectUtil.isEmpty(bizVehicle)) {
            throw new CommonException("车辆信息不存在，id值为：{}", id);
        }
        return bizVehicle;
    }

    @Override
    public BizVehicle queryByUserId() {
        BizVehicle bizVehicle = this.getOne(new QueryWrapper<BizVehicle>().lambda().
                eq(BizVehicle::getStatus, "1").
                eq(BizVehicle::getCreateUser, StpLoginUserUtil.getLoginUser().getId()).
                last("limit 1"));
        if(ObjectUtil.isNotNull(bizVehicle)){
            BizExcessConfig excessConfig = bizExcessConfigService.getById(bizVehicle.getVehicleAxles());
            if(ObjectUtil.isNotNull(excessConfig)){
                bizVehicle.setVehicleAxleNumber(excessConfig.getVehicleAxleNumber().toString());
            }
        }
        return bizVehicle;
    }

    /**
     * 车牌号校验
     * @param carNumber
     * @return
     */
    public boolean isCarNumber(String carNumber){
        String carNumberPattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(carNumberPattern, carNumber);
    }
}
