package com.fs.course.controller;

import java.util.*;
import java.math.BigDecimal;
import java.util.*;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.PageDomain;
import com.fs.common.core.page.TableSupport;
import com.fs.common.utils.ServletUtils;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.mapper.FsUserCourseMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.param.FsCourseRedPacketLogParam;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.vo.FsCourseRedPacketLogListPVO;
import com.fs.course.vo.FsCourseRedPacketLogListVO;
import com.fs.framework.web.service.TokenService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.OptionsVO;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.course.domain.FsCourseRedPacketLog;
import com.fs.course.service.IFsCourseRedPacketLogService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

import static com.fs.his.utils.PhoneUtil.encryptPhone;

/**
 * 短链课程看课记录Controller
 *
 * @author fs
 * @date 2024-10-24
 */
@RestController
@RequestMapping("/course/courseRedPacketLog")
public class FsCourseRedPacketLogController extends BaseController
{
    @Autowired
    private IFsCourseRedPacketLogService fsCourseRedPacketLogService;

    @Autowired
    private IFsUserCoursePeriodService fsUserCoursePeriodService;
    @Autowired
    FsUserCourseMapper fsUserCourseMapper;
    @Autowired
    TokenService tokenService;
    @Autowired
    ISysConfigService configService;
    @Autowired
    FsUserCourseVideoMapper fsUserCourseVideoMapper;
    /**
     * 查询短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:list')")
    @PostMapping("/list")
    public R list(@RequestBody FsCourseRedPacketLogParam fsCourseRedPacketLog)
    {
        if(fsCourseRedPacketLog.getPageNum() == null) {
            fsCourseRedPacketLog.setPageNum(1);
        }
        if(fsCourseRedPacketLog.getPageSize() == null) {
            fsCourseRedPacketLog.setPageSize(10);
        }


        if (fsCourseRedPacketLog.getPhoneMk() != null && fsCourseRedPacketLog.getPhoneMk() != "") {
            fsCourseRedPacketLog.setPhone(encryptPhone(fsCourseRedPacketLog.getPhoneMk()));
        }
        PageHelper.startPage(fsCourseRedPacketLog.getPageNum(), fsCourseRedPacketLog.getPageSize());

        List<FsCourseRedPacketLogListPVO> list = fsCourseRedPacketLogService.selectFsCourseRedPacketLogListVO(fsCourseRedPacketLog);
        for (FsCourseRedPacketLogListPVO fsCourseRedPacketLogListPVO : list) {
            if (ObjectUtil.isNotEmpty(fsCourseRedPacketLogListPVO.getPeriodId())){
                FsUserCoursePeriod fsUserCoursePeriod = fsUserCoursePeriodService.selectFsUserCoursePeriodById(fsCourseRedPacketLogListPVO.getPeriodId().longValue());
                fsCourseRedPacketLogListPVO.setPeriodName(fsUserCoursePeriod.getPeriodName());
            }
            fsCourseRedPacketLogListPVO.setPhone(PhoneUtil.decryptAutoPhoneMk(fsCourseRedPacketLogListPVO.getPhone()));
        }
        return R.ok().put("data",new PageInfo<>(list));
    }

    /**
     * 查询短链课程看课记录列表分页
     * 与上面请求方式不同，list集合数据在get传输掉包
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:pageList')")
    @PostMapping("/pageList")
    public R pageList(@RequestBody FsCourseRedPacketLogParam fsCourseRedPacketLog)
    {

        if (fsCourseRedPacketLog.getPhoneMk() != null && fsCourseRedPacketLog.getPhoneMk() != "") {
            fsCourseRedPacketLog.setPhone(encryptPhone(fsCourseRedPacketLog.getPhoneMk()));
        }

        // P0：无时间范围时默认近 7 天，避免无筛选 COUNT 全表扫描
        if (fsCourseRedPacketLog.getSTime() == null && fsCourseRedPacketLog.getETime() == null) {
            java.time.LocalDate end = java.time.LocalDate.now();
            java.time.LocalDate start = end.minusDays(6);
            fsCourseRedPacketLog.setSTime(java.sql.Timestamp.valueOf(start.atStartOfDay()));
            fsCourseRedPacketLog.setETime(java.sql.Timestamp.valueOf(end.atStartOfDay()));
        }

        PageHelper.startPage(fsCourseRedPacketLog.getPageNum(), fsCourseRedPacketLog.getPageSize());

        List<FsCourseRedPacketLogListPVO> list = fsCourseRedPacketLogService.selectFsCourseRedPacketLogListVO(fsCourseRedPacketLog);
        for (FsCourseRedPacketLogListPVO fsCourseRedPacketLogListPVO : list) {
            if (ObjectUtil.isNotEmpty(fsCourseRedPacketLogListPVO.getPeriodId())){
                FsUserCoursePeriod fsUserCoursePeriod = fsUserCoursePeriodService.selectFsUserCoursePeriodById(fsCourseRedPacketLogListPVO.getPeriodId().longValue());
                fsCourseRedPacketLogListPVO.setPeriodName(fsUserCoursePeriod.getPeriodName());
            }
            fsCourseRedPacketLogListPVO.setPhone(PhoneUtil.decryptAutoPhoneMk(fsCourseRedPacketLogListPVO.getPhone()));
        }

        return R.ok().put("data", new PageInfo<>(list));
    }

    /**
     * 导出短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:export')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(@RequestBody FsCourseRedPacketLogParam fsCourseRedPacketLog)
    {
        if (fsCourseRedPacketLog.getPhoneMk()!=null&&fsCourseRedPacketLog.getPhoneMk()!=""){
            fsCourseRedPacketLog.setPhone(encryptPhone(fsCourseRedPacketLog.getPhoneMk()));
        }
        List<FsCourseRedPacketLogListPVO> list = fsCourseRedPacketLogService.selectFsCourseRedPacketLogListVO(fsCourseRedPacketLog);
        for (FsCourseRedPacketLogListPVO fsCourseRedPacketLogListPVO : list) {
            if (ObjectUtil.isNotEmpty(fsCourseRedPacketLogListPVO.getPeriodId())){
                FsUserCoursePeriod fsUserCoursePeriod = fsUserCoursePeriodService.selectFsUserCoursePeriodById(fsCourseRedPacketLogListPVO.getPeriodId().longValue());
                fsCourseRedPacketLogListPVO.setPeriodName(fsUserCoursePeriod.getPeriodName());
            }
            fsCourseRedPacketLogListPVO.setPhone(PhoneUtil.decryptAutoPhoneMk(fsCourseRedPacketLogListPVO.getPhone()));
        }
        ExcelUtil<FsCourseRedPacketLogListPVO> util = new ExcelUtil<FsCourseRedPacketLogListPVO>(FsCourseRedPacketLogListPVO.class);
        return util.exportExcel(list, "短链课程看课记录数据");
    }

    /**
     * 获取短链课程看课记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:query')")
    @GetMapping(value = "/{logId}")
    public AjaxResult getInfo(@PathVariable("logId") Long logId)
    {
        return AjaxResult.success(fsCourseRedPacketLogService.selectFsCourseRedPacketLogByLogId(logId));
    }

    /**
     * 新增短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:add')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCourseRedPacketLog fsCourseRedPacketLog)
    {
        return toAjax(fsCourseRedPacketLogService.insertFsCourseRedPacketLog(fsCourseRedPacketLog));
    }

    /**
     * 修改短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:edit')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCourseRedPacketLog fsCourseRedPacketLog)
    {
        return toAjax(fsCourseRedPacketLogService.updateFsCourseRedPacketLog(fsCourseRedPacketLog));
    }

    /**
     * 删除短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:remove')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{logIds}")
    public AjaxResult remove(@PathVariable Long[] logIds)
    {
        return toAjax(fsCourseRedPacketLogService.deleteFsCourseRedPacketLogByLogIds(logIds));
    }

    /**
     * 查询课程列表（三级联动第一级）
     */
    @GetMapping("/courseList")
    public R courseList()
    {
        // 总后台查询所有课程，不受公司限制
        List<OptionsVO> optionsVOS = fsUserCourseMapper.selectFsUserCourseAllList();
        return R.ok().put("list", optionsVOS);
    }

