package shop.alien.store.controller;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreBookingBusinessHours;
import shop.alien.entity.store.dto.StoreBookingBusinessHoursDTO;
import shop.alien.store.service.StoreBookingBusinessHoursService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 预订服务营业时间管理 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"预订服务-营业时间管理"})
@ApiSort(18)
@CrossOrigin
@RestController
@RequestMapping("/store/booking/business-hours")
@RequiredArgsConstructor
public class StoreBookingBusinessHoursController {

    private final StoreBookingBusinessHoursService storeBookingBusinessHoursService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("查询预订服务营业时间列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "settingsId", value = "设置ID（关联store_booking_settings表 id）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "businessType", value = "营业类型（1:正常营业时间, 2:特殊营业时间，可选，不传则查询全部）", dataType = "Integer", paramType = "query", required = false)
    })
    @GetMapping("/list")
    public R<List<StoreBookingBusinessHours>> getBusinessHoursList(
            @RequestParam Integer settingsId,
            @RequestParam(required = false) Integer businessType) {
        log.info("StoreBookingBusinessHoursController.getBusinessHoursList?settingsId={}, businessType={}", settingsId, businessType);
        
        if (settingsId == null) {
            return R.fail("设置ID不能为空");
        }
        
        try {
            List<StoreBookingBusinessHours> list;
            if (businessType != null) {
                list = storeBookingBusinessHoursService.getListBySettingsIdAndType(settingsId, businessType);
            } else {
                list = storeBookingBusinessHoursService.getListBySettingsId(settingsId);
            }
            return R.data(list);
        } catch (Exception e) {
            log.error("查询预订服务营业时间列表失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("查询预订服务营业时间详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "营业时间ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/detail")
    public R<StoreBookingBusinessHours> getBusinessHoursDetail(@RequestParam Integer id) {
        log.info("StoreBookingBusinessHoursController.getBusinessHoursDetail?id={}", id);
        
        if (id == null) {
            return R.fail("营业时间ID不能为空");
        }
        
        try {
            StoreBookingBusinessHours businessHours = storeBookingBusinessHoursService.getById(id);
            if (businessHours == null) {
                return R.fail("营业时间不存在");
            }
            return R.data(businessHours);
        } catch (Exception e) {
            log.error("查询预订服务营业时间详情失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("新增或更新预订服务营业时间")
    @PostMapping("/save")
    public R<String> saveBusinessHours(@RequestBody StoreBookingBusinessHoursDTO dto) {
        log.info("StoreBookingBusinessHoursController.saveBusinessHours?dto={}", dto);
        
        // 参数验证
        if (dto.getSettingsId() == null) {
            return R.fail("设置ID不能为空");
        }
//        if (dto.getBusinessType() == null) {
//            return R.fail("营业类型不能为空");
//        }
//        if (dto.getBookingTimeType() == null) {
//            return R.fail("预订时间类型不能为空");
//        }
        
        // 如果是特殊营业（节假日），验证节假日类型
//        if (dto.getBusinessType() != null && dto.getBusinessType() == 1) {
//            if (!StringUtils.hasText(dto.getHolidayType())) {
//                return R.fail("特殊营业时必须填写节假日类型");
//            }
//        }
        
        // 如果选择非全天，必须填写开始时间和结束时间
//        if (dto.getBookingTimeType() != null && dto.getBookingTimeType() == 0) {
//            if (!StringUtils.hasText(dto.getStartTime())) {
//                return R.fail("非全天时必须填写开始时间");
//            }
//            if (!StringUtils.hasText(dto.getEndTime())) {
//                return R.fail("非全天时必须填写结束时间");
//            }
//        }
        
        try {
            StoreBookingBusinessHours businessHours = new StoreBookingBusinessHours();
            businessHours.setId(dto.getId());
            businessHours.setSettingsId(dto.getSettingsId());
            businessHours.setBusinessType(dto.getBusinessType());
            businessHours.setHolidayType(dto.getHolidayType());
            businessHours.setHolidayDate(dto.getHolidayDate());
            businessHours.setBookingTimeType(dto.getBookingTimeType());
            businessHours.setStartTime(dto.getStartTime());
            businessHours.setEndTime(dto.getEndTime());
            businessHours.setSort(dto.getSort());
            
            boolean result = storeBookingBusinessHoursService.saveOrUpdateBusinessHours(businessHours);
            if (result) {
                return R.success("保存成功");
            } else {
                return R.fail("保存失败");
            }
        } catch (Exception e) {
            log.error("保存预订服务营业时间失败", e);
            return R.fail("保存失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("批量保存预订服务营业时间")
    @PostMapping("/batch-save")
    public R<String> batchSaveBusinessHours(@RequestBody List<StoreBookingBusinessHoursDTO> dtoList) {
        log.info("StoreBookingBusinessHoursController.batchSaveBusinessHours?size={}", dtoList != null ? dtoList.size() : 0);
        
        if (dtoList == null || dtoList.isEmpty()) {
            return R.fail("营业时间列表不能为空");
        }
        
        // 验证所有DTO的settingsId是否一致
        Integer settingsId = dtoList.get(0).getSettingsId();
        if (settingsId == null) {
            return R.fail("设置ID不能为空");
        }
        for (StoreBookingBusinessHoursDTO dto : dtoList) {
            if (dto.getSettingsId() == null || !dto.getSettingsId().equals(settingsId)) {
                return R.fail("所有营业时间的设置ID必须一致");
            }
        }
        
        try {
            // 转换为实体对象列表
            List<StoreBookingBusinessHours> businessHoursList = dtoList.stream()
                    .map(dto -> {
                        StoreBookingBusinessHours businessHours = new StoreBookingBusinessHours();
                        businessHours.setId(dto.getId());
                        businessHours.setSettingsId(dto.getSettingsId());
                        businessHours.setBusinessType(dto.getBusinessType());
                        businessHours.setHolidayType(dto.getHolidayType());
                        businessHours.setHolidayDate(dto.getHolidayDate());
                        businessHours.setBookingTimeType(dto.getBookingTimeType());
                        businessHours.setStartTime(dto.getStartTime());
                        businessHours.setEndTime(dto.getEndTime());
                        businessHours.setSort(dto.getSort());
                        return businessHours;
                    })
                    .collect(Collectors.toList());
            
            boolean result = storeBookingBusinessHoursService.batchSaveBusinessHours(settingsId, businessHoursList);
            if (result) {
                return R.success("批量保存成功");
            } else {
                return R.fail("批量保存失败");
            }
        } catch (Exception e) {
            log.error("批量保存预订服务营业时间失败", e);
            return R.fail("批量保存失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("删除预订服务营业时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "营业时间ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/delete")
    public R<String> deleteBusinessHours(@RequestParam Integer id) {
        log.info("StoreBookingBusinessHoursController.deleteBusinessHours?id={}", id);
        
        if (id == null) {
            return R.fail("营业时间ID不能为空");
        }
        
        try {
            boolean result = storeBookingBusinessHoursService.deleteBusinessHours(id);
            if (result) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除预订服务营业时间失败", e);
            return R.fail("删除失败：" + e.getMessage());
        }
    }
}
