package com.fs.course.controller;

import com.fs.baidu.domain.BdAccount;
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.domain.entity.SysDictData;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.domain.FsUserCoursePeriodDays;
import com.fs.course.domain.FsUserCourseVideoRedPackage;
import com.fs.course.param.*;
import com.fs.course.service.IFsUserCoursePeriodDaysService;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.service.IFsUserCourseVideoRedPackageService;
import com.fs.course.vo.*;
import com.fs.course.vo.newfs.FsCourseAnalysisCountVO;
import com.fs.course.vo.FsPeriodCountVO;
import com.fs.course.vo.FsUserCoursePeriodVO;
import com.fs.course.vo.PeriodRedPacketVO;
import com.fs.course.vo.UpdateCourseTimeVo;
import com.fs.course.vo.newfs.FsCourseAnalysisCountVO;
import com.fs.his.vo.OptionsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 会员营期Controller
 *
 * @author fs
 * @date 2025-04-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/course/period")
@Slf4j
public class FsUserCoursePeriodController extends BaseController {

    private final IFsUserCoursePeriodService fsUserCoursePeriodService;
    private final IFsUserCoursePeriodDaysService fsUserCoursePeriodDaysService;
    private final IFsUserCourseVideoRedPackageService fsUserCourseVideoRedPackageService;

