package com.yida.data.user.controller.in;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.user.EduParent;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.entity.user.EduTeacherDept;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.entity.user.enums.DeptVisibleTypeEnum;
import com.yida.data.common.core.entity.user.enums.UserDeptTypeEnum;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.school.dto.transaction.ListBuyStudentDTO;
import com.yida.data.user.dto.ListStudentDTO;
import com.yida.data.user.mapper.EduParentMapper;
import com.yida.data.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Api(tags = "学生管理（不鉴权）")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/in/student")
public class InStudentController {

    private final EduStudentService eduStudentService;
    private final EduParentMapper eduParentMapper;
    private final EduParentService eduParentService;
    private final EduUserDeptService eduUserDeptService;
    private final QywxSyncService qywxSyncService;
    private final DaHuaSyncService daHuaSyncService;
    private final RedisService redisService;
    private final EduTeacherDeptService eduTeacherDeptService;
    private final EduStudentDormService eduStudentDormService;

    @ApiOperation("处理企业微信 改变学生事件")
    @PostMapping("/dealWxStudentChange")
    public ResultBean dealStudentWxChange(@RequestBody EduStudent eduStudent) {
        EduStudent student =
            eduStudentService.getOne(Wrappers.lambdaQuery(new EduStudent()).eq(EduStudent::getSchoolId,
                eduStudent.getSchoolId()).eq(EduStudent::getWxId, eduStudent.getWxId()));
        if (student != null) {
            eduStudent.setId(student.getId());
        }
        if (CollUtil.isNotEmpty(eduStudent.getParents())) {
            for (EduParent parent : eduStudent.getParents()) {
                EduParent exist = eduParentMapper.selectOne(Wrappers.lambdaQuery(new EduParent())
                    .eq(EduParent::getMobile, parent.getMobile())
                    .eq(EduParent::getSchoolId, eduStudent.getSchoolId()));
                if (exist != null) {
                    parent.setId(exist.getId());
                }
            }
        }
        eduStudentService.saveStudent(eduStudent, null, true);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("处理企业微信 删除学生事件")
    @GetMapping("/dealWxStudentDelete")
    public ResultBean dealStudentWxDelete(@RequestParam String wxId, @RequestParam Long schoolId) {
        EduStudent student =
            eduStudentService.getOne(Wrappers.lambdaQuery(new EduStudent()).eq(EduStudent::getWxId,
                wxId).eq(EduStudent::getSchoolId, schoolId));
        if (student != null) {
            log.info("微信删除学生不存在，wxId:[{}]，schoolId:[{}]", wxId, schoolId);
            eduStudentService.delStudentBatchIds(Arrays.asList(student.getId()), true);
        }
        return ResultBean.buildSuccess();
    }


    @ApiOperation("处理企业微信 改变家长事件(改变家长信息   删除家长后仍存在学生   创建学生后第一次新增该家长)")
    @PostMapping("/dealWxParentChange")
    public ResultBean dealParentWxChange(@RequestBody EduParent parent, @RequestParam Long schoolId) {
        eduParentService.dealWxParentChange(parent, schoolId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("处理企业微信  删除家长事件（无学生关联，直接删除家长）")
    @GetMapping("/dealWxParentDelete")
    public ResultBean dealParentWxDelete(@RequestParam String wxId, @RequestParam Long schoolId) {
        EduParent parent = eduParentMapper.selectOne(Wrappers.<EduParent>lambdaQuery()
            .eq(EduParent::getWxId, wxId)
            .eq(EduParent::getSchoolId, schoolId));
        if (parent != null) {
            log.info("微信删除家长不存在，wxId:[{}]，schoolId:[{}]", wxId, schoolId);
            eduParentService.dealParentWxDelete(wxId, schoolId);
        }
        return ResultBean.buildSuccess();
    }

    @ApiOperation("根据学生id查询学生")
    @GetMapping("/getStudent")
    public ResultBean<EduStudent> getStudent(Long studentId) {
        return ResultBean.buildSuccess(eduStudentService.getStudent(studentId));
    }

    @ApiOperation("根据学生Id查询学生部门信息")
    @PostMapping("/getStudentDeptByIds")
    public ResultBean<List<EduStudent>> getStudentDeptByIds(@RequestBody List<Long> studentIdList) {
        return ResultBean.buildSuccess(eduStudentService.getStudentDeptByIds(studentIdList));
    }

    @ApiOperation("根据企业微信通讯录初始化学生")
    @PostMapping("/initStudent")
    public ResultBean initStudent(@RequestBody List<EduStudent> student) {
        eduStudentService.initStudent(student);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("根据学生学号和学校查询学生")
    @GetMapping("/getStudentByStuNumAndSchool")
    public ResultBean<EduStudent> getStudentByStuNumAndSchool(String stuNumber, Long schoolId) {
        EduStudent one = eduStudentService.getOne(
            Wrappers.lambdaQuery(new EduStudent()).eq(EduStudent::getStuNumber, stuNumber)
                .eq(EduStudent::getSchoolId, schoolId));
        if (ObjectUtil.isEmpty(one)) {
            return ResultBean.buildSuccess(one);
        }
        EduUserDept gradeDept = eduUserDeptService.getById(one.getGradeId());
        EduUserDept classDept = eduUserDeptService.getById(one.getClassId());
        one.setGradeName(gradeDept.getDeptName());
        one.setClassName(classDept.getDeptName());

        return ResultBean.buildSuccess(one);
    }

    @GetMapping("/listStudentByGradeAndClass")
    ResultBean<List<EduStudent>> listStudentByGradeAndClass(@RequestParam("studentName") String studentName,
        @RequestParam("className") String className,
        @RequestParam("gradeId") Long gradeId) {
        return ResultBean.buildSuccess(eduStudentService.list(Wrappers.lambdaQuery(new EduStudent())
            .eq(EduStudent::getGradeId, gradeId)
            .eq(EduStudent::getClassName, className)
            .eq(EduStudent::getStuName, studentName)));
    }

    @ApiOperation("保存家长易达app用户id")
    @GetMapping("/saveYidaAppUserId")
    ResultBean saveYidaAppUserId(@RequestParam("parentId") Long parentId,
        @RequestParam("yidaAppUserId") String yidaAppUserId) {
        EduParent parent = new EduParent();
        parent.setId(parentId);
        parent.setYidaAppUserId(yidaAppUserId);
        eduParentService.updateById(parent);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("保存家长openId")
    @GetMapping("/saveWxPublicOpenId")
    ResultBean saveWxPublicOpenId(@RequestParam("parentId") Long parentId,
        @RequestParam("openId") String openId) {
        EduParent parent = new EduParent();
        parent.setId(parentId);
        parent.setWxPublicOpenId(openId);
        eduParentService.updateById(parent);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询带学生的家长信息")
    @GetMapping("/getParentWithStudent")
    ResultBean getParentWithStudent(@RequestParam(required = false) String mobile,
        @RequestParam(required = false) String wxId,
        Long schoolId) {
        return ResultBean.buildSuccess(eduParentService.getParentWithStudent(wxId, mobile, schoolId));
    }

    @ApiOperation("根据学生列表查询家长微信id列表")
    @PostMapping("/findParentWxId")
    public ResultBean<List<String>> findParentWxId(@RequestBody List<Long> studentId) {

        return ResultBean.buildSuccess(eduStudentService.findParentWxId(studentId));
    }

    @ApiOperation("根据学生列表查询家长微信id列表")
    @PostMapping("/listAllNotBuyStudent")
    public ResultBean<List<EduStudent>> listAllNotBuyStudent(@RequestBody ListBuyStudentDTO listBuyStudentDTO) {

        return ResultBean.buildSuccess(eduStudentService.listAllNotBuyStudent(listBuyStudentDTO));
    }

    @ApiOperation("同步企业微信学生数据")
    @GetMapping("/syncQywxStudent")
    public ResultBean syncQywxStudent() {
//        eduStudentService.syncQywxStudent();
        qywxSyncService.syncQywxStudent(null);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("同步指定学校企业微信学生数据")
    @GetMapping("/syncSchoolQywxStudent")
    public ResultBean syncSchoolQywxStudent(@RequestParam Long schoolId) {
//        eduStudentService.syncQywxStudent();
        qywxSyncService.syncQywxStudent(schoolId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("同步学生数据到大华")
    @GetMapping("/syncSchoolDaHuaStudent")
    public ResultBean<String> syncSchoolDaHuaStudent(@RequestParam Long schoolId) {
        daHuaSyncService.syncSchoolDaHuaStudent(schoolId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("更新学生在校离校状态")
    @GetMapping("/updateStudentStatus")
    public ResultBean updateStudentStatus(Long studentId,
        @RequestParam(required = false) Integer status,
        @RequestParam(required = false) Integer dormStatus) {
        EduStudent student = new EduStudent();
        student.setId(studentId);
        student.setStatus(status);
        student.setDormStatus(dormStatus);
        eduStudentService.updateById(student);
        redisService.hdel(CachePrefixConstant.STUDENT_DATA, studentId.toString());
        return ResultBean.buildSuccess();
    }


    @ApiOperation("根据大华id查询学生")
    @GetMapping("/getStudentByDahua")
    public ResultBean<EduStudent> getStudentByDahua(String dahuaCode) {
        return ResultBean.buildSuccess(eduStudentService.getOne(Wrappers.<EduStudent>lambdaQuery()
            .eq(EduStudent::getDahuaCode, dahuaCode)));
    }

    @ApiOperation("根据条件查询学生列表")
    @PostMapping("/listStudent")
    public ResultBean<List<EduStudent>> listStudent(@RequestBody ListStudentDTO dto) {
        return ResultBean.buildSuccess(eduStudentService.listStudent(dto));
    }

    @ApiOperation("根据班级查询学生列表")
    @PostMapping("/listStudentByClassId")
    public ResultBean<List<EduStudent>> listStudentByClassId(@RequestBody ListStudentDTO dto) {
        return ResultBean.buildSuccess(eduStudentService.listStudentByClassId(dto));
    }

    @ApiOperation("根据学生表字段查询学生id信息")
    @PostMapping("/listBaseStudentIds")
    public ResultBean<List<Long>> listBaseStudentIds(@RequestBody EduStudent eduStudent) {
        return ResultBean.buildSuccess(eduStudentService.listBaseStudentIds(eduStudent));
    }

    @ApiOperation("根据学生表字段查询学生列表信息")
    @PostMapping("/listBaseStudent")
    public ResultBean<List<EduStudent>> listBaseStudent(@RequestBody EduStudent eduStudent) {
        return ResultBean.buildSuccess(eduStudentService.listBaseStudent(eduStudent));
    }

    @ApiOperation("单表查询学生信息")
    @PostMapping("/listBaseStudentNoJoin")
    public ResultBean<List<EduStudent>> listBaseStudentNoJoin(@RequestBody EduStudent eduStudent) {
        return ResultBean.buildSuccess(eduStudentService.listBaseStudentNoJoin(eduStudent));
    }

    @ApiOperation("根据deptId查询学生关联的宿舍")
    @PostMapping("/listDormIdsByDeptId")
    public ResultBean<List<Long>> listDormIdsByDeptId(@RequestBody ListStudentDTO dto) {
        return ResultBean.buildSuccess(eduStudentService.listDormIdsByDeptId(dto));
    }

    @ApiOperation("查询校园大数据的人员统计数据")
    @GetMapping("/countUserDashboardNum")
    public ResultBean<JSONObject> countUserDashboardNum(@RequestParam Long schoolId) {
        JSONObject jsonObject = JSONUtil.createObj();
        // 学生数量
        long studentNum = eduStudentService.count(Wrappers.lambdaQuery(new EduStudent())
            .eq(EduStudent::getSchoolId, schoolId));
        jsonObject.set("studentNum", studentNum);
        // 班级数量
        long classNum = eduUserDeptService.count(Wrappers.lambdaQuery(new EduUserDept())
            .eq(EduUserDept::getSchoolId, schoolId)
            .eq(EduUserDept::getDeptType, UserDeptTypeEnum.CLASS_TYPE.getValue())
            .eq(EduUserDept::getVisible, DeptVisibleTypeEnum.VISIBLE_TYPE.getValue())
        );
        jsonObject.set("classNum", classNum);
        // 教师数量
        jsonObject.set("teacherNum", eduTeacherDeptService.countTeacherNumber(schoolId));
        return ResultBean.buildSuccess(jsonObject);
    }


    @ApiOperation("新增住宿生")
    @PostMapping("/saveStudentDorm")
    public ResultBean saveStudentDorm(@RequestBody EduStudent eduStudent) {
        Asserts.isNotNull(eduStudent, "学生不存在");
        eduStudentDormService.saveStudentDorm(eduStudent.getId(), eduStudent.getDormRoomId(), eduStudent.getDormId());
        return ResultBean.buildSuccess();
    }

    @ApiOperation("更新学生信息缓存")
    @GetMapping("/updateStudentCache")
    public ResultBean updateStudentCache() {
        eduStudentService.updateStudentCache();
        return ResultBean.buildSuccess();
    }
}
