package cn.iocoder.yudao.module.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.IDCardOCR;
import cn.iocoder.yudao.util.VehicleLicenseOCR;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.shop.entity.ShopCoupon;
import cn.iocoder.yudao.module.shop.entity.ShopUserCar;
import cn.iocoder.yudao.module.shop.mapper.ShopUserCarMapper;
import cn.iocoder.yudao.module.shop.service.IShopCouponService;
import cn.iocoder.yudao.module.shop.service.IShopUserCarService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 用户车辆Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-10
 */
@Service
public class ShopUserCarServiceImpl extends ServiceImpl<ShopUserCarMapper,ShopUserCar> implements IShopUserCarService
{
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IShopCouponService shopCouponService;

    /**
     * 查询用户车辆
     *
     * @param carId 用户车辆主键
     * @return 用户车辆
     */
    @Override
    public ShopUserCar selectShopUserCarByCarId(Long carId)
    {
        return baseMapper.selectShopUserCarByCarId(carId);
    }



    /**
     * 查询用户车辆列表
     *
     * @param shopUserCar 用户车辆
     * @return 用户车辆
     */
    @Override
    public IPage<ShopUserCar> selectShopUserCarList(Page<ShopUserCar> page, ShopUserCar shopUserCar)
    {
        return baseMapper.selectShopUserCarList(page,shopUserCar);
    }

    /**
     * 新增用户车辆
     *
     * @param shopUserCar 用户车辆
     * @return 结果
     */
    @Override
    public int insertShopUserCar(ShopUserCar shopUserCar)
    {
        return baseMapper.insertShopUserCar(shopUserCar);
    }

    /**
     * 修改用户车辆
     *
     * @param shopUserCar 用户车辆
     * @return 结果
     */
    @Override
    public int updateShopUserCar(ShopUserCar shopUserCar)
    {
        return baseMapper.updateShopUserCar(shopUserCar);
    }

    /**
     * 批量删除用户车辆
     *
     * @param carIds 需要删除的用户车辆主键
     * @return 结果
     */
    @Override
    public int deleteShopUserCarByCarIds(Long[] carIds)
    {
        return baseMapper.deleteShopUserCarByCarIds(carIds);
    }

    /**
     * 删除用户车辆信息
     *
     * @param carId 用户车辆主键
     * @return 结果
     */
    @Override
    public int deleteShopUserCarByCarId(Long carId)
    {
        return baseMapper.deleteShopUserCarByCarId(carId);
    }

    @Override
    public ShopUserCar selectShopUserCarByUserId(Long userId) {
        ShopUserCar shopUserCar = baseMapper.selectShopUserCarByUserId(userId);
        //注册日期
        if (ObjectUtil.isEmpty(shopUserCar)||ObjectUtil.isEmpty(shopUserCar.getCarRegisterDate())){
            return shopUserCar;
        }
        Date carRegisterDate = shopUserCar.getCarRegisterDate();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(carRegisterDate);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //营运性质
        String carNature = shopUserCar.getCarNature();
        if (!StringUtils.isEmpty(carNature)){
            LocalDate currentDate = LocalDate.now();
            int nowYear = currentDate.getYear();
            int nowMonth = currentDate.getMonthValue();
            int nowDay = currentDate.getDayOfMonth();
            String  resDate = (nowYear)+1+"-"+month+"-"+day;
            if (carNature.equals("营运车")){
                if (nowMonth>month){
                    resDate = nowYear+"-"+month+"-"+day;
                }else if (nowMonth == month){
                    if (nowDay>day){
                        resDate = nowYear+"-"+month+"-"+day;
                    }
                }
            }else {
                if (year+5>=nowYear){
                    //五年免检
                    resDate = year+6+"-"+month+"-"+day;
                }else {
                    if (nowMonth>month){
                        resDate = nowYear+"-"+month+"-"+day;
                    }else if (nowMonth == month){
                        if (nowDay>day){
                            resDate = nowYear+"-"+month+"-"+day;
                        }
                    }
                }
            }
            shopUserCar.setNextInspectionDate(DateUtil.parseDate(resDate));

            if (carNature.equals("营运车")&&!ObjectUtil.isEmpty(shopUserCar.getCheckDate())){
                //处理二级维护时间
                Date checkDate = shopUserCar.getCheckDate();
                Instant instant = checkDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
                LocalDate checkLocalDate = instant.atZone(zoneId).toLocalDate();
                LocalDate newDate = checkLocalDate.plusMonths(3); // 将当前日期加上三个月
                LocalDate today = LocalDate.now(); // 获取当前日期
                while(newDate.isBefore(today)){
                    newDate = newDate.plusMonths(3);
                }
                ZoneId zoneId2 = ZoneId.systemDefault();
                ZonedDateTime zdt2 = newDate.atStartOfDay(zoneId2);

                Date date = Date.from(zdt2.toInstant());
                shopUserCar.setNextCheckDate(date);
            }
        }
        return shopUserCar;
    }

