package com.fs.company.controller.course;

import cn.hutool.core.util.ObjectUtil;
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.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
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.CompanyRedPacketParam;
import com.fs.course.param.FsBatchPeriodRedPackageParam;
import com.fs.course.param.PeriodCountParam;
import com.fs.course.param.PeriodStatisticCountParam;
import com.fs.course.service.IFsUserCoursePeriodDaysService;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.service.IFsUserCourseVideoRedPackageService;
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.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.his.vo.OptionsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.openapi.tool.fastjson.JSON;
import com.hc.openapi.tool.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.*;


/**
 * 会员营期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;
    private final TokenService tokenService;

    /**
     * 查询会员营期列表
     */
//    @PreAuthorize("@ss.hasPermi('course:period:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserCoursePeriod fsUserCoursePeriod)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsUserCoursePeriodList(fsUserCoursePeriod);
        return getDataTable(list);
    }


    /**
     * @Description: 营期key value 值
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/11/18 14:59
     */
    @GetMapping("/listLabel")
    public TableDataInfo listLabel(FsUserCoursePeriod fsUserCoursePeriod)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        List<SysDictData> list = fsUserCoursePeriodService.selectFsUserCoursePeriodListLabel(fsUserCoursePeriod);
        return getDataTable(list);
    }


    @PostMapping("/page")
    @ApiOperation("自定义查询主列表分页")
    public R pageList(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        if (ObjectUtil.isNotEmpty(fsUserCoursePeriod.getTrainingCampId())){
            throw new CustomException("训练营不能为空！");
        }
//        startPage();
        PageHelper.startPage(fsUserCoursePeriod.getPageNum(), fsUserCoursePeriod.getPageSize());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyIdList(Collections.singletonList(loginUser.getCompany().getCompanyId()));
        List<FsUserCoursePeriodVO> list = fsUserCoursePeriodService.selectFsUserCoursePeriodPage(fsUserCoursePeriod);
        // 使用Stream API的简洁写法
        Long currentCompanyId = loginUser.getCompany().getCompanyId();
        for (FsUserCoursePeriodVO vo : list) {
            String isNeedRegisterMember = vo.getIsNeedRegisterMember();

            if (StringUtils.isNotEmpty(isNeedRegisterMember)) {
                boolean containsCurrentCompany = Arrays.stream(isNeedRegisterMember.split(","))
                        .map(String::trim)
                        .anyMatch(id -> id.equals(String.valueOf(currentCompanyId)));
                vo.setIsNeedRegisterMember(containsCurrentCompany ? "1" : "0");
            } else {
                vo.setIsNeedRegisterMember("0");
            }

            // 看课休息判断
            if(StringUtils.isNotBlank(vo.getIsOpenRestFlag())){
                JSONObject  jsonObject= JSON.parseObject(vo.getIsOpenRestFlag());
                vo.setIsOpenRestReminder(Integer.parseInt(jsonObject.get(currentCompanyId.toString()).toString()));
            }else {
                vo.setIsOpenRestReminder(null);
            }

        }
        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)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        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 AjaxResult add(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        if (ObjectUtil.isNotEmpty(fsUserCoursePeriod.getTrainingCampId())){
            throw new CustomException("训练营不能为空！");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        return toAjax(fsUserCoursePeriodService.insertFsUserCoursePeriod(fsUserCoursePeriod));
    }

    /**
     * 修改会员营期
     */
    @PreAuthorize("@ss.hasPermi('course:period:edit')")
    @Log(title = "会员营期", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsUserCoursePeriod.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        return toAjax(fsUserCoursePeriodService.updateFsUserCoursePeriod(fsUserCoursePeriod));
    }
    /**
     * 修改会员营期单独注册状态
     */
    @PreAuthorize("@ss.hasPermi('course:period:edit')")
    @Log(title = "会员营期", businessType = BusinessType.UPDATE)
    @PutMapping("/editIsNeedRegisterMember")
    public AjaxResult editIsNeedRegisterMember(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        FsUserCoursePeriod fsUserCoursePeriod1 = fsUserCoursePeriodService.selectFsUserCoursePeriodById(fsUserCoursePeriod.getPeriodId());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (ObjectUtil.isEmpty(fsUserCoursePeriod.getIsNeedRegisterMember())){
            throw new CustomException("修改失败！");
        }

        return toAjax(fsUserCoursePeriodService.editIsNeedRegisterMember(fsUserCoursePeriod,loginUser.getCompany().getCompanyId().toString()));

    }

    @PreAuthorize("@ss.hasPermi('course:period:edit')")
    @Log(title = "会员营期", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePeriodIsOpenRestReminder")
    public AjaxResult updatePeriodIsOpenRestReminder(@RequestBody FsUserCoursePeriod fsUserCoursePeriod)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return toAjax(fsUserCoursePeriodService.updatePeriod(fsUserCoursePeriod,loginUser.getCompany().getCompanyId()));

    }

    /**
     * 删除会员营期
     */
    @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 TableDataInfo getDays(FsUserCoursePeriodDays fsUserCoursePeriodDays){
        startPage();
        FsUserCoursePeriod period = fsUserCoursePeriodService.selectFsUserCoursePeriodById(fsUserCoursePeriodDays.getPeriodId());
        fsUserCoursePeriodDays.setMaxDate(LocalDate.now().plusDays(period.getMaxViewNum()));
        List<FsUserCoursePeriodDays> list = fsUserCoursePeriodDaysService.selectFsUserCoursePeriodDaysList(fsUserCoursePeriodDays);
        return getDataTable(list);
    }

    @PostMapping("/addCourse")
    public R addCourse(@RequestBody FsUserCoursePeriodDays entity){
        return fsUserCoursePeriodDaysService.addCourse(entity);
    }
    @PostMapping("/updateCourseTime")
    public R updateCourseTime(@RequestBody UpdateCourseTimeVo vo){
        return fsUserCoursePeriodDaysService.updateCourseTime(vo);
    }
    @PostMapping("/updateCourseDate")
    public R updateCourseDate(@RequestBody UpdateCourseTimeVo vo){
        return fsUserCoursePeriodDaysService.updateCourseDate(vo);
    }
    @PostMapping("/updateListCourseData")
    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);
    }

    @ApiOperation("按课程批量保存设置红包金额")
    @PostMapping("/batchRedPacket")
    @Log(title = "按课程批量保存设置红包金额", businessType = BusinessType.UPDATE)
    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();
    }

    @ApiOperation("按营期批量保存设置红包金额")
    @PostMapping("/batchRedPacket/byPeriod")
    @Log(title = "按营期批量保存设置红包金额", businessType = BusinessType.UPDATE)
    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());
        FsUserCoursePeriod period = fsUserCoursePeriodService.selectFsUserCoursePeriodById(param.getPeriodId());
        param.setMaxDate(LocalDate.now().plusDays(period.getMaxViewNum()));
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        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);
    }

    @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));
    }

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

    @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);
    }
}
