package yangtz.cs.liu.campus.controller.student;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentClassRelation;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.domain.studentChange.StudentInfoChange;
import yangtz.cs.liu.campus.domain.studentTurnover.StudentTurnover;
import yangtz.cs.liu.campus.service.student.ISchoolStudentClassRelationService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.service.studentChange.IStudentInfoChangeService;
import yangtz.cs.liu.campus.service.studentTurnover.IStudentTurnoverService;
import yangtz.cs.liu.campus.vo.schoolClass.StudentClassRelationVo;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;
import yangtz.cs.liu.campus.vo.studentTurnover.StudentTurnoverVo;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import static yangtz.cs.liu.campus.constant.TurnoverConstant.BJ;
import static yangtz.cs.liu.campus.constant.TurnoverConstant.YTJ;

/**
 * 学校学生Controller
 *
 * @author ruoyi
 * @date 2022-09-27
 */
@RestController
@RequestMapping("/school/student")
public class SchoolStudentController extends BaseController {

    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISchoolStudentClassRelationService relationService;

    @Autowired
    private ISchoolStudentParentService parentService;

    @Autowired
    private IStudentInfoChangeService studentInfoChangeService;

    @Autowired
    private IStudentTurnoverService studentTurnoverService;


    /**
     * 学生列表
     *
     * @param schoolStudent
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolStudentVO schoolStudent) {
        startPage();
        List<SchoolStudentVO> list = schoolStudentService.queryList(schoolStudent);
        return getDataTable(list);
    }

    /**
     * @author lyric
     * @date 2022/10/30 14:29
     * <p>
     * 新增学生
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolStudent schoolStudent) {
        checkStudentUniqueXz(schoolStudent);
        boolean flag = schoolStudentService.save(schoolStudent);
        //添加关系到学生班级表
        if(StringUtils.isNotNull(schoolStudent.getClassId())){
            addRelation(schoolStudent);
        }
        return toAjax(flag);
    }

    /**
     * 修改
     *
     * @param schoolStudent
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolStudent schoolStudent) {
        if (StringUtils.isNull(schoolStudent.getId())) {
            AjaxResult.error("学生id未传");
        }
        checkStudentUnique(schoolStudent);
        //查询修改前学生信息，用于比对学生班级是否更改
        SchoolStudent student = schoolStudentService.getById(schoolStudent.getId());
        boolean flag = schoolStudentService.updateById(schoolStudent);
        if(StringUtils.isNotNull(schoolStudent.getClassId())){
            if (!student.getClassId().equals(schoolStudent.getClassId())) {
                LambdaQueryWrapper<SchoolStudentClassRelation> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolStudentClassRelation::getClassId,student.getClassId())
                        .eq(SchoolStudentClassRelation::getStudentId,student.getId());
                relationService.remove(lqw);
                addRelation(schoolStudent);
            }
        }

        return toAjax(flag);
    }

    private void checkStudentUniqueXz(SchoolStudent schoolStudent) {
        // TODO 修改
        LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolStudent::getIdCard, schoolStudent.getIdCard());
        SchoolStudent student = schoolStudentService.getOne(lqw);
        if (StringUtils.isNotNull(student)){
            if (schoolStudent.getIdCard().equals(student.getIdCard())){
                throw new ServiceException("身份证号已存在");
            }
        }

        LambdaQueryWrapper<SchoolStudent> lqw1 = new LambdaQueryWrapper<>();
        lqw1
                .eq(SchoolStudent::getSchoolNo, schoolStudent.getSchoolNo());
        SchoolStudent student1 = schoolStudentService.getOne(lqw1);
        if (StringUtils.isNotNull(student1)){
            if (schoolStudent.getSchoolNo().equals(student1.getSchoolNo())){
                throw new ServiceException("注册序号已存在");
            }
        }

        if (StringUtils.isNotBlank(schoolStudent.getProvincialNumber())){
            LambdaQueryWrapper<SchoolStudent> lqw2 = new LambdaQueryWrapper<>();
            lqw2
                    .eq(SchoolStudent::getProvincialNumber, schoolStudent.getProvincialNumber());
            SchoolStudent student2 = schoolStudentService.getOne(lqw2);
            if (StringUtils.isNotNull(student2)){
                if (schoolStudent.getProvincialNumber().equals(student2.getProvincialNumber())){
                    throw new ServiceException("省学籍辅号已存在");
                }
            }
        }


        if (StringUtils.isNotBlank(schoolStudent.getNationalNumber())){
            LambdaQueryWrapper<SchoolStudent> lqw3 = new LambdaQueryWrapper<>();
            lqw3
                    .eq(SchoolStudent::getNationalNumber, schoolStudent.getNationalNumber());
            SchoolStudent student3 = schoolStudentService.getOne(lqw3);
            if (StringUtils.isNotNull(student3)){
                if (schoolStudent.getNationalNumber().equals(student3.getNationalNumber())){
                    throw new ServiceException("全国学籍号已存在");
                }
            }
        }


        if (StringUtils.isNotBlank(schoolStudent.getOneCard())){
            LambdaQueryWrapper<SchoolStudent> lqw4 = new LambdaQueryWrapper<>();
            lqw4
                    .eq(SchoolStudent::getOneCard, schoolStudent.getOneCard());
            SchoolStudent student4 = schoolStudentService.getOne(lqw4);
            if (StringUtils.isNotNull(student4)){
                if (schoolStudent.getOneCard().equals(student4.getOneCard())){
                    throw new ServiceException("校园一卡通已存在");
                }
            }
        }
    }

    private void checkStudentUnique(SchoolStudent schoolStudent) {
        // TODO 原代码
//        LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
//        lqw
//                .eq(SchoolStudent::getIdCard, schoolStudent.getIdCard())
//                .or()
//                .eq(SchoolStudent::getSchoolNo, schoolStudent.getSchoolNo())
//                .or()
//                .eq(isNotBlank(schoolStudent.getProvincialNumber()),SchoolStudent::getProvincialNumber,schoolStudent.getProvincialNumber())
//                .or()
//                .eq(isNotBlank(schoolStudent.getNationalNumber()),SchoolStudent::getNationalNumber,schoolStudent.getNationalNumber())
//                .or()
//                .eq(isNotBlank(schoolStudent.getOneCard()), SchoolStudent::getOneCard, schoolStudent.getOneCard());
//        SchoolStudent student = schoolStudentService.getOne(lqw);
//        if (StringUtils.isNotNull(student)) {
//            if (StringUtils.isNotNull(schoolStudent.getId()) && schoolStudent.getId().equals(student.getId())) {
//                return;
//            }
//            if (schoolStudent.getIdCard().equals(student.getIdCard())) {
//                throw new ServiceException("身份证号已存在");
//            }
//            if (schoolStudent.getSchoolNo().equals(student.getSchoolNo())) {
//                throw new ServiceException("注册序号已存在");
//            }
//            if(StringUtils.isNotBlank(schoolStudent.getProvincialNumber())){
//                if (schoolStudent.getProvincialNumber().equals(student.getProvincialNumber())) {
//                    throw new ServiceException("省学籍辅号已存在");
//                }
//            }
//            if(StringUtils.isNotBlank(schoolStudent.getNationalNumber())){
//                if (schoolStudent.getNationalNumber().equals(student.getNationalNumber())) {
//                    throw new ServiceException("全国学籍号已存在");
//                }
//            }
//            if (StringUtils.isNotBlank(schoolStudent.getOneCard())) {
//                if (schoolStudent.getOneCard().equals(student.getOneCard())) {
//                    throw new ServiceException("校园一卡通已存在");
//                }
//            }
//        }
        // TODO 修改
        LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolStudent::getIdCard, schoolStudent.getIdCard())
                .notIn(SchoolStudent::getId,schoolStudent.getId());
        SchoolStudent student = schoolStudentService.getOne(lqw);
        if (StringUtils.isNotNull(student)){
            if (schoolStudent.getIdCard().equals(student.getIdCard())){
                throw new ServiceException("身份证号已存在");
            }
        }

        LambdaQueryWrapper<SchoolStudent> lqw1 = new LambdaQueryWrapper<>();
        lqw1
                .eq(SchoolStudent::getSchoolNo, schoolStudent.getSchoolNo())
                .notIn(SchoolStudent::getId,schoolStudent.getId());
        SchoolStudent student1 = schoolStudentService.getOne(lqw1);
        if (StringUtils.isNotNull(student1)){
            if (schoolStudent.getSchoolNo().equals(student1.getSchoolNo())){
                throw new ServiceException("注册序号已存在");
            }
        }

        if (StringUtils.isNotBlank(schoolStudent.getProvincialNumber())){
            LambdaQueryWrapper<SchoolStudent> lqw2 = new LambdaQueryWrapper<>();
            lqw2
                    .eq(SchoolStudent::getProvincialNumber, schoolStudent.getProvincialNumber())
                    .notIn(SchoolStudent::getId,schoolStudent.getId());
            SchoolStudent student2 = schoolStudentService.getOne(lqw2);
            if (StringUtils.isNotNull(student2)){
                if (schoolStudent.getProvincialNumber().equals(student2.getProvincialNumber())){
                    throw new ServiceException("省学籍辅号已存在");
                }
            }
        }

        if (StringUtils.isNotBlank(schoolStudent.getNationalNumber())){
            LambdaQueryWrapper<SchoolStudent> lqw3 = new LambdaQueryWrapper<>();
            lqw3
                    .eq(SchoolStudent::getNationalNumber, schoolStudent.getNationalNumber())
                    .notIn(SchoolStudent::getId,schoolStudent.getId());
            SchoolStudent student3 = schoolStudentService.getOne(lqw3);
            if (StringUtils.isNotNull(student3)){
                if (schoolStudent.getNationalNumber().equals(student3.getNationalNumber())){
                    throw new ServiceException("全国学籍号已存在");
                }
            }
        }

        if (StringUtils.isNotBlank(schoolStudent.getOneCard())){
            LambdaQueryWrapper<SchoolStudent> lqw4 = new LambdaQueryWrapper<>();
            lqw4
                    .eq(SchoolStudent::getOneCard, schoolStudent.getOneCard())
                    .notIn(SchoolStudent::getId,schoolStudent.getId());
            SchoolStudent student4 = schoolStudentService.getOne(lqw4);
            if (StringUtils.isNotNull(student4)){
                if (schoolStudent.getOneCard().equals(student4.getOneCard())){
                    throw new ServiceException("校园一卡通已存在");
                }
            }
        }
    }

    //添加学生与班级关系表
    private boolean addRelation(SchoolStudent schoolStudent) {
        SchoolStudentClassRelation relation = new SchoolStudentClassRelation();
        relation.setClassId(schoolStudent.getClassId());
        relation.setStudentId(schoolStudent.getId());
        return relationService.save(relation);
}

    /**
     * 查询详情
     *(只有学生的详情信息)
     * @param id
     * @return
     */
    @GetMapping("/queryOne/{id}")
    public AjaxResult queryOne(@PathVariable("id") Long id) {
        SchoolStudentVO schoolStudent = schoolStudentService.getInfo(id);
        return AjaxResult.success(schoolStudent);
    }