    /**
     * 根据课程ID和营期名称模糊查询营期列表（三级联动第二级）
     */
    @GetMapping("/period")
    public R getPeriodListLikeName(String periodName, Long courseId)
    {
        // 总后台查询所有营期，传入null表示不限制公司
        List<OptionsVO> list = fsCourseRedPacketLogService.getPeriodListLikeName(periodName, courseId, null);
        return R.ok().put("data", list);
    }

    /**
     * 根据营期ID查询视频列表（三级联动第三级）
     */
    @GetMapping(value = "/videoList/{id}")
    public R videoList(@PathVariable("id") Long id)
    {
        List<OptionsVO> optionsVOS = fsUserCourseVideoMapper.selectVideoListByPeriodId(id);
        return R.ok().put("list", optionsVOS);
    }

    /**
     * 查询课程列表（企微用户绑定课程）
     */
    @GetMapping("/qwcourseList")
    public R qwcourseList()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        List<OptionsVO> optionsVOS;
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            optionsVOS = fsUserCourseMapper.selectFsUserCourseAllListByUserId(userId);
        }else{
            optionsVOS = fsUserCourseMapper.selectFsUserCourseAllList();
        }
        return R.ok().put("list", optionsVOS);
    }

    @GetMapping("/courseListByCompanyId/{companyId}")
    public R courseListByCompanyId(@PathVariable("companyId") Long companyId)
    {
        List<OptionsVO> optionsVOS = fsUserCourseMapper.selectFsUserCourseByCompany(companyId);
        return R.ok().put("list", optionsVOS);
    }


    @GetMapping(value = "/qwvideoList/{id}")
    public R qwvideoList(@PathVariable("id") Long id)
    {
        List<OptionsVO> optionsVOS = fsUserCourseVideoMapper.selectFsUserCourseVodeAllList(id);
        return R.ok().put("list", optionsVOS);
    }


    /**
     * 红包消耗统计
     * @param fsCourseRedPacketLog
     * @return
     */
    @GetMapping("/getReadPackageTotal")
    public TableDataInfo getReadPackageTotal(FsCourseRedPacketLog fsCourseRedPacketLog) {

        List<FsCourseRedPacketLogListPVO> list = fsCourseRedPacketLogService.getReadPackageTotal(fsCourseRedPacketLog);
        FsCourseRedPacketLogListPVO fsCourseRedPacketLogListPVO = new FsCourseRedPacketLogListPVO();
        fsCourseRedPacketLogListPVO.setCompanyName("合计");
        BigDecimal totalAmount = list.stream()
                .map(item -> item.getAmount())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        fsCourseRedPacketLogListPVO.setAmount(totalAmount);
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        int total = list.size();

        if (pageNum != null && pageSize != null) {
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);
            // 确保索引不越界
            if (fromIndex < total) {
                list = list.subList(fromIndex, toIndex);
            } else {
                list = new ArrayList<>(); // 返回空列表
            }
        }
        list.add(fsCourseRedPacketLogListPVO); // 将合计行添加到列表末尾
        // 构造返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }



    /**
    * 红包消耗统计
    */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:countList')")
    @PostMapping("/getRedPacketLogCount")
    public R getRedPacketLogCount(@RequestBody FsCourseRedPacketLogParam fsCourseRedPacketLog){

        PageHelper.startPage(fsCourseRedPacketLog.getPageNum(), fsCourseRedPacketLog.getPageSize());

        List<FsCourseRedPacketLogListVO> list = fsCourseRedPacketLogService.selectFsCourseRedPacketLogListCountVO(fsCourseRedPacketLog);


        return R.ok().put("data", new PageInfo<>(list));
    }


    /**
     * 导出短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseRedPacketLog:countExport')")
    @Log(title = "红包消耗统计导出", businessType = BusinessType.EXPORT)
    @PostMapping("/countExport")
    public AjaxResult countExport(@RequestBody FsCourseRedPacketLogParam fsCourseRedPacketLog)
    {

        List<FsCourseRedPacketLogListVO> list = fsCourseRedPacketLogService.selectFsCourseRedPacketLogListCountVO(fsCourseRedPacketLog);

        ExcelUtil<FsCourseRedPacketLogListVO> util = new ExcelUtil<FsCourseRedPacketLogListVO>(FsCourseRedPacketLogListVO.class);
        return util.exportExcel(list, "红包消耗统计导出");
    }

}
