package com.xjrsoft.module.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.enums.RoleEnum;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.base.dto.AddBaseClassDynamicsDto;
import com.xjrsoft.module.base.dto.BaseClassDynamicsPageDto;
import com.xjrsoft.module.base.dto.UpdateBaseClassDynamicsDto;
import com.xjrsoft.module.base.entity.BaseClassDynamics;
import com.xjrsoft.module.base.entity.BaseUserStudent;
import com.xjrsoft.module.base.service.IBaseClassDynamicsService;
import com.xjrsoft.module.base.service.IBaseUserStudentService;
import com.xjrsoft.module.base.vo.BaseClassDynamicsPageVo;
import com.xjrsoft.module.base.vo.BaseClassDynamicsVo;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.student.service.IBaseStudentSchoolRollService;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @title: 班级动态表
* @Author dzx
* @Date: 2024-09-04
* @Version 1.0
*/
@RestController
@RequestMapping("/base" + "/baseClassDynamics")
@Api(value = "/base"  + "/baseClassDynamics",tags = "班级动态表代码")
@AllArgsConstructor
public class BaseClassDynamicsController {


    private final IBaseClassDynamicsService baseClassDynamicsService;
    private final IBaseStudentSchoolRollService rollService;
    private final IBaseUserStudentService userStudentService;
    private final IUserService userService;
    private final IFileService fileService;

    @GetMapping(value = "/page")
    @ApiOperation(value="班级动态表列表(分页)")
    @SaCheckPermission("baseclassdynamics:detail")
    public RT<PageOutput<BaseClassDynamicsPageVo>> page(@Valid BaseClassDynamicsPageDto dto){
        List<String> roleList = StpUtil.getRoleList();
        long userId = StpUtil.getLoginIdAsLong();
        Integer roleType = null;
        List<Long> classIds = new ArrayList<>();
        if(roleList.contains("STUDENT")){
            roleType = 3;
            classIds.add(rollService.getClassIdByUserId(userId));
        }
        if(roleList.contains("PARENT")){
            roleType = 4;
            List<BaseUserStudent> list = userStudentService.list(new QueryWrapper<BaseUserStudent>().lambda().eq(BaseUserStudent::getUserId, userId));
            for (BaseUserStudent userStudent : list) {
                classIds.add(rollService.getClassIdByUserId(userStudent.getStudentId()));
            }
        }

        LambdaQueryWrapper<BaseClassDynamics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(BaseClassDynamics::getId)
                .select(BaseClassDynamics.class,x -> VoToColumnUtil.fieldsToColumns(BaseClassDynamicsPageVo.class).contains(x.getProperty()))
                .like(roleType != null, BaseClassDynamics::getRoleType, roleType)
                .in(!classIds.isEmpty(), BaseClassDynamics::getClassId, classIds)
        ;
        IPage<BaseClassDynamics> page = baseClassDynamicsService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<BaseClassDynamicsPageVo> pageOutput = ConventPage.getPageOutput(page, BaseClassDynamicsPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/release-page")
    @ApiOperation(value="班主任发布列表(分页)")
    @SaCheckPermission("baseclassdynamics:detail")
    public RT<PageOutput<BaseClassDynamicsPageVo>> releasePage(@Valid BaseClassDynamicsPageDto dto){
        long userId = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<BaseClassDynamics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(BaseClassDynamics::getId)
                .select(BaseClassDynamics.class,x -> VoToColumnUtil.fieldsToColumns(BaseClassDynamicsPageVo.class).contains(x.getProperty()))
                .eq(BaseClassDynamics::getCreateUserId, userId);
        IPage<BaseClassDynamics> page = baseClassDynamicsService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<BaseClassDynamicsPageVo> pageOutput = ConventPage.getPageOutput(page, BaseClassDynamicsPageVo.class);
        return RT.ok(pageOutput);
    }


    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询班级动态表信息")
    @SaCheckPermission("baseclassdynamics:detail")
    public RT<BaseClassDynamicsVo> info(@RequestParam Long id){
        BaseClassDynamics baseClassDynamics = baseClassDynamicsService.getById(id);
        if (baseClassDynamics == null) {
           return RT.error("找不到此数据！");
        }
        BaseClassDynamicsVo dynamicsVo = BeanUtil.toBean(baseClassDynamics, BaseClassDynamicsVo.class);
        User user = userService.getById(baseClassDynamics.getCreateUserId());
        dynamicsVo.setCreateUserName(user.getName());

        if(dynamicsVo.getFolderId() != null){
            File file = fileService.getOne(new QueryWrapper<File>().lambda().eq(File::getFolderId, dynamicsVo.getFolderId()));
            if(file != null){
                dynamicsVo.setFileUrl(file.getFileUrl());
            }
        }

        return RT.ok(dynamicsVo);
    }


    @PostMapping
    @ApiOperation(value = "新增班级动态表")
    @SaCheckPermission("baseclassdynamics:add")
    public RT<Boolean> add(@Valid @RequestBody AddBaseClassDynamicsDto dto){
        BaseClassDynamics baseClassDynamics = BeanUtil.toBean(dto, BaseClassDynamics.class);
        baseClassDynamics.setCreateDate(new Date());
        boolean isSuccess = baseClassDynamicsService.save(baseClassDynamics);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改班级动态表")
    @SaCheckPermission("baseclassdynamics:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateBaseClassDynamicsDto dto){

        BaseClassDynamics baseClassDynamics = BeanUtil.toBean(dto, BaseClassDynamics.class);
        baseClassDynamics.setModifyDate(new Date());
        return RT.ok(baseClassDynamicsService.updateById(baseClassDynamics));

    }

    @DeleteMapping
    @ApiOperation(value = "删除班级动态表")
    @SaCheckPermission("baseclassdynamics:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(baseClassDynamicsService.removeBatchByIds(ids));
    }

}