    /**
     * 教务管理-学生管理-学生详情
     * 查询详情
     *(学生详情+学生班级关系+家长信息+关键信息变动+异动信息)
     * @param id
     * @return
     */
    @GetMapping("/queryAllInfo/{id}")
    public AjaxResult queryAllInfo(@PathVariable("id") Long id) {
        //学生基本信息
        SchoolStudentVO schoolStudent = schoolStudentService.getInfo(id);
        if(StringUtils.isNotNull(schoolStudent.getEnrollmentYear()) && !"".equals(schoolStudent.getEnrollmentYear())){
            schoolStudent.setCurrentGrade("高中"+schoolStudent.getEnrollmentYear()+"级");
        }
        AjaxResult ajax = AjaxResult.success(schoolStudent);

        //学生班级关系信息列表
        List<StudentClassRelationVo> relationVos = relationService.queryListByStudentId(id);
        ajax.put("studentClassRelation", relationVos);

        //学生家长信息列表
        SchoolStudentParent parent = new SchoolStudentParent();
        parent.setStudentId(id);
        List<SchoolStudentParent> parentList = parentService.queryList(parent);
        ajax.put("studentParents", parentList);

        //学生关键信息变更
        StudentInfoChange studentInfoChange = new StudentInfoChange();
        studentInfoChange.setStudentId(id);
        studentInfoChange.setState(YTJ);
        List<StudentInfoChange> list = studentInfoChangeService.selectStudentInfoChangeList(studentInfoChange);
        ajax.put("studentInfoChange", list);

        //异动信息
        List<StudentTurnoverVo> turnoverVoList = new ArrayList<>();
        StudentTurnover studentTurnover = new StudentTurnover();
        studentTurnover.setStudentId(id);
        studentTurnover.setState(BJ);
        List<StudentTurnover> turnoverList = studentTurnoverService.selectStudentTurnoverList(studentTurnover);
        for(StudentTurnover turnover : turnoverList){
            StudentTurnoverVo vo = new StudentTurnoverVo();
            String remark = " ";
            String d = DateUtils.formatDate(turnover.getEndTime());
            if("0".equals(turnover.getChangeType()) || "1".equals(turnover.getChangeType())){
                remark = d + "由" + turnover.getTurnSchool()+"转入";
            } else if ("2".equals(turnover.getChangeType()) || "3".equals(turnover.getChangeType())) {
                remark = d + "转至" + turnover.getTurnSchool();
            }else if ("4".equals(turnover.getChangeType())) {
                remark = d + "退学";
            }else if ("5".equals(turnover.getChangeType())) {
                remark = d + "，休学";
            }else if ("6".equals(turnover.getChangeType())) {
                remark = d + "复学";
            }
            vo.setId(turnover.getId());
            vo.setChangeType(turnover.getChangeType());
            vo.setRemark(remark);
            turnoverVoList.add(vo);
        }
        ajax.put("studentTurnover", turnoverVoList);

        return ajax;
    }

