package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeClassManage;
import shop.alien.entity.store.excelVo.util.ExcelExporter;
import shop.alien.entity.store.vo.LifeClassManageVo;
import shop.alien.mapper.LifeClassManageMapper;
import shop.alien.storeplatform.service.PlatformClassService;
import shop.alien.storeplatform.util.FileUploadUtil;
import shop.alien.util.common.VideoDurationFFmpeg;
import shop.alien.util.common.VideoUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PlatformClassServiceImpl implements PlatformClassService {

    private final LifeClassManageMapper lifeClassManageMapper;

    private final FileUploadUtil fileUploadUtil;

    private final VideoUtils videoUtils;

    @Value("${spring.web.resources.static-locations}")
    private String uploadDir;

    @Value("${spring.web.resources.url}")
    private String fileUrl;

    /**
     * 懒得查, 留着导出Excel
     */
    List<LifeClassManage> toExcel = new ArrayList<>();

    @Override
    public IPage<LifeClassManage> getClassManageList(int page, int size, String className, String classTeacher, String classBigType) {
        LambdaQueryWrapper<LifeClassManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(className), LifeClassManage::getClassName, className);
        queryWrapper.like(StringUtils.isNotEmpty(classTeacher), LifeClassManage::getClassTeacher, classTeacher);
        queryWrapper.like(StringUtils.isNotEmpty(classBigType), LifeClassManage::getClassBigType, classBigType);
        queryWrapper.orderByDesc(LifeClassManage::getCreatedTime);
        IPage<LifeClassManage> iPageList = lifeClassManageMapper.selectPage(new Page<>(page, size), queryWrapper);
        List<LifeClassManageVo> newRecords = new ArrayList<>();
        //处理视频时长
        for (LifeClassManage record : iPageList.getRecords()) {
            /*String classLength = record.getClassLength();
            String s = convertMilliseconds(Long.parseLong(classLength));
            record.setClassLength(s);*/
            //处理文件名称
            //获取视频地址
            String videoPath = record.getVideoPath();
            //根据视频地址获取文件名称
            String fileNameFromUrl = VideoDurationFFmpeg.getFileNameFromUrl(videoPath);
            record.setFileName(fileNameFromUrl);
        }
        toExcel = iPageList.getRecords();
        return iPageList;
    }

    @Override
    public int addOrUpdateClassManage(LifeClassManage lifeClassManage) throws IOException, InterruptedException {
        //获取视频地址
        String videoPath = lifeClassManage.getVideoPath();
        //根据视频地址获取文件名称
        /*String fileNameFromUrl = VideoDurationFFmpeg.getFileNameFromUrl(videoPath);
        //获取时长毫秒数
        long videoDuration = VideoDurationFFmpeg.getVideoDuration(uploadDir + "/video/" + fileNameFromUrl);
        lifeClassManage.setClassLength(videoDuration + "");*/
        if (StringUtils.isEmpty(lifeClassManage.getId())) {
            return lifeClassManageMapper.insert(lifeClassManage);
        } else {
            return lifeClassManageMapper.updateById(lifeClassManage);
        }
    }

    @Override
    public LifeClassManage getClassManageById(Integer id) {
        return lifeClassManageMapper.selectById(id);
    }

    public int setClassState(Integer id, String classState) {
        LambdaUpdateWrapper<LifeClassManage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LifeClassManage::getId, id).set(LifeClassManage::getClassState, classState);
        return lifeClassManageMapper.update(null, updateWrapper);
    }

    public int deleteClassById(Integer id) {
        return lifeClassManageMapper.deleteById(id);
    }

    @Override
    public ResponseEntity<byte[]> exportToExcel(String className, String classTeacher, String classBigType) {
        try {
            LambdaQueryWrapper<LifeClassManage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StringUtils.isNotEmpty(className), LifeClassManage::getClassName, className);
            queryWrapper.like(StringUtils.isNotEmpty(classTeacher), LifeClassManage::getClassTeacher, classTeacher);
            queryWrapper.like(StringUtils.isNotEmpty(classBigType), LifeClassManage::getClassBigType, classBigType);
            queryWrapper.orderByDesc(LifeClassManage::getCreatedTime);
            List<LifeClassManage> list = lifeClassManageMapper.selectList(queryWrapper);
            String[] headers = {"课程名称", "课程时长", "培训老师", "浏览量", "课程类型", "创建时间", "状态"};
            byte[] excelData = ExcelExporter.exportToExcel(list, headers, "课程列表清单");
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.add("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("课程列表清单.xlsx") + "\";charset=utf-8");
            responseHeaders.set("Charset", "UTF-8");
            return new ResponseEntity<>(excelData, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertMilliseconds(long milliseconds) {
        // 计算小时数
        long hours = milliseconds / 3600000;
        // 计算剩余的毫秒数
        milliseconds %= 3600000;
        // 计算分钟数
        long minutes = milliseconds / 60000;
        // 再次计算剩余的毫秒数
        milliseconds %= 60000;
        // 计算秒数
        long seconds = milliseconds / 1000;

        // 格式化输出
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}