    @Override
    public ShopUserCar selectUserCarsByUserIdCarNum(Long userId,String carNum) {
        return baseMapper.selectUserCarsByUserIdCarNum(userId,carNum);
    }
    @Override
    public List<ShopUserCar> selectUserCarsByUserId(Long userId){
        return baseMapper.selectUserCarsByUserId(userId);
    }
    @Override
    public List<ShopUserCar> getDbCars(Long userId){
        return baseMapper.getDbCars(userId);
    }

    @Override
    public String vehicleLicenseOCR(String imagePath) throws TencentCloudSDKException {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO sysUser = userService.getUser(loginUser.getId());
        String info = VehicleLicenseOCR.dealFunction(imagePath);
        JSONObject infoJson =JSONObject.parseObject(info);
        JSONObject jsonObject = infoJson.getJSONObject("FrontInfo");

        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        userSaveReqVO.setId(sysUser.getId());
        userSaveReqVO.setNickname(jsonObject.getString("Owner"));
        userService.updateUser(new UserSaveReqVO());


        ShopUserCar shopUserCar = this.selectShopUserCarByUserId(loginUser.getId());
        if (ObjectUtil.isNotEmpty(shopUserCar)){
            //编辑
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.updateShopUserCar(shopUserCar);
        }
        else {
            //新增
            shopUserCar =new ShopUserCar();
            shopUserCar.setUserId(sysUser.getId());
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.insertShopUserCar(shopUserCar);
            if (sysUser.getUserLevel()==0){
                sysUser.setUserLevel(1);
                UserSaveReqVO userSaveReqVO2 = new UserSaveReqVO();
                userSaveReqVO2.setId(sysUser.getId());
                userSaveReqVO2.setUserLevel(1);
                userService.updateUser(userSaveReqVO2);
                //处理优惠券
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MONTH, 1);
                ShopCoupon shopCoupon2 =new ShopCoupon();
                shopCoupon2.setStartTime(new Date());
                shopCoupon2.setExpirationTime(cal.getTime());
                shopCoupon2.setBindMoudle("维修项目现金券");
                shopCoupon2.setTitle("汽修50元优惠券");
                shopCoupon2.setPhonenumber(sysUser.getMobile());
                shopCoupon2.setDiscount(5000L);
                shopCoupon2.setUserId(sysUser.getId());
                shopCoupon2.setCouponType("cash");
                shopCouponService.insertShopCoupon(shopCoupon2);
                return "恭喜您，成功升级白银级别会员";
            }

        }
        return "";
    }

    @Override
    public String appVehicleLicenseOCR(String imagePath) throws Exception {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO sysUser = userService.getUser(loginUser.getId());
        String info = VehicleLicenseOCR.dealFunction(imagePath);
        JSONObject infoJson =JSONObject.parseObject(info);
        JSONObject jsonObject = infoJson.getJSONObject("FrontInfo");
        ShopUserCar shopUserCar = this.selectUserCarsByUserIdCarNum(loginUser.getId(),jsonObject.getString("PlateNo"));
        if (ObjectUtil.isNotEmpty(shopUserCar)){
            //编辑
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.updateShopUserCar(shopUserCar);
            this.dealCarDate(shopUserCar);
        }else {
            //新增
            shopUserCar =new ShopUserCar();
            shopUserCar.setUserId(sysUser.getId());
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.save(shopUserCar);
            this.dealCarDate(shopUserCar);
            if (sysUser.getUserLevel()==0){
                sysUser.setUserLevel(1);
                UserSaveReqVO userSaveReqVO2 = new UserSaveReqVO();
                userSaveReqVO2.setId(sysUser.getId());
                userSaveReqVO2.setUserLevel(1);
                userService.updateUser(userSaveReqVO2);
                return "恭喜您，成功升级白银级别会员";
            }
        }
        return "";
    }
    @Override
    public JSONObject appVehicleLicenseOCR2(String imagePath) throws Exception {

        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO sysUser = userService.getUser(loginUser.getId());
        String info = VehicleLicenseOCR.dealFunction(imagePath);
        JSONObject infoJson =JSONObject.parseObject(info);
        JSONObject jsonObject = infoJson.getJSONObject("FrontInfo");
        ShopUserCar shopUserCar = this.selectUserCarsByUserIdCarNum(loginUser.getId(),jsonObject.getString("PlateNo"));
        if (ObjectUtil.isNotEmpty(shopUserCar)){
            //编辑
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.updateShopUserCar(shopUserCar);
            this.dealCarDate(shopUserCar);
        }else {
            //新增
            shopUserCar =new ShopUserCar();
            shopUserCar.setUserId(sysUser.getId());
            //车牌号
            shopUserCar.setCarNo(jsonObject.getString("PlateNo"));
            //车型
            shopUserCar.setCarModel(jsonObject.getString("Model")+"  "+jsonObject.getString("VehicleType"));
            //车品牌
            shopUserCar.setCarBrand(jsonObject.getString("Model"));
            shopUserCar.setCarRegisterDate(DateUtil.parse(jsonObject.getString("RegisterDate"),"yyyy-MM-dd"));
            shopUserCar.setCarNature(jsonObject.getString("UseCharacter"));
            shopUserCar.setCarLicenseImg(imagePath);
            this.save(shopUserCar);
            this.dealCarDate(shopUserCar);
            if (sysUser.getUserLevel()==0){
                sysUser.setUserLevel(1);
                UserSaveReqVO userSaveReqVO2 = new UserSaveReqVO();
                userSaveReqVO2.setId(sysUser.getId());
                userSaveReqVO2.setUserLevel(1);
                userService.updateUser(userSaveReqVO2);
            }
        }
        return jsonObject;
    }
    @Override
    public void infoCardOCR(String imagePath) throws TencentCloudSDKException {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();

        String cardInfo = IDCardOCR.dealFunction(imagePath);
        JSONObject infoCardJson =JSONObject.parseObject(cardInfo);

        UserSaveReqVO userSaveReqVO2 = new UserSaveReqVO();
        userSaveReqVO2.setId(loginUser.getId());
        userSaveReqVO2.setNickname(infoCardJson.getString("Name"));
        userSaveReqVO2.setSex(infoCardJson.getString("Sex").equals("男")?0:1);
        userSaveReqVO2.setIdCard(infoCardJson.getString("IdNum"));
        userSaveReqVO2.setIdCardImage(imagePath);
        //计算年龄
        String birth = infoCardJson.getString("Birth").split("/")[0];
        userSaveReqVO2.setUserAge(year-Integer.parseInt(birth));
        userService.updateUser(userSaveReqVO2);
    }

    @Override
    public JSONObject getInfoCard() {
        JSONObject res =new JSONObject();
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO sysUser = userService.getUser(loginUser.getId());
        ShopUserCar shopUserCar = this.selectShopUserCarByUserId(loginUser.getId());
        res.put("licenseImage",null);
        if (ObjectUtil.isNotEmpty(shopUserCar)){
            res.put("licenseImage",shopUserCar.getCarLicenseImg());
        }
        res.put("idCardImage",sysUser.getIdCardImage());
        return res;
    }

    @Override
    public void deleteShopUserCarByUserId(Long userId) {
        baseMapper.deleteShopUserCarByUserId(userId);
    }

    //处理年检日期保养日期
    void  dealCarDate(ShopUserCar shopUserCar){
            //注册日期
            Date carRegisterDate = shopUserCar.getCarRegisterDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(carRegisterDate);

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            //营运性质
            String carNature = shopUserCar.getCarNature();
            if (!StringUtils.isEmpty(carNature)){
                LocalDate currentDate = LocalDate.now();
                int nowYear = currentDate.getYear();
                int nowMonth = currentDate.getMonthValue();
                int nowDay = currentDate.getDayOfMonth();
                String  resDate = (nowYear)+1+"-"+month+"-"+day;
                if (carNature.equals("营运车")){
                    if (nowMonth>month){
                        resDate = nowYear+"-"+month+"-"+day;
                    }else if (nowMonth == month){
                        if (nowDay>day){
                            resDate = nowYear+"-"+month+"-"+day;
                        }
                    }
                }else {
                    if (year+5>=nowYear){
                        //五年免检
                        resDate = year+6+"-"+month+"-"+day;
                    }else {
                        if (nowMonth>month){
                            resDate = nowYear+"-"+month+"-"+day;
                        }else if (nowMonth == month){
                            if (nowDay>day){
                                resDate = nowYear+"-"+month+"-"+day;
                            }
                        }
                    }
                }
                shopUserCar.setNextInspectionDate(DateUtil.parseDate(resDate));

                if (carNature.equals("营运车")&&!ObjectUtil.isEmpty(shopUserCar.getCheckDate())){
                    //处理二级维护时间
                    Date checkDate = shopUserCar.getCheckDate();
                    Instant instant = checkDate.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
                    LocalDate checkLocalDate = instant.atZone(zoneId).toLocalDate();
                    LocalDate newDate = checkLocalDate.plusMonths(3); // 将当前日期加上三个月
                    LocalDate today = LocalDate.now(); // 获取当前日期
                    while(newDate.isBefore(today)){
                        newDate = newDate.plusMonths(3);
                    }
                    ZoneId zoneId2 = ZoneId.systemDefault();
                    ZonedDateTime zdt2 = newDate.atStartOfDay(zoneId2);

                    Date date = Date.from(zdt2.toInstant());
                    shopUserCar.setNextCheckDate(date);
                }
            }
            this.updateById(shopUserCar);
    }
}