    /**
     * 教务管理-异动管理-新增 录入学生身份证信息后带出学生信息
     * 查询详情
     * 姓名，性别，出生年月，年级班级，学号
     * @param idCard
     * @return
     */
    @GetMapping("/queryAllInfoByidCard/{idCard}")
    public AjaxResult queryAllInfoByidCard(@PathVariable("idCard") String idCard) {
        //学生基本信息
        SchoolStudentVO schoolStudent = schoolStudentService.getInfoByidCard(idCard);
        AjaxResult ajax = AjaxResult.success(schoolStudent);

        //学生班级关系信息列表
       /* List<StudentClassRelationVo> relationVos = relationService.queryListByStudentId(schoolStudent.getId());
        ajax.put("studentClassRelation", relationVos);*/

        return ajax;
    }

    /**
     * 教务管理-异动管理-新增 选择监护人关系带出家长信息
     * 查询详情
     * 家长姓名，地址，联系电话
     * @param id
     * @param relationship
     * @return
     */
    @GetMapping("/queryByrelationship/{id}/{relationship}")
    public AjaxResult queryAllInfoByrelationship1(@PathVariable("id") String id,@PathVariable("relationship") String relationship) {

        //学生家长信息列表???
        /*SchoolStudentParent parent = new SchoolStudentParent();
        parent.setStudentId(id);
        parent.setRelationship(relationship);
        List<SchoolStudentParent> parentList = parentService.queryList(parent);*/
        //SchoolStudentParent schoolStudentParent = new SchoolStudentParent();
        if (StringUtils.isEmpty(id) || id.equals("undefined")){
            throw new ServiceException("请先选择学生!");
        }
        Long StudentId = Long.valueOf(id);
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolStudentParent::getStudentId,StudentId)
                .eq(SchoolStudentParent::getRelationship,relationship);
        List<SchoolStudentParent> list = parentService.list(lqw);
        //对应关系的家长不存在，抛异常
        if(StringUtils.isNull(list) || list.size() == 0){
            throw new ServiceException("查不到该学生对应关系的家长");
        }
        //有数据，返回列表第一个对象
        return AjaxResult.success(list.get(0));
    }


    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("ids") List<Long> ids) {
        //删除学生，删除学生班级关系
        List<SchoolStudent> studentList = schoolStudentService.listByIds(ids);
        for(SchoolStudent student : studentList){
            LambdaQueryWrapper<SchoolStudentClassRelation> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolStudentClassRelation::getClassId,student.getClassId())
               .eq(SchoolStudentClassRelation::getStudentId,student.getId());
            relationService.remove(lqw);
        }
        return toAjax(schoolStudentService.deleteByIds(ids));
    }

    /**
     * 导出
     *
     * @param ids
     * @return
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        List<SchoolStudentVO> list = schoolStudentService.exportSelect(ids);
        ExcelUtil<SchoolStudentVO> util = new ExcelUtil<>(SchoolStudentVO.class);
        util.exportExcel(response, list, "学生信息表");
    }

    //导出全部
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, SchoolStudentVO schoolStudent) {
        List<SchoolStudentVO> list = schoolStudentService.exportQueryList(schoolStudent);
        ExcelUtil<SchoolStudentVO> util = new ExcelUtil<>(SchoolStudentVO.class);
        util.exportExcel(response, list, "学生信息表");
    }

    /*
     * 模板
     * */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SchoolStudentVO> util = new ExcelUtil<SchoolStudentVO>(SchoolStudentVO.class);
        util.importTemplateExcel(response, "学生数据");
    }

    /**
     * 学生导入
     */
