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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import yangtz.cs.liu.campus.domain.message.SchoolMessagePush;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherVO;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static yangtz.cs.liu.campus.constant.SexConstant.MAN;
import static yangtz.cs.liu.campus.constant.UserType.TEACHER;


/**
 * 学校老师Controller
 *
 * @author ruoyi
 * @date 2022-09-27
 */
@RestController
@RequestMapping("/school/teacher")
public class SchoolTeacherController extends BaseController {

    @Autowired
    private ISchoolTeacherService schoolTeacherService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询学校老师列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolTeacherVO schoolTeacher) {
        startPage();
        List<SchoolTeacher> list = schoolTeacherService.selectSchoolTeacherList(schoolTeacher);
        return getDataTable(list);
    }

    /**
     * 查询学校老师列表(查询全部)
     */
    @GetMapping("/teacherList")
    public TableDataInfo teacherList(SchoolTeacherVO schoolTeacher) {
        startPage();
        List<SchoolTeacher> list = schoolTeacherService.teacherList(schoolTeacher);
        return getDataTable(list);
    }

    /**
     * 查询学校老师列表(查询全部)(不分页)
     */
    @GetMapping("/getTeachers")
    public TableDataInfo getTeachers(SchoolTeacherVO schoolTeacher) {
        List<SchoolTeacher> list = schoolTeacherService.teacherList(schoolTeacher);
        return getDataTable(list);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @GetMapping("/queryOne/{id}")
    public AjaxResult queryOne(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolTeacherService.queryOne(id));
//        return AjaxResult.success(schoolTeacherService.getById(id));
    }


    /*
     * 添加老师信息
     * */
    @Log(title = "添加老师信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolTeacherVO schoolTeacherVO) {
        //checkTeacherUnique(schoolTeacherVO);
        schoolTeacherService.checkDeviceNumUnique(schoolTeacherVO);
        schoolTeacherService.checkTeacherCodeUnique(schoolTeacherVO);
        schoolTeacherService.checkTeacherTelUnique(schoolTeacherVO);
        schoolTeacherService.checkIdCardUnique(schoolTeacherVO);
        schoolTeacherService.checkPasswordUnique(schoolTeacherVO);
        if(StringUtils.isNotEmpty(schoolTeacherVO.getEmail())){
            schoolTeacherService.checkEmailUnique(schoolTeacherVO);
        }
        schoolTeacherVO.insert();
        return toAjax(schoolTeacherService.insert(schoolTeacherVO));
    }

    /*
     * 修改老师信息
     * */
    @Log(title = "修改老师信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SchoolTeacherVO schoolTeacherVO) {
        if (StringUtils.isNull(schoolTeacherVO.getId())) {
            return AjaxResult.error("教师id未传");
        }
        schoolTeacherService.checkDeviceNumUnique(schoolTeacherVO);
        schoolTeacherService.checkTeacherCodeUnique(schoolTeacherVO);
        schoolTeacherService.checkTeacherTelUnique(schoolTeacherVO);
        schoolTeacherService.checkIdCardUnique(schoolTeacherVO);
        if(StringUtils.isNotEmpty(schoolTeacherVO.getEmail())){
            schoolTeacherService.checkEmailUnique(schoolTeacherVO);
        }
        schoolTeacherVO.update();
        //如果是个人信息修改，则需要更新缓存
        if (getUserId().equals(schoolTeacherVO.getId())) {
            if (schoolTeacherService.updateTeacher(schoolTeacherVO) > 0) {
                // 更新缓存用户信息
                LoginUser loginUser = getLoginUser();
                SysUser sysUser = loginUser.getUser();
                sysUser.setUserName(schoolTeacherVO.getTeacherName());
                sysUser.setDeptId(schoolTeacherVO.getDeptId());
                sysUser.setPhonenumber(schoolTeacherVO.getTeacherTel());
                sysUser.setEmail(schoolTeacherVO.getEmail());
                sysUser.setSex(schoolTeacherVO.getSex());
                sysUser.setAvatar(schoolTeacherVO.getPicUrl());
                sysUser.setSign(schoolTeacherVO.getSign());
                tokenService.setLoginUser(loginUser);
                return AjaxResult.success();
            }
            return AjaxResult.error("修改个人信息异常，请联系管理员");
        }

        return toAjax(schoolTeacherService.updateTeacher(schoolTeacherVO));
    }

    /**
     * 删除学校老师byIdS
     */
    @Log(title = "学校老师", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable("ids") List<Long> ids) {
//        return AjaxResult.success(schoolTeacherService.deleteSchoolTeacherByIds(ids));
        return AjaxResult.success(schoolTeacherService.deleteTeacher(ids));
    }


    /**
     * 按行导出
     *
     * @param ids
     * @return
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        List<SchoolTeacher> list = schoolTeacherService.listByIds(ids);
        ExcelUtil<SchoolTeacher> util = new ExcelUtil<>(SchoolTeacher.class);
        util.exportExcel(response, list, "老师信息");
    }

    /**
     * 导出全部
     *
     * @param response
     * @param schoolTeacher
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolTeacherVO schoolTeacher) {
        List<SchoolTeacher> list = schoolTeacherService.selectSchoolTeacherList(schoolTeacher);
        ExcelUtil<SchoolTeacher> util = new ExcelUtil<>(SchoolTeacher.class);
        util.exportExcel(response, list, "老师信息");
    }

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

    @PostMapping("/importData")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<SchoolTeacher> util = new ExcelUtil<SchoolTeacher>(SchoolTeacher.class);
        List<SchoolTeacher> list = util.importExcel(file.getInputStream());
        //先校验
        schoolTeacherService.checkImport(list);
        //数据导入
        String message = schoolTeacherService.importData(list);
        return AjaxResult.success(message);
    }


    private void checkTeacherUnique(SchoolTeacherVO schoolTeacher) {
       /* LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolTeacher::getDeviceNum,schoolTeacher.getDeviceNum())
                .or()
                .eq(SchoolTeacher::getIdCard, schoolTeacher.getIdCard())
                .or()
                .eq(SchoolTeacher::getTeacherCode, schoolTeacher.getTeacherCode())
                .or()
                .eq(SchoolTeacher::getTeacherTel, schoolTeacher.getTeacherTel())
        ;*/
        //查询设备号
        if(StringUtils.isNotNull(schoolTeacher.getDeviceNum())){
            LambdaQueryWrapper<SchoolTeacher> lqw1 = new LambdaQueryWrapper<>();
            lqw1.notIn(SchoolTeacher::getId,schoolTeacher.getId())
                    .eq(SchoolTeacher::getDeviceNum,schoolTeacher.getDeviceNum());
            SchoolTeacher teacher = schoolTeacherService.getOne(lqw1);
            if (StringUtils.isNotNull(teacher)){
                throw new ServiceException("设备号已存在");
            }
//            if (StringUtils.isNotNull(schoolTeacher.getId()) && schoolTeacher.getId().equals(teacher.getId())) {
//
//            }else if(schoolTeacher.getDeviceNum().equals(teacher.getDeviceNum())){
//                throw new ServiceException("设备号已存在");
//            }
        }

        //查询身份证号
        if(StringUtils.isNotNull(schoolTeacher.getIdCard())){
            LambdaQueryWrapper<SchoolTeacher> lqw2 = new LambdaQueryWrapper<>();
            lqw2.notIn(SchoolTeacher::getId,schoolTeacher.getId())
                    .eq(SchoolTeacher::getIdCard,schoolTeacher.getIdCard());
            SchoolTeacher teacher = schoolTeacherService.getOne(lqw2);
            if (StringUtils.isNotNull(teacher)){
                throw new ServiceException("身份证号已存在");
            }
//            if (StringUtils.isNotNull(schoolTeacher.getId()) && schoolTeacher.getId().equals(teacher.getId())) {
//
//            }else if(schoolTeacher.getIdCard().equals(teacher.getIdCard())){
//                throw new ServiceException("身份证号已存在");
//            }
        }

        //查询编号
        if(StringUtils.isNotNull(schoolTeacher.getTeacherCode())){
            LambdaQueryWrapper<SchoolTeacher> lqw3 = new LambdaQueryWrapper<>();
            lqw3.notIn(SchoolTeacher::getId,schoolTeacher.getId())
                    .eq(SchoolTeacher::getTeacherCode,schoolTeacher.getTeacherCode());
            SchoolTeacher teacher = schoolTeacherService.getOne(lqw3);
            if (StringUtils.isNotNull(teacher)){
                throw new ServiceException("编号已存在");
            }
//            if (StringUtils.isNotNull(schoolTeacher.getId()) && schoolTeacher.getId().equals(teacher.getId())) {
//
//            }else if(schoolTeacher.getTeacherCode().equals(teacher.getTeacherCode())){
//                throw new ServiceException("编号已存在");
//            }
        }

        //查询电话号码
        if(StringUtils.isNotNull(schoolTeacher.getTeacherCode())){
            LambdaQueryWrapper<SchoolTeacher> lqw4 = new LambdaQueryWrapper<>();
            lqw4.notIn(SchoolTeacher::getId,schoolTeacher.getId())
                    .eq(SchoolTeacher::getTeacherTel,schoolTeacher.getTeacherTel());
            SchoolTeacher teacher = schoolTeacherService.getOne(lqw4);
            if (StringUtils.isNotNull(teacher)){
                throw new ServiceException("电话号码已存在");
            }
//            if (StringUtils.isNotNull(schoolTeacher.getId()) && schoolTeacher.getId().equals(teacher.getId())) {
//
//            }else if(schoolTeacher.getTeacherTel().equals(teacher.getTeacherTel())){
//                throw new ServiceException("电话号码已存在");
//            }
        }


       /* List<SchoolTeacher> teachers = schoolTeacherService.list(lqw);
        if (StringUtils.isNotNull(teachers) && teachers.size() > 0) {
            SchoolTeacher teacher = teachers.get(0);
            if (StringUtils.isNotNull(schoolTeacher.getId()) && schoolTeacher.getId().equals(teacher.getId())) {
                return;
            }
            if (StringUtils.isNotBlank(schoolTeacher.getTeacherCode()) && schoolTeacher.getTeacherCode().equals(teacher.getTeacherCode())) {
                throw new ServiceException("编号已存在");
            }
            if(schoolTeacher.getDeviceNum().equals(teacher.getDeviceNum())){
                throw new ServiceException("设备号已存在");
            }
            if (schoolTeacher.getIdCard().equals(teacher.getIdCard())) {
                throw new ServiceException("身份证号已存在");
            }
            if (schoolTeacher.getTeacherTel().equals(teacher.getTeacherTel())) {
                throw new ServiceException("电话号码已存在");
            }
        }*/

    }

    /**
     * 个人工作->基本信息
     */
    @GetMapping("/getProfile")
    public AjaxResult getProfile() {
        SchoolTeacher teacher = schoolTeacherService.getProfile();
        AjaxResult ajax = AjaxResult.success(teacher);
        //查询用户所属角色组
        List<SysRole> roleList = roleService.getRoleListByUserId(teacher.getId());
        if (CollectionUtils.isEmpty(roleList)) {
            ajax.put("roleGroup", StringUtils.EMPTY);
        } else {
            ajax.put("roleGroup", roleList.stream().map(SysRole::getRoleName).collect(Collectors.joining(",")));
        }
        List<SysPost> postList = postService.getPostListByUserId(teacher.getId());
        if (CollectionUtils.isEmpty(postList)) {
            ajax.put("postGroup", StringUtils.EMPTY);
        } else {
            ajax.put("postGroup", postList.stream().map(SysPost::getPostName).collect(Collectors.joining(",")));
        }
        return ajax;
    }

    /**
     * 个人工作->基本信息修改
     */
    @PutMapping("/editProfile")
    public AjaxResult editProfile(@Validated @RequestBody SchoolTeacherVO schoolTeacherVO) {
        if (StringUtils.isNull(schoolTeacherVO.getId())) {
            return AjaxResult.error("教师id未传");
        }
        checkTeacherUnique(schoolTeacherVO);
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getUser();
        //如果是个人信息修改，则需要更新缓存
        schoolTeacherService.editProfile(schoolTeacherVO);
        // 更新缓存用户信息
        sysUser.setUserName(schoolTeacherVO.getTeacherName());
        sysUser.setPhonenumber(schoolTeacherVO.getTeacherTel());
        sysUser.setEmail(schoolTeacherVO.getEmail());
        sysUser.setSex(schoolTeacherVO.getSex());
        //sysUser.setAvatar(schoolTeacherVO.getPicUrl());
        //sysUser.setSign(schoolTeacherVO.getSign());
        tokenService.setLoginUser(loginUser);
        return AjaxResult.success();
    }


    /**
     * 查询教师list(全部或者按职工类型是带班的)
     */
    @GetMapping("/getTeacherList")
    public TableDataInfo getTeacherList(SchoolTeacher teacher) {
        startPage();
        List<SchoolTeacher> list = schoolTeacherService.getAllTeachers(teacher);
        return getDataTable(list);
    }

    //职工信息状态修改
    @PutMapping("/changeState/{id}")
    public AjaxResult changeState(@PathVariable("id") Long id, String status) {
        if (StringUtils.isBlank(status)) {
            return AjaxResult.error("修改状态失败");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(id);
        sysUser.setStatus(status);
        return toAjax(userService.updateUserStatus(sysUser));
    }
}
