package com.ruoyi.app.mendian;

import com.ruoyi.app.mendian.dto.AppointmentTimeDto;
import com.ruoyi.app.utils.OperatingUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.OperatingHours;
import com.ruoyi.system.service.IOperatingHoursService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * OperatingHoursController
 *
 * @author ruoyi
 * @date 2025-02-11
 */
@RestController
@RequestMapping("/hours")
public class OperatingHoursController extends BaseController
{
    @Autowired
    private IOperatingHoursService operatingHoursService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 获取客户端预约时间段
     *
     * @return
     */
    @Anonymous
    @GetMapping("/getAppointmentTime")
    public AjaxResult getAppointmentTime(){
        List<SysDictData> dictList = dictTypeService.selectDictDataByType("sys_operating_hours");

        AppointmentTimeDto dto = new AppointmentTimeDto();
        dto.setStartTime(dictList.get(0).getDictValue());
        dto.setEndTime(dictList.get(dictList.size()-1).getDictValue());
        List<AppointmentTimeDto> appointmentTimeList = OperatingUtil.getAppointmentTime(dto);
        return success(appointmentTimeList);
    }

    /**
     * 管理员统一设置门店营业时间段
     * @param command
     * @return
     */
    @Anonymous
    @GetMapping("/setStoreHours")
    public AjaxResult setStoreHours(String command){
        if(!command.equals("我是管理员")){
            throw new ServiceException("指令错误");
        }
        List<OperatingHours> list = operatingHoursService.list();
        Map<Long, List<OperatingHours>> map = list.stream().collect(Collectors.groupingBy(OperatingHours::getMdId));
        List<OperatingHours> inserts = new ArrayList<>();
        map.forEach((mdId, hoursList) -> {
            List<OperatingHours> mdDefaultList = hoursList.stream().filter(x->x.getDayOfWeek().equals(1)).collect(Collectors.toList());
            for(int i = 1; i <=7 ; i++){
                int finalI = i;
                OperatingHours hours = hoursList.stream().filter(h -> h.getDayOfWeek() == finalI).findFirst().orElse(null);
                if(hours == null){
                    mdDefaultList.forEach(mdDefault -> {
                        OperatingHours data = new OperatingHours();
                        data.setMdId(mdId);
                        data.setDayOfWeek(finalI);
                        data.setIsOpen(true);
                        data.setStartTime(mdDefault.getStartTime());
                        data.setEndTime(mdDefault.getEndTime());
                        inserts.add( data);
                    });

                }
            }
        });
        if(!inserts.isEmpty())
            operatingHoursService.saveBatch(inserts);
        return success(MessageUtils.message("no.action.success"));

    }

    /**
     * 添加时间段
     * @param operatingHours
     * @return
     */
    @Anonymous
    @PostMapping("/addHours")
    public AjaxResult addHours(@RequestBody OperatingHours operatingHours){
        Long id = operatingHoursService.insertOperatingHoursReturnId(operatingHours);
        if (id > 0) {
            Map<String, Long> data = new HashMap<>();
            data.put("id", id);
            return success(MessageUtils.message("no.action.success"), data);
        }
        return toAjax(id.intValue());
    }
    /**
     * 修改时间段
     * @param operatingHours
     * @return
     */
    @Anonymous
    @PostMapping("/setHours")
    public AjaxResult setHours(@RequestBody OperatingHours operatingHours){
        return toAjax(operatingHoursService.updateOperatingHours(operatingHours));
    }

    /**
     * 删除时间段
     * @return
     */
    @Anonymous
    @GetMapping("/delHours")
    public AjaxResult delHours(@RequestParam Long id){
        return toAjax(operatingHoursService.deleteOperatingHoursById(id));
    }

    /**
     * 查询时间段
     * @param mdId
     * @return
     */
    @Anonymous
    @GetMapping("/getHours")
    public AjaxResult getHours(@RequestParam Long mdId){
        OperatingHours operatingHours = new OperatingHours();
        operatingHours.setMdId(mdId);
        List<OperatingHours> list = operatingHoursService.selectOperatingHoursList(operatingHours);
        return success(MessageUtils.message("no.obtained.success"),list);
    }

    /**
     * 查询OperatingHours列表
     */
    @PreAuthorize("@ss.hasPermi('system:hours:list')")
    @GetMapping("/list")
    public TableDataInfo list(OperatingHours operatingHours)
    {
        startPage();
        List<OperatingHours> list = operatingHoursService.selectOperatingHoursList(operatingHours);
        return getDataTable(list);
    }

    /**
     * 导出OperatingHours列表
     */
    @PreAuthorize("@ss.hasPermi('system:hours:export')")
    @Log(title = "OperatingHours", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OperatingHours operatingHours)
    {
        List<OperatingHours> list = operatingHoursService.selectOperatingHoursList(operatingHours);
        ExcelUtil<OperatingHours> util = new ExcelUtil<OperatingHours>(OperatingHours.class);
        util.exportExcel(response, list, "OperatingHours数据");
    }

    /**
     * 获取OperatingHours详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:hours:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(operatingHoursService.selectOperatingHoursById(id));
    }

    /**
     * 新增OperatingHours
     */
    @PreAuthorize("@ss.hasPermi('system:hours:add')")
    @Log(title = "OperatingHours", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OperatingHours operatingHours)
    {
        return toAjax(operatingHoursService.insertOperatingHours(operatingHours));
    }

    /**
     * 修改OperatingHours
     */
    @PreAuthorize("@ss.hasPermi('system:hours:edit')")
    @Log(title = "OperatingHours", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OperatingHours operatingHours)
    {
        return toAjax(operatingHoursService.updateOperatingHours(operatingHours));
    }

    /**
     * 删除OperatingHours
     */
    @PreAuthorize("@ss.hasPermi('system:hours:remove')")
    @Log(title = "OperatingHours", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(operatingHoursService.deleteOperatingHoursByIds(ids));
    }
}
