package org.jeecg.modules.system.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.domain.StudentInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.app.entity.*;
import org.jeecg.modules.system.app.form.ClassGroupingCasePageForm;
import org.jeecg.modules.system.app.form.ClassGroupingForm;
import org.jeecg.modules.system.app.form.ClassGroupingPageForm;
import org.jeecg.modules.system.app.form.StudentInfoForm;
import org.jeecg.modules.system.app.mapper.AppSiteMapper;
import org.jeecg.modules.system.app.service.*;
import org.jeecg.modules.system.app.vo.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.simpleframework.xml.core.Validate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Tag(name="分班管理")
@RestController
@AllArgsConstructor
@RequestMapping("/app/classGrouping")
public class AppClassGroupingController {

    private final IAppClassGroupingService appClassGroupingService;
    private final IAppClassUserService appClassUserService;
    private final ISysUserService sysUserService;
    private final IAppCoureseService appCoureseService;
    private final IAppSiteService appSiteService;

    /**
     * 分班管理分页
     *
     * @param classGroupingPageForm
     * @return
     */
    @PostMapping(value = "/queryPage")
    public Result<IPage<ClassGroupingVO>> queryPage(@RequestBody ClassGroupingPageForm classGroupingPageForm) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String orgCode = loginUser.getOrgCode();
        if (!"A01".equals(orgCode)){
            classGroupingPageForm.setOrgCode(orgCode);
        }
        IPage<ClassGroupingVO> classGroupingVOIPage = appClassGroupingService.queryPage(classGroupingPageForm);
        return Result.OK(classGroupingVOIPage);
    }

    /**
     * 分班情况分页
     *
     * @param classGroupingCasePageForm
     * @return
     */
    @PostMapping(value = "/queryCasePage")
    public Result<IPage<ClassGroupingCaseVO>> queryCasePage(@RequestBody ClassGroupingCasePageForm classGroupingCasePageForm) {
        IPage<ClassGroupingCaseVO> classGroupingCaseVOIPage = appClassGroupingService.queryCasePage(classGroupingCasePageForm);
        return Result.OK(classGroupingCaseVOIPage);
    }

    /**
     * 根据课程ID查询未分班的学员
     *
     * @param
     * @return
     */
    @PostMapping(value = "/getStudentInfoList")
    public Result<List<StudentInfoVO>> getStudentInfoList(@RequestBody StudentInfoForm studentInfoForm) {
         List<StudentInfoVO> studentInfoList = appClassGroupingService.getStudentInfoList(studentInfoForm);
        return Result.OK(studentInfoList);
    }

    /**
     * 查询所有门店地址
     *
     * @param
     * @return
     */
    @GetMapping(value = "/getSiteList")
    public Result<List<SiteInfoVO>> getSiteList() {
        List<AppSite> list = appSiteService.list();
        List<SiteInfoVO> siteInfoVOList = list.stream().map(item -> {
            SiteInfoVO siteInfoVO = new SiteInfoVO();
            siteInfoVO.setSiteId(item.getId()).setSiteName(item.getName());
            return siteInfoVO;
        }).collect(Collectors.toList());
        return Result.OK(siteInfoVOList);
    }

    /**
     * 根据课程查询教练列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "/getCoachInfoVOList")
    public Result<List<CoachInfoVO>> getCoachInfoVOList(@RequestParam(value = "coursesId") String coursesId) {

        List<CoachInfoVO> coachInfoVOList = new ArrayList<>();

        AppCourses course = appCoureseService.getById(coursesId);
        if (ObjectUtil.isNotEmpty(course.getUserId())){
            List<String> ids = Arrays.stream(course.getUserId().split(",")).collect(Collectors.toList());
            for (String id : ids) {
                SysUser sysUser = sysUserService.getById(id);
                if (ObjectUtil.isNotEmpty(sysUser)){
                    CoachInfoVO coachInfoVO = new CoachInfoVO();
                    coachInfoVO.setCoachUserId(sysUser.getId()).setName(sysUser.getRealname());
                    coachInfoVOList.add(coachInfoVO);
                }
            }
        }
        return Result.OK(coachInfoVOList);
    }

    /**
     * 分班创建
     *
     * @param classGroupingCaseForm
     * @return
     */
    @AutoLog(value = "分班创建")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody @Validated ClassGroupingForm classGroupingCaseForm) {

        AppClassGrouping appClassGrouping = new AppClassGrouping();
        appClassGrouping.setClassName(classGroupingCaseForm.getClassName());
        appClassGrouping.setCourseId(classGroupingCaseForm.getCourseId());
        appClassGrouping.setCoachUserId(classGroupingCaseForm.getCoachUserId());
        appClassGroupingService.save(appClassGrouping);

        for (String familyMemberId : classGroupingCaseForm.getFamilyMemberIds()) {
            AppClassUser appClassUser = new AppClassUser();
            appClassUser.setClassGroupingId(appClassGrouping.getId());
            appClassUser.setCourseId(appClassGrouping.getCourseId());
            appClassUser.setFamilyMemberId(familyMemberId);
            appClassUserService.save(appClassUser);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 分班修改
     *
     * @param classGroupingCaseForm
     * @return
     */
    @AutoLog(value = "分班修改")
    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody @Validate ClassGroupingForm classGroupingCaseForm) {

        AppClassGrouping appClassGrouping = new AppClassGrouping();
        appClassGrouping.setId(classGroupingCaseForm.getId());
        appClassGrouping.setClassName(classGroupingCaseForm.getClassName());
        appClassGrouping.setCourseId(classGroupingCaseForm.getCourseId());
        appClassGrouping.setCoachUserId(classGroupingCaseForm.getCoachUserId());
        appClassGroupingService.updateById(appClassGrouping);

        // 删除原来的
        appClassUserService.remove(Wrappers.<AppClassUser>lambdaQuery().eq(AppClassUser::getClassGroupingId, appClassGrouping.getId()));
        for (String familyMemberId : classGroupingCaseForm.getFamilyMemberIds()) {
            AppClassUser appClassUser = new AppClassUser();
            appClassUser.setClassGroupingId(appClassGrouping.getId());
            appClassUser.setCourseId(appClassGrouping.getCourseId());
            appClassUser.setFamilyMemberId(familyMemberId);
            appClassUserService.save(appClassUser);
        }
        return Result.OK("修改成功！");
    }

    /**
     * 分班删除
     *
     * @param classGroupingId 分班ID
     * @return
     */
    @AutoLog(value = "分班删除")
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@NotBlank(message = "分班ID不能为空") @RequestParam(name = "classGroupingId", required = true) String classGroupingId) {
        appClassGroupingService.removeById(classGroupingId);
        // 删除原来的
        appClassUserService.remove(Wrappers.<AppClassUser>lambdaQuery().eq(AppClassUser::getClassGroupingId, classGroupingId));
        return Result.OK("删除成功！");
    }
}
