package com.fs.course.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.annotation.Log;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.SortUtils;
import com.fs.common.utils.StringUtils;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.domain.FsUserCourseTrainingCamp;
import com.fs.course.dto.FsUserCourseTrainingCampDTO;
import com.fs.course.dto.FsUserCourseTrainingCampUpdateDTO;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.service.IFsUserCourseTrainingCampService;
import com.fs.course.vo.FsUserCoursePeriodVO;
import com.fs.course.vo.FsUserCourseTrainingCampVO;
import com.fs.framework.web.service.TokenService;
import com.fs.his.vo.OptionsVO;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/course/trainingCamp")
@AllArgsConstructor
public class FsUserCourseTrainingCampController {

    private final IFsUserCourseTrainingCampService fsUserCourseTrainingCampService;
    private final TokenService tokenService;

    private final ISysConfigService configService;
    private final IFsUserCoursePeriodService fsUserCoursePeriodService;

    /**
     * 查询训练营列表
     */
    @PreAuthorize("@ss.hasPermi('course:trainingCamp:list')")
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(required = false) String trainingCampName,
                           @RequestParam(required = false) String userId,
                           @RequestParam String scs,
                           @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                           @RequestParam(required = false, defaultValue = "10") Integer pageSize)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("trainingCampName", trainingCampName);
        params.put("scs", SortUtils.parseSort(scs));
        params.put("userId", userId);

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userIds = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            params.put("userIds", userIds);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<FsUserCourseTrainingCampVO> list = fsUserCourseTrainingCampService.selectFsUserCourseTrainingCampVOListByMap(params);
        return AjaxResult.success(new PageInfo<>(list));
    }

    /**
     * 新增训练营
     * @param params    参数
     * @return  AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('course:trainingCamp:add')")
    @Log(title = "训练营", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody FsUserCourseTrainingCampDTO params) {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userIds = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsUserCourseTrainingCampService.add(params,userIds);
            return AjaxResult.success();
        }
        fsUserCourseTrainingCampService.add(params,null);
        return AjaxResult.success();
    }

    /**
     * 修改训练营
     * @param params    参数
     * @return  AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('course:trainingCamp:edit')")
    @Log(title = "训练营", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody FsUserCourseTrainingCampUpdateDTO params) {
        FsUserCourseTrainingCamp trainingCamp = fsUserCourseTrainingCampService.getById(params.getTrainingCampId());
        if (Objects.isNull(trainingCamp)) {
            return AjaxResult.error("训练营不存在");
        }

        trainingCamp.setTrainingCampName(params.getTrainingCampName());
        fsUserCourseTrainingCampService.updateById(trainingCamp);
        return AjaxResult.success();
    }

    /**
     * 更新训练营序号
     * @param trainingCampId    训练营ID
     * @param orderNumber       序号
     * @return  AjaxResult
     */
    @Log(title = "训练营序号", businessType = BusinessType.UPDATE)
    @PostMapping("/updateOrderNumber")
    public AjaxResult updateOrderNumber(@RequestParam Long trainingCampId, @RequestParam Long orderNumber) {
        if (trainingCampId == null) {
            return AjaxResult.error("训练营ID不能为空");
        }
        
        FsUserCourseTrainingCamp trainingCamp = fsUserCourseTrainingCampService.getById(trainingCampId);
        if (Objects.isNull(trainingCamp)) {
            return AjaxResult.error("训练营不存在");
        }
        
        trainingCamp.setOrderNumber(orderNumber);
        fsUserCourseTrainingCampService.updateById(trainingCamp);
        return AjaxResult.success("序号更新成功");
    }

    /**
     * 删除训练营
     * @param ids    参数
     * @return  AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('course:trainingCamp:remove')")
    @Log(title = "训练营", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult del(@PathVariable Long[] ids) {
        fsUserCourseTrainingCampService.del(ids);
        return AjaxResult.success();
    }

    /**
     * 复制训练营
     * @param id    参数
     * @return  AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('course:trainingCamp:copy')")
    @Log(title = "训练营", businessType = BusinessType.INSERT)
    @PostMapping("/copy/{id}")
    public AjaxResult copy(@PathVariable Long id) {
        fsUserCourseTrainingCampService.copy(id);
        return AjaxResult.success();
    }

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

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


    /**
     * 通过训练营来筛选营期-展示创建成功的营期
     *
     * @return
     */
    @GetMapping("/getScreeningCampPeriod")
    public R getScreeningCampPeriod(@RequestParam String campPeriodType,
                                    @RequestParam(required = false) Long periodId,
                                    @RequestParam(required = false) String campPeriodName) {
        try {
            // 获取用户和配置信息
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            Long userId = loginUser.getUser().getUserId();
            CourseConfig config = getCourseConfig();
            boolean needBindUser = config != null && config.getIsBound();
            if ("2".equals(campPeriodType)) {
                // 查询其他训练营
                List<FsUserCoursePeriodVO> resultList = new ArrayList<>();
                Map<String, Object> params = new HashMap<>();
                params.put("scs", SortUtils.parseSort("order_number(desc),training_camp_id(desc)"));
                if (needBindUser) params.put("userIds", userId);
                List<FsUserCourseTrainingCampVO> fsUserCourseTrainingCampList= fsUserCourseTrainingCampService.selectFsUserCourseTrainingCampVOListByMap(params);
                fsUserCourseTrainingCampList = fsUserCourseTrainingCampList.stream()
                        .filter(camp -> !Objects.equals(camp.getTrainingCampId(), periodId))
                        .collect(Collectors.toList());
                return R.ok().put("resultList", fsUserCourseTrainingCampList);
            } else if ("3".equals(campPeriodType)) {
                // 新建训练营
                if (StringUtils.isEmpty(campPeriodName)) {
                    return R.error("训练营名称不能为空");
                }
                FsUserCourseTrainingCampDTO campDTO = new FsUserCourseTrainingCampDTO();
                campDTO.setTrainingCampName(campPeriodName.trim());
                return R.ok("训练营创建成功");
            }
            return R.error("不支持的训练营类型");
        } catch (Exception e) {
            return R.error("系统处理异常");
        }
    }
    private CourseConfig getCourseConfig() {
        try {
            String json = configService.selectConfigByKey("course.config");
            return JSONUtil.toBean(json, CourseConfig.class);
        } catch (Exception e) {
            return null;
        }
    }
}
