package com.fs.company.controller.live;

import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveAutoTask;
import com.fs.live.mapper.LiveMapper;
import com.fs.live.param.LiveAutoTaskExportParam;
import com.fs.live.param.LiveAutoTaskImportParam;
import com.fs.live.service.ILiveAutoTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 直播间自动化任务配置Controller
 *
 * @author fs
 * @date 2025-08-29
 */
@RestController
@RequestMapping("/live/task")
public class LiveAutoTaskController extends BaseController
{
    @Autowired
    private ILiveAutoTaskService liveAutoTaskService;
    @Autowired
    private LiveMapper liveMapper;

    /**
     * 查询直播间自动化任务配置列表
     */
    @PreAuthorize("@ss.hasPermi('live:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(LiveAutoTask liveAutoTask)
    {
        startPage();
        List<LiveAutoTask> list = liveAutoTaskService.selectLiveAutoTaskList(liveAutoTask);
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('live:task:list')")
    @GetMapping("/consoleList")
    public TableDataInfo consoleList(LiveAutoTask liveAutoTask)
    {
        startPage();
        // 大屏查询后面20条数据
        List<LiveAutoTask> list = liveAutoTaskService.consoleList(liveAutoTask.getLiveId());
        return getDataTable(list);
    }
    /**
     * 查询直播间自动化任务配置列表
     */
    @PreAuthorize("@ss.hasPermi('live:task:list')")
    @GetMapping("/listBarrage")
    public TableDataInfo listBarrage(LiveAutoTask liveAutoTask)
    {
        startPage();
        List<LiveAutoTask> list = liveAutoTaskService.selectLiveAutoTaskBarrageList(liveAutoTask);
        return getDataTable(list);
    }

    /**
     * 导出直播间自动化任务配置列表
     */
    @PreAuthorize("@ss.hasPermi('live:task:export')")
    @Log(title = "直播间自动化任务配置", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveAutoTask liveAutoTask)
    {
        List<LiveAutoTask> list = liveAutoTaskService.selectLiveAutoTaskList(liveAutoTask);
        ExcelUtil<LiveAutoTask> util = new ExcelUtil<LiveAutoTask>(LiveAutoTask.class);
        return util.exportExcel(list, "直播间自动化任务配置数据");
    }

    /**
     * 获取直播间自动化任务配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:task:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(liveAutoTaskService.selectLiveAutoTaskById(id));
    }

    /**
     * 新增直播间自动化任务配置
     */
    @PreAuthorize("@ss.hasPermi('live:task:add')")
    @Log(title = "直播间自动化任务配置", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody LiveAutoTask liveAutoTask)
    {
        return liveAutoTaskService.insertLiveAutoTask(liveAutoTask);
    }

    /**
     * 修改直播间自动化任务配置
     */
    @PreAuthorize("@ss.hasPermi('live:task:edit')")
    @Log(title = "直播间自动化任务配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody LiveAutoTask liveAutoTask)
    {
        return liveAutoTaskService.updateLiveAutoTask(liveAutoTask);
    }

    /**
     * 删除直播间自动化任务配置
     */
    @PreAuthorize("@ss.hasPermi('live:task:remove')")
    @Log(title = "直播间自动化任务配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(liveAutoTaskService.deleteLiveAutoTaskByIds(ids));
    }

    /**
     * 导出直播间自动化任务配置列表
     */
    @PreAuthorize("@ss.hasPermi('live:task:export')")
    @Log(title = "直播间自动化任务配置", businessType = BusinessType.EXPORT)
    @GetMapping("/exportData")
    public AjaxResult exportData(LiveAutoTask liveAutoTask)
    {
        List<LiveAutoTask> list = liveAutoTaskService.selectLiveAutoTaskBarrageList(liveAutoTask);
        ExcelUtil<LiveAutoTaskExportParam> util = new ExcelUtil<LiveAutoTaskExportParam>(LiveAutoTaskExportParam.class);
        ArrayList<LiveAutoTaskExportParam> barrageList = new ArrayList<>();
        for (LiveAutoTask autoTask : list) {
            LiveAutoTaskExportParam liveAutoTaskImportParam = new LiveAutoTaskExportParam();
            liveAutoTaskImportParam.setTaskName(autoTask.getTaskName());
            liveAutoTaskImportParam.setContent(autoTask.getContent());
            liveAutoTaskImportParam.setRegisterDate(autoTask.getTriggerValue());
            barrageList.add(liveAutoTaskImportParam);
        }

        return util.exportExcel(barrageList, "直播间弹幕脚本数据");
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<LiveAutoTaskImportParam> util = new ExcelUtil<>(LiveAutoTaskImportParam.class);
        return util.importTemplateExcel("导入模板");
    }

    @PreAuthorize("@ss.hasPermi('live:task:export')")
    @PostMapping("/importData")
    public AjaxResult importLineData(@RequestParam("liveId") String liveId,MultipartFile file) throws Exception
    {
        ExcelUtil<LiveAutoTaskImportParam> util = new ExcelUtil<LiveAutoTaskImportParam>(LiveAutoTaskImportParam.class);
        List<LiveAutoTaskImportParam> list = util.importExcel(file.getInputStream());
        if(list.size()>12000){
            return new AjaxResult(500,"导入数据超出范围,最大12000条");
        }
        LiveAutoTask liveAutoTask;
        Date nowDate = DateUtils.getNowDate();
        Live live = liveMapper.selectLiveByLiveId(Long.parseLong(liveId));
        for (LiveAutoTaskImportParam liveAutoTaskImportParam : list) {
            if(StringUtils.isEmpty(liveAutoTaskImportParam.getTaskName()) || StringUtils.isEmpty(liveAutoTaskImportParam.getRegisterDate()) || StringUtils.isEmpty(liveAutoTaskImportParam.getContent())) continue;
            liveAutoTask = new LiveAutoTask();
            liveAutoTask.setLiveId(Long.parseLong(liveId));
            liveAutoTask.setTaskName(liveAutoTaskImportParam.getTaskName());
            liveAutoTask.setTaskType(3L);
            liveAutoTask.setTriggerType(2L);
            liveAutoTask.setTriggerValue(formatTime(liveAutoTaskImportParam.getRegisterDate()));
            liveAutoTask.setContent(liveAutoTaskImportParam.getContent());
            liveAutoTask.setAbsValue(getTriggerValue(liveAutoTask.getTriggerValue(),live.getStartTime()));
            liveAutoTask.setCreateTime(nowDate);
            liveAutoTask.setUpdateTime(nowDate);
            liveAutoTask.setStatus(1L);
            liveAutoTask.setFinishStatus(0L);
            liveAutoTaskService.directInsertLiveAutoTask(liveAutoTask);
        }
        return AjaxResult.success();
    }

    public static Date formatTime(String duration) {
        String[] parts = duration.split(":");
        if (parts.length != 3) {
            throw new IllegalArgumentException("时间格式不正确，应为 hh:mm:ss");
        }
        int hours = Integer.parseInt(parts[0]);
        int minutes = Integer.parseInt(parts[1]);
        int seconds = Integer.parseInt(parts[2]);

        // 获取当前日期的Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 设置时分秒
        calendar.set(Calendar.HOUR_OF_DAY, hours); // 24小时制
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, 0); // 毫秒设为0

        return calendar.getTime();
    }

    private Date getTriggerValue(Date triggerValue, LocalDateTime liveStartTime) {
        LocalDateTime triggerDateTime = LocalDateTime.ofInstant(
                triggerValue.toInstant(),
                ZoneId.systemDefault()
        );
        LocalTime triggerTime = triggerDateTime.toLocalTime();
        LocalDateTime combinedTime = liveStartTime
                .plusHours(triggerTime.getHour())
                .plusMinutes(triggerTime.getMinute())
                .plusSeconds(triggerTime.getSecond());
        return Date.from(combinedTime.atZone(ZoneId.systemDefault()).toInstant());
    }
}
