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

import cn.hutool.core.collection.CollectionUtil;
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.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.SendSmsUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.service.AppUserOwnService;
import cn.iocoder.yudao.module.shop.entity.ShopUserCar;
import cn.iocoder.yudao.module.shop.service.IShopUserCarService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.*;
import java.util.stream.Collectors;

@Service
public class AppUserOwnServiceImpl implements AppUserOwnService {

    @Autowired
    private AdminUserService userService;
    @Autowired
    private RoleApi roleApi;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private IShopUserCarService userCarService;

    @Override
    public void updateRole(String roleCode) {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();

        RoleReqDTO sysRole = roleApi.getRoleInfo(roleCode);
        if (ObjectUtil.isEmpty(sysRole)){
            return;
        }
        Set<Long> roleCodes = new HashSet<>();
        roleCodes.add(sysRole.getId());
        permissionService.assignUserRole(loginUser.getId(),roleCodes);
    }

    @Override
    public List<ShopUserCar> getCars() {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        List<ShopUserCar> shopUserCars = userCarService.selectUserCarsByUserId(loginUser.getId());
        return shopUserCars;
    }

    @Override
    public List<ShopUserCar> getCanInspectionCars() {
        List<ShopUserCar> res = new ArrayList<>();
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //自己的车
        List<ShopUserCar> shopUserCars = userCarService.selectUserCarsByUserId(loginUser.getId());
        if (CollectionUtil.isNotEmpty(shopUserCars)){
            res.addAll(shopUserCars);
        }
        //代办车
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(loginUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);

        List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());
        if (roleKeys.contains("jcdb")){
            //如果是代办
            //再追加近十天的委托授权
            List<ShopUserCar> dbCars = userCarService.getDbCars(loginUser.getId());
            res.addAll(dbCars);

        }
        return res;
    }

    @Override
    public List<AdminUserDO> getDbList(Page<AdminUserDO> page, String searchValue) {
        String roleCode = "jcdb";
        return userService.getUsersByRoleRescue(roleCode,searchValue,null);
    }
    @Override
    public IPage<AdminUserDO> getDbListTow(Page<AdminUserDO> page, String searchValue) {
        String roleCode = "jcdb";
        return userService.getUsersByRoleRescueTow(page,roleCode,searchValue,null);
    }
    @Override
    public List<ShopUserCar> getAppUserCar() {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        List<ShopUserCar> shopUserCars = userCarService.selectUserCarsByUserId(loginUser.getId());
        if (CollectionUtil.isEmpty(shopUserCars)){
            return new ArrayList<>();
        }
        for (ShopUserCar shopUserCar : shopUserCars) {
            //注册日期
            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 shopUserCars;
    }

    @Override
    public void userCarWarn() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 30);
        Date date = cal.getTime();
        String dateStr = DateUtil.format(date,"yyyy-MM-dd");
        LambdaQueryWrapper<ShopUserCar> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.like(ShopUserCar::getNextInspectionDate,dateStr);
        List<ShopUserCar> list = userCarService.list(queryWrapper);
        for (ShopUserCar shopUserCar : list) {
            AdminUserDO user = userService.getUser(shopUserCar.getUserId());
            SendSmsUtil.sendMsg(shopUserCar.getCarNo(),user.getMobile(),"1400852709","机动车管家小程序","1918105");
        }
    }
}