    /**
     * 查询会员营期列表
     */
//    @PreAuthorize("@ss.hasPermi('course:period:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserCoursePeriod fsUserCoursePeriod)
    {
        startPage();
        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsUserCoursePeriodList(fsUserCoursePeriod);
        return getDataTable(list);
    }
    /**
     * @Description: 营期key value 值
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/11/18 14:59
     */
    @GetMapping("/listLabel/{companyId}")
    public TableDataInfo listLabel(@PathVariable("companyId") Long companyId)
    {
        FsUserCoursePeriod fsUserCoursePeriod = new FsUserCoursePeriod();
        fsUserCoursePeriod.setCompanyId(companyId + "");
        startPage();
        List<SysDictData> list = fsUserCoursePeriodService.selectFsUserCoursePeriodListLabel(fsUserCoursePeriod);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('course:period:list')")
    @PostMapping("/page")
    @ApiOperation("自定义查询主列表分页")
    public R pageList(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
//        startPage();
        PageHelper.startPage(fsUserCoursePeriod.getPageNum(), fsUserCoursePeriod.getPageSize());
        List<FsUserCoursePeriodVO> list = fsUserCoursePeriodService.selectFsUserCoursePeriodPage(fsUserCoursePeriod);
        PageInfo<FsUserCoursePeriodVO> pageInfo = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return R.ok(result);
//        return getDataTable(list);
    }

    /**
     * 导出会员营期列表
     */
//    @PreAuthorize("@ss.hasPermi('course:period:export')")
    @Log(title = "会员营期", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsUserCoursePeriod fsUserCoursePeriod)
    {
        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsUserCoursePeriodList(fsUserCoursePeriod);
        ExcelUtil<FsUserCoursePeriod> util = new ExcelUtil<FsUserCoursePeriod>(FsUserCoursePeriod.class);
        return util.exportExcel(list, "userCoursePeriod");
    }

    /**
     * 获取会员营期详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:period:query')")
    @GetMapping(value = "/{periodId}")
    public AjaxResult getInfo(@PathVariable("periodId") Long periodId) {
        return AjaxResult.success(fsUserCoursePeriodService.selectFsUserCoursePeriodById(periodId));
    }

    /**
     * 新增会员营期
     */
    @PreAuthorize("@ss.hasPermi('course:period:add')")
    @Log(title = "会员营期", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody FsUserCoursePeriod fsUserCoursePeriod) {
        if (fsUserCoursePeriod == null) {
            return R.error("营期信息不能为空");
        }
        if (fsUserCoursePeriod.getCourseId() == null) {
            boolean isSuccess = fsUserCoursePeriodService.insertFsUserCoursePeriod(fsUserCoursePeriod) > 0;
            return isSuccess ? R.ok("营期新增成功") : R.error("营期新增失败");
        } else {
            return fsUserCoursePeriodService.insertFsUserCoursePeriodAndCourse(fsUserCoursePeriod);
        }
    }

    /**
     * 修改会员营期
     */
    @PreAuthorize("@ss.hasPermi('course:period:edit')")
    @Log(title = "会员营期", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        return toAjax(fsUserCoursePeriodService.updateFsUserCoursePeriod(fsUserCoursePeriod));
    }

    /**
     * 删除会员营期
     */
    @PreAuthorize("@ss.hasPermi('course:period:remove')")
    @Log(title = "会员营期", businessType = BusinessType.DELETE)
	@DeleteMapping("/{periodIds}")
    public AjaxResult remove(@PathVariable Long[] periodIds)
    {
        return toAjax(fsUserCoursePeriodService.deleteFsUserCoursePeriodByIds(periodIds));
    }

    @GetMapping("/getDays")
    public R getDays(FsUserCoursePeriodDays fsUserCoursePeriodDays){
//        startPage();
        //PageHelper.startPage(fsUserCoursePeriodDays.getPageNum(), fsUserCoursePeriodDays.getPageSize());
        List<FsUserCoursePeriodDays> list = fsUserCoursePeriodDaysService.selectFsUserCoursePeriodDaysList(fsUserCoursePeriodDays);

        PageInfo<FsUserCoursePeriodDays> pageInfo = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return R.ok(result);
    }
    @GetMapping("/getSortDays")
    public R getSortDays(FsUserCoursePeriodDays fsUserCoursePeriodDays){
        PageHelper.startPage(fsUserCoursePeriodDays.getPageNum(), fsUserCoursePeriodDays.getPageSize());
        List<FsUserCoursePeriodDays> list = fsUserCoursePeriodDaysService.selectFsUserCoursePeriodDaysList(fsUserCoursePeriodDays);

        PageInfo<FsUserCoursePeriodDays> pageInfo = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return R.ok(result);
    }

    @PreAuthorize("@ss.hasPermi('course:period:addCourse')")
    @PostMapping("/addCourse")
    @ApiOperation("添加单个课程小节")
    public R addCourse(@RequestBody FsUserCoursePeriodDays entity){
        return fsUserCoursePeriodDaysService.addCourse(entity);
    }

    @PreAuthorize("@ss.hasPermi('course:period:addCourse')")
    @PostMapping("/batchAddCourseSections")
    @ApiOperation("一键批量添加课程小节")
    public R batchAddCourseSections(@Validated @RequestBody BatchAddCourseSectionParam param) {
        try {
            logger.info("开始批量添加课程小节，营期ID：{}，课程ID：{}，视频数量：{}，视频ID列表：{}",
                param.getPeriodId(), param.getCourseId(), param.getVideoIds().size(), param.getVideoIds());
            return fsUserCoursePeriodDaysService.batchAddCourseSections(param);
        } catch (Exception e) {
            logger.error("批量添加课程小节失败，营期ID：{}，错误信息：{}", param.getPeriodId(), e.getMessage(), e);
            return R.error("批量添加课程小节失败：" + e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('course:period:dayRemove')")
    @Log(title = "会员营期课程删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/day/{ids}")
    public AjaxResult dayRemove(@PathVariable Long[] ids)
    {
        return toAjax(fsUserCoursePeriodDaysService.deleteFsUserCoursePeriodDaysByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('course:period:updateCourseTime')")
    @PostMapping("/updateCourseTime")
    @Log(title = "会员营期修改课程时间", businessType = BusinessType.UPDATE)
    public R updateCourseTime(@RequestBody UpdateCourseTimeVo vo){
        return fsUserCoursePeriodDaysService.updateCourseTime(vo);
    }
    @PostMapping("/updateCourseDate")
    @Log(title = "会员营期修改CourseDate", businessType = BusinessType.UPDATE)
    public R updateCourseDate(@RequestBody UpdateCourseTimeVo vo){
        return fsUserCoursePeriodDaysService.updateCourseDate(vo);
    }
    @PostMapping("/updateListCourseData")
    @Log(title = "会员营期修改ListCourseData", businessType = BusinessType.UPDATE)
    public R updateListCourseData(@RequestBody List<FsUserCoursePeriodDays> entity){
        return fsUserCoursePeriodDaysService.updateListCourseData(entity);
    }

    @ApiOperation("根据营期id获取公司红包金额列表(暂废弃)")
    @GetMapping("/companyList")
    public R getCompanyByPeriod(Long periodId, Long videoId) {
        List<CompanyRedPacketParam> companyList = fsUserCoursePeriodDaysService.getCompanyByPeriod(periodId, videoId);
        return R.ok().put("data", companyList);
    }

    @ApiOperation("获取设置红包金额列表")
    @GetMapping("/redPacketList")
    public R getPeriodRedPacketList(Long periodId, Long companyId) {
        List<PeriodRedPacketVO> periodRedPacketList = fsUserCoursePeriodDaysService.getPeriodRedPacketList(periodId, companyId);
        return R.ok().put("data", periodRedPacketList);
    }

    @Log(title = "按课程批量保存设置红包金额", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('course:period:setCourseRedPacket')")
    @ApiOperation("按课程批量保存设置红包金额")
    @PostMapping("/batchRedPacket")
    public R batchRedPacketMoney(@RequestBody List<FsUserCourseVideoRedPackage> videoRedPackageList) {
        try {
            fsUserCourseVideoRedPackageService.batchSaveCompanyRedPackage(videoRedPackageList);
        } catch (Exception e) {
            logger.error("按课程批量保存设置红包金额-失败！，营期id：{}", videoRedPackageList.get(0).getPeriodId());
            return R.error("保存失败！");
        }
        return R.ok();
    }

    @Log(title = "按营期批量保存设置红包金额", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('course:period:setRedPacket')")
    @ApiOperation("按营期批量保存设置红包金额")
    @PostMapping("/batchRedPacket/byPeriod")
    public R batchRedPacketByPeriod(@RequestBody List<FsBatchPeriodRedPackageParam> periodRedPackageList) {
        try {
            fsUserCourseVideoRedPackageService.batchRedPacketByPeriod(periodRedPackageList);
        } catch (Exception e) {
            logger.error("按营期批量保存设置红包金额-失败！，入参：{}", periodRedPackageList);
            return R.error("保存失败！");
        }
        return R.ok();
    }

    @PostMapping("/periodCount")
    @ApiOperation("营期统计")
    public R periodCourseCount(@RequestBody PeriodCountParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsPeriodCountVO> list = fsUserCoursePeriodDaysService.periodCourseCount(param);
        long count = fsUserCoursePeriodDaysService.periodCourseByCount(param);
        PageInfo<FsPeriodCountVO> pageInfo = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", pageInfo.getList());
        result.put("total", count);
        return R.ok(result);
    }

    /**
     * @Description: 会员营期导出课程统计
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/12/12 11:37
     */
    @PostMapping("/exportInfo")
    @ApiOperation("营期统计")
    public AjaxResult exportInfo(@RequestBody PeriodCountParam param) {
        List<FsPeriodCountExportVO> exportList = new ArrayList<>();
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsPeriodCountVO> list = fsUserCoursePeriodDaysService.periodCourseCount(param);
        list.forEach(item -> {
            FsPeriodCountExportVO exportVO = new FsPeriodCountExportVO();
            exportVO.setTitle(item.getTitle());
            exportVO.setDayDate(item.getDayDate());
            if(item.getCountDetailsVO() != null){
                FsCourseAnalysisCountVO countDetailsVO =item.getCountDetailsVO();
                exportVO.setCourseWatchTimes(countDetailsVO.getCourseWatchTimes());
                exportVO.setCourseCompleteTimes(countDetailsVO.getCourseCompleteTimes());
                exportVO.setCourseWatchNum(countDetailsVO.getCourseWatchNum());
                exportVO.setCourseCompleteNum(countDetailsVO.getCourseCompleteNum());
                exportVO.setCompleteRate(countDetailsVO.getCompleteRate()+"%");
                exportVO.setAnswerTimes(countDetailsVO.getAnswerTimes());
                exportVO.setAnswerNum(countDetailsVO.getAnswerNum());
                exportVO.setAnswerRightNum(countDetailsVO.getAnswerRightNum());
                exportVO.setAnswerRightRate(countDetailsVO.getAnswerRightRate()+"%");
                exportVO.setRedPacketNum(countDetailsVO.getRedPacketNum());
                exportVO.setRedPacketAmount(countDetailsVO.getRedPacketAmount());
            }
            exportList.add(exportVO);
        });

        ExcelUtil<FsPeriodCountExportVO> util = new ExcelUtil<FsPeriodCountExportVO>(FsPeriodCountExportVO.class);
        return util.exportExcel(exportList, "百度账号数据");
    }

    @GetMapping("/getPeriodListLikeName")
    public R getPeriodListLikeName(@RequestParam(required = false) String name,
                                   @RequestParam(required = false) Long campId,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String,Object> params = new HashMap<>();
        params.put("name", name);
        params.put("campId", campId);

        PageHelper.startPage(pageNum, pageSize);
        List<OptionsVO> periodList = fsUserCoursePeriodDaysService.selectPeriodListByMap(params);
        return R.ok().put("data", new PageInfo<>(periodList));
    }

    @PreAuthorize("@ss.hasPermi('course:period:courseMove')")
    @ApiOperation("营期课程-上移/下移")
    @PutMapping("/courseMove")
    public R periodCourseMove(Long id, Long targetId) {
        return fsUserCoursePeriodDaysService.periodCourseMove(id, targetId);
    }

    @PreAuthorize("@ss.hasPermi('course:period:close')")
    @ApiOperation("结束营期")
    @PostMapping("/closePeriod")
    public R closePeriod(Long id) {
        fsUserCoursePeriodService.closePeriod(id);
        return R.ok();
    }

    @PostMapping("/periodCourseStatisticCount")
    @ApiOperation("会员详情训练营数据总览")
    public R periodCourseStatisticCount(@RequestBody PeriodStatisticCountParam param) {
        if (param == null) {
            return R.error("请求参数不能为空！");
        }
        return R.ok().put("data", fsUserCoursePeriodService.periodCourseStatisticCount(param));
    }

    @PostMapping("/periodlist")
    public R periodList(@RequestBody PeriodStatisticCountParam param)
    {
        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsPeriodlist(param);
        return R.ok().put("data", list);
    }

    @PreAuthorize("@ss.hasPermi('course:period:setCompanyRedPacket')")
    @ApiOperation("按公司批量保存设置红包金额")
    @Log(title = "按公司批量保存设置红包金额", businessType = BusinessType.UPDATE)
    @PostMapping("/batchRedPacket/byCompany")
    public R batchRedPacketByCompany(@Validated @RequestBody BatchCompanyRedPackageParam param) {
        try {
            fsUserCourseVideoRedPackageService.batchRedPacketByCompany(param);
        } catch (Exception e) {
            logger.error("按恭送批量保存设置红包金额-失败！，入参：{}", param);
            return R.error("保存失败！");
        }
        return R.ok();
    }

    @ApiOperation("复制创建成功的营期和对应营期中的看课")
    @PostMapping("/copyExistCampPeriod")
    public R copyExistCampPeriod(@RequestBody PeriodStatisticCountParam param){
        R result = fsUserCoursePeriodService.copyFsUserCoursePeriodAndCourse(param);
        return result;
    }

}
