package com.sikey.wa04.business.application.service.user;

import cn.hutool.http.HttpStatus;
import com.sikey.wa04.business.application.service.message.SchoolDisableMessageService;
import com.sikey.wa04.business.domain.adapter.DeviceConfigAdapter;
import com.sikey.wa04.business.infrastructure.dto.model.ChildSchoolDisableModel;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.SchoolDisableMessageRequest;
import com.sikey.wa04.business.infrastructure.dto.request.schooldisable.CreateSchoolDisableRequest;
import com.sikey.wa04.business.infrastructure.dto.request.schooldisable.DeleteSchoolDisableRequest;
import com.sikey.wa04.business.infrastructure.dto.request.schooldisable.GetallSchoolDisableRequest;
import com.sikey.wa04.business.infrastructure.dto.request.schooldisable.UpdateSchoolDisableRequest;
import com.sikey.wa04.business.infrastructure.dto.response.schooldisable.GetallSchoolDisableResponse;
import com.sikey.wa04.business.infrastructure.repository.ChildSchoolDisableRepository;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.exception.BusinessException;
import com.sikey.wa04.common.interceptor.CurrentRequestUser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 上课禁用
 *
 * @author luoyangwei
 */
@Slf4j
@Service
public class SchoolDisableService {
    @Resource
    private ChildSchoolDisableRepository childSchoolDisableRepository;

    @Resource
    private DeviceConfigAdapter deviceConfigAdapter;

    @Qualifier("myTaskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor myTaskExecutor;

    @Resource
    private SchoolDisableMessageService schoolDisableMessageService;

    /**
     * 创建上课禁用
     *
     * @param request                   请求
     * @param genericManufacturerHeader header
     */
    public void create(CreateSchoolDisableRequest request, GenericManufacturerHeader genericManufacturerHeader) {
        ChildSchoolDisableModel savedModel = childSchoolDisableRepository.save(new ChildSchoolDisableModel()
                .setChildId(request.cid())
                .setRepeats(request.repeats())
                .setStartTime(request.startTime())
                .setEndTime(request.endTime())
                .setStatus(request.status()));

        String currentUserId = CurrentRequestUser.get().getId();

        myTaskExecutor.execute(() -> {
            SchoolDisableMessageRequest schoolDisableMessageRequest = new SchoolDisableMessageRequest();
            schoolDisableMessageRequest.setId(String.valueOf(savedModel.getId()));
            schoolDisableMessageRequest.setStatus(request.status());
            schoolDisableMessageRequest.setHeader(genericManufacturerHeader);
            schoolDisableMessageRequest.setRepeats(request.repeats());
            schoolDisableMessageRequest.setStartTime(request.startTime());
            schoolDisableMessageRequest.setEndTime(request.endTime());
            schoolDisableMessageRequest.setCid(request.cid());
            schoolDisableMessageService.schoolDisableMessageChange(schoolDisableMessageRequest, currentUserId);
        });
    }

    /**
     * 更新上课禁用
     *
     * @param request                   请求
     * @param genericManufacturerHeader header
     */
    public void update(UpdateSchoolDisableRequest request, GenericManufacturerHeader genericManufacturerHeader) {
        Optional<ChildSchoolDisableModel> optional = childSchoolDisableRepository.findById(request.sdid());
        ChildSchoolDisableModel childSchoolDisableModel = optional.orElseThrow();
        Objects.requireNonNull(childSchoolDisableModel, "上课禁用不存在");
        childSchoolDisableModel.setRepeats(request.repeats())
                .setStartTime(request.startTime())
                .setEndTime(request.endTime())
                .setStatus(request.status());
        childSchoolDisableRepository.save(childSchoolDisableModel);

        String currentUserId = CurrentRequestUser.get().getId();

        myTaskExecutor.execute(() -> {
            SchoolDisableMessageRequest schoolDisableMessageRequest = new SchoolDisableMessageRequest();
            schoolDisableMessageRequest.setId(String.valueOf(childSchoolDisableModel.getId()));
            schoolDisableMessageRequest.setStatus(request.status());
            schoolDisableMessageRequest.setHeader(genericManufacturerHeader);
            schoolDisableMessageRequest.setRepeats(request.repeats());
            schoolDisableMessageRequest.setStartTime(request.startTime());
            schoolDisableMessageRequest.setEndTime(request.endTime());
            schoolDisableMessageRequest.setCid(request.cid());
            schoolDisableMessageService.schoolDisableMessageChange(schoolDisableMessageRequest, currentUserId);
        });
    }

    /**
     * 删除上课禁用
     *
     * @param request                   请求
     * @param genericManufacturerHeader header
     */
    public void delete(DeleteSchoolDisableRequest request, GenericManufacturerHeader genericManufacturerHeader) {
        // 获取上课禁用
        Optional<ChildSchoolDisableModel> optional = childSchoolDisableRepository.findById(request.sdid());
        ChildSchoolDisableModel childSchoolDisableModel = optional.orElseThrow(() -> new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, "上课禁用不存在"));

        childSchoolDisableRepository.deleteById(request.sdid());

        String currentUserId = CurrentRequestUser.get().getId();

        myTaskExecutor.execute(() -> {
            SchoolDisableMessageRequest schoolDisableMessageRequest = new SchoolDisableMessageRequest();
            schoolDisableMessageRequest.setId(String.valueOf(childSchoolDisableModel.getId()));
            schoolDisableMessageRequest.setStatus(childSchoolDisableModel.getStatus());
            schoolDisableMessageRequest.setHeader(genericManufacturerHeader);
            schoolDisableMessageRequest.setRepeats(childSchoolDisableModel.getRepeats());
            schoolDisableMessageRequest.setStartTime(childSchoolDisableModel.getStartTime());
            schoolDisableMessageRequest.setEndTime(childSchoolDisableModel.getEndTime());
            schoolDisableMessageRequest.setCid(childSchoolDisableModel.getChildId());
            schoolDisableMessageService.schoolDisableMessageChange(schoolDisableMessageRequest, currentUserId);
        });
    }

    /**
     * 获取所有上课禁用
     *
     * @param request      请求
     * @param isWristwatch 是否手表
     * @return 上课禁用列表
     */
    public GetallSchoolDisableResponse getall(GetallSchoolDisableRequest request, GenericManufacturerHeader genericManufacturerHeader, boolean isWristwatch) {
        List<ChildSchoolDisableModel> schoolDisableDOList = childSchoolDisableRepository.findByChildId(request.cid());
        List<GetallSchoolDisableResponse.GetallSchoolDisable> schoolDisables = schoolDisableDOList.stream()
                .map(schoolDisableDO -> new GetallSchoolDisableResponse.GetallSchoolDisable()
                        .setCid(schoolDisableDO.getChildId())
                        .setRepeats(schoolDisableDO.getRepeats())
                        .setStartTime(schoolDisableDO.getStartTime())
                        .setEndTime(schoolDisableDO.getEndTime())
                        .setStatus(schoolDisableDO.getStatus())
                        .setSdid(schoolDisableDO.getId())).toList();

        if (isWristwatch) {
            myTaskExecutor.execute(() -> {
                // 设备配置
                deviceConfigAdapter.deviceConfigMessageCenter(request.cid(), genericManufacturerHeader);
            });
        }

        return new GetallSchoolDisableResponse(schoolDisables);
    }
}
