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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.common.RepairRoleEnum;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.app.booking.vo.BookingQueryVO;
import cn.iocoder.yudao.module.booking.entity.DlRepairBooking;
import cn.iocoder.yudao.module.booking.mapper.DlRepairBookingMapper;
import cn.iocoder.yudao.module.booking.service.DlRepairBookingService;
import cn.iocoder.yudao.module.booking.vo.BookingVO;
import cn.iocoder.yudao.module.booking.vo.DlRepairBookingReqVO;
import cn.iocoder.yudao.module.booking.vo.DlRepairBookingRespVO;
import cn.iocoder.yudao.module.company.entity.Company;
import cn.iocoder.yudao.module.company.service.CompanyService;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.service.ServicePackageApi;
import cn.iocoder.yudao.module.system.api.service.dto.ServicePackageDto;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 针对表【dl_repair_booking(维修预约表)】的数据库操作Service实现
 *
 * @author 小李
 * @date 10:19 2024/9/23
 **/
@Service
public class DlRepairBookingServiceImpl extends ServiceImpl<DlRepairBookingMapper, DlRepairBooking>
        implements DlRepairBookingService {

    @Resource
    @Lazy
    private CompanyService companyService;

    @Resource
    @Lazy
    private ServicePackageApi servicePackageApi;
    @Autowired
    private RoleApi roleApi;

    /**
     * 维修预约表 新增、修改
     *
     * @author 小李
     * @date 10:21 2024/9/23
     * @param repairBookingRespVO 预约对象
     **/
    @Override
    public void updateBooking(DlRepairBookingRespVO repairBookingRespVO){
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        Optional.ofNullable(loginUserId).ifPresent(repairBookingRespVO::setUserId);
        repairBookingRespVO.setBookingStatus("01");
        baseMapper.insertOrUpdate(repairBookingRespVO);
    }

    /**
     * 维修预约表 删除
     *
     * @author 小李
     * @date 10:26 2024/9/23
     * @param id 预约记录id
     **/
    @Override
    public void deleteBooking(String id){
        baseMapper.deleteById(id);
    }

    /**
     * 维修预约表 分页
     *
     * @author 小李
     * @date 10:31 2024/9/23
     * @param repairBookingReqVO 请求对象
     **/
    @Override
    public IPage<DlRepairBooking> getBookingPage(DlRepairBookingReqVO repairBookingReqVO, Page<DlRepairBooking> page){
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        Optional.ofNullable(loginUserId).ifPresent(repairBookingReqVO::setUserId);
        return baseMapper.getBookingPage(repairBookingReqVO, page);
    }

    /**
     * 维修预约表 查询单个
     *
     * @author 小李
     * @date 10:38 2024/9/23
     * @param id id
     **/
    @Override
    public DlRepairBooking getBookingById(String id){
        return baseMapper.selectById(id);
    }

    /**
     * 维修预约表 映射
     *
     * @author 小李
     * @date 13:32 2024/9/24
     * @param ids 预约记录ID
     **/
    @Override
    public List<BookingQueryVO> getBookingMap(List<String> ids){
        // 查预约记录
        if (CollectionUtil.isEmpty(ids)){
            return new ArrayList<>();
        }
        List<DlRepairBooking> dlRepairBookings = baseMapper.selectBatchIds(ids);
        List<BookingQueryVO> result = dlRepairBookings.stream().map(item -> BeanUtil.toBean(item, BookingQueryVO.class)).collect(Collectors.toList());
        // 查企业
        Set<String> companyIds = result.stream().map(BookingQueryVO::getCorpId).collect(Collectors.toSet());
        List<Company> companies = companyService.list(new LambdaQueryWrapper<Company>().in(Company::getId, companyIds));
        // 查服务
        Set<String> serviceIds = result.stream().map(BookingQueryVO::getProjectId).collect(Collectors.toSet());
        List<ServicePackageDto> servicePackageByIds = servicePackageApi.getServicePackageByIds(new ArrayList<>(serviceIds));
        // 映射
        result.forEach(item -> {
            companies.stream().filter(i -> i.getId().equals(item.getCorpId())).findFirst().ifPresent(item::setCompany);
            servicePackageByIds.stream().filter(i -> i.getId().equals(item.getProjectId())).findFirst().ifPresent(item::setServicePackage);
        });
        return result.stream().sorted(Comparator.comparing(BookingQueryVO::getCreateTime).reversed()).collect(Collectors.toList());
    }

    /**
     * @param tenantId 租户ID
     * @return java.util.List<cn.iocoder.yudao.module.booking.vo.BookingVO>
     * @author vinjor-M
     * @date 15:03 2024/10/26
     **/
    @Override
    @TenantIgnore
    public List<BookingVO> getBookingTime(Long tenantId) {
        Date nowDate = new Date();
        String[] timeList = "09:00,11:00,14:00,15:00,16:00,17:00".split(",");
        List<BookingVO> rtnList = new ArrayList<>();
        //先遍历日期
        for (int i = 0; i < 7; i++) {
            BookingVO thisDay = new BookingVO();
            List<BookingVO> timeVoList = new ArrayList<>();
            if(i==0){
                //今天
                String dayStr = DateUtil.formatDate(nowDate);
                //周几
                int weekDay = DateUtil.dayOfWeek(nowDate);
                System.out.println(dayStr.substring(5));
                thisDay.setDate(dayStr.substring(5));
                thisDay.setTitle(this.changeWeek(weekDay));
                thisDay.setDisabled(false);
                //遍历时间
                for (String timeStr:timeList){
                    BookingVO thisTime = new BookingVO();
                    thisTime.setDate(timeStr);
                    //拼接时间
                    String timeDateStr = dayStr+" "+timeStr+":00";
                    //转时间戳，比对大小
                    Date timeDate = DateUtil.parseDateTime(timeDateStr);
                    int compareResult = DateUtil.compare(nowDate, timeDate);
                    //nowDate  在 timeDate  之前,可以预约,否则不能预约
                    thisTime.setDisabled(compareResult >= 0);
                    timeVoList.add(thisTime);
                }
            }else{
                //往后6天,每天、每个时间都能预约
                Date thisDate =  DateUtil.offsetDay(nowDate, i);
                String dayStr = DateUtil.formatDate(thisDate);
                //周几
                int weekDay = DateUtil.dayOfWeek(thisDate);
                thisDay.setDate(dayStr.substring(5));
                thisDay.setTitle(this.changeWeek(weekDay));
                thisDay.setDisabled(false);
                //遍历时间
                for (String timeStr:timeList){
                    BookingVO thisTime = new BookingVO();
                    thisTime.setDate(timeStr);
                    thisTime.setDisabled(false);
                    timeVoList.add(thisTime);
                }
            }
            thisDay.setTimeList(timeVoList);
            rtnList.add(thisDay);
        }
        return rtnList;
    }

    private String changeWeek(int weekNum){
        String weekStr="";
        switch (weekNum){
            case 1:
                weekStr = "周日";
                break;
            case 2:
                weekStr = "周一";
                break;
            case 3:
                weekStr = "周二";
                break;
            case 4:
                weekStr = "周三";
                break;
            case 5:
                weekStr = "周四";
                break;
            case 6:
                weekStr = "周五";
                break;
            case 7:
                weekStr = "周六";
                break;
            default:
                break;
        }
        return weekStr;
    }

    /**
     * 获取所有服务顾问
     *
     * @param tenantId 租户ID
     * @return java.util.List<cn.iocoder.yudao.module.base.entity.RepairWorker>
     * @author vinjor-M
     * @date 15:52 2024/10/26
     **/
    @Override
    @TenantIgnore
    public List<UserDTO> getAllServicer(Long tenantId) {
        return roleApi.selectUserListByRoleCode(tenantId, RepairRoleEnum.ADVISOR.getCode());
    }
}