//    @PostMapping("/importStudent")
//    public AjaxResult importData(MultipartFile file) {
//        try {
//            ExcelUtil<SchoolStudentVO> util = new ExcelUtil<SchoolStudentVO>(SchoolStudentVO.class);
//            List<SchoolStudentVO> list = util.importExcel(file.getInputStream());
//            String operName = getUsername();
////            schoolStudentService.checkImport(list);
//            String message = schoolStudentService.importStudent(list, false, operName);
//            return AjaxResult.success(message);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.error();
//    }

    /**
     * 学生导入
     */
    @PostMapping("/importData")
    public AjaxResult importStudent(MultipartFile file) throws Exception {
        ExcelUtil<SchoolStudentVO> util = new ExcelUtil<SchoolStudentVO>(SchoolStudentVO.class);
        List<SchoolStudentVO> list = util.importExcel(file.getInputStream());
        //先校验
        schoolStudentService.checkImport(list);
        //数据导入
        String message = schoolStudentService.importData(list);
        return AjaxResult.success(message);

    }
    /*
    * 批量导入学生照片
    * */
    @PostMapping("/importStudentPicture")
    public AjaxResult importStudentPicture(MultipartFile file){
        return AjaxResult.success(schoolStudentService.importStudentPicture(file));
    }


}
