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

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

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.SchoolGkAchievementVo;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.SchoolXteachingAchievements;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXteachingAchievementsService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.SchoolTeacherBasichlnformationService;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXacademicWorksVo;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXteachingAchievementsVo;

/**
 * 教学成绩Controller
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@RestController
@RequestMapping("/system/achievements")
public class SchoolXteachingAchievementsController extends BaseController
{
    @Autowired
    private ISchoolXteachingAchievementsService schoolXteachingAchievementsService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SchoolTeacherBasichlnformationService basichlnformationService;

    /**
     * 查询教学成绩列表
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:list')")
    @GetMapping("/list")
    public TableDataInfo list(SchoolXteachingAchievementsVo schoolXteachingAchievementsVo)
    {

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()) {
            startPage();
            List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
            return getDataTable(list);
        }

        //全部权限
        List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("jxcj_admin")).collect(Collectors.toList());
        if (roleList.size() > 0){
            startPage();
            List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
            return getDataTable(list);
        }
        //部分权限
        List<SysRole> roleList1 = roles.stream().filter(role -> role.getRoleKey().equals("jsdnzj_admin")).collect(Collectors.toList());
        //查询是否包含学科组长角色
        List<SysRole> roleList2 = roles.stream().filter(role -> role.getRoleKey().equals("sub_leader")).collect(Collectors.toList());
        if (roleList1.size() > 0 ){
            //教师电子档案中级管理员只能查看本部门及部门以下的数据
//                Long deptId = null;
            //根据用户部门id查询用户部门信息
            SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
            //判断用户部门属于科室还是级部
            //查询所有级部id
//                List<Long> jbDeptIds = schoolXteachingAchievementsService.getJbDeptId();
//                //查询所有科室id
//                List<Long> ksDeptIds = schoolXteachingAchievementsService.getKsDeptId();
//                for (Long jbDeptId : jbDeptIds) {
//                    if (sysDept.getAncestors().contains(jbDeptId.toString())){
//                        deptId = jbDeptId;
//                    }else {
//                        String[] split = sysDept.getAncestors().split(",");
//                        if (split.length == 2){
//                            deptId = sysDept.getDeptId();
//                        }
//                    }
//                }
//                if (StringUtils.isNull(deptId)){
//                    for (Long ksDeptId : ksDeptIds) {
//                        if (sysDept.getAncestors().contains(ksDeptId.toString())){
//                            deptId = ksDeptId;
//                        }else {
//                            String[] split = sysDept.getAncestors().split(",");
//                            if (split.length == 3){
//                                deptId = sysDept.getDeptId();
//                            }
//                        }
//                    }
//                }
            //获取当前登陆人部门下所有人的手机号
            List<String> userPhones = schoolXteachingAchievementsService.getUserPhonesByDeptId(sysDept.getDeptId());
            //根据用户手机号查询用户身份证信息
            List<String> userIdCards = basichlnformationService.selectIdCardsByDdPhone(userPhones);
            if (userIdCards.size() > 0){
                schoolXteachingAchievementsVo.setIdCards(userIdCards);
            }
            if (roleList2.size() > 0){
                //根据当前登陆人手机号查询任教学科
                String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                schoolXteachingAchievementsVo.setSub1(sub);
            }
            startPage();
            List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
            return getDataTable(list);
        }
        if (roleList2.size() > 0){
            //根据当前登陆人手机号查询任教学科
            String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
            schoolXteachingAchievementsVo.setSub1(sub);
            startPage();
            List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

    /**
     * 导出教学成绩列表
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:export')")
    @Log(title = "教学成绩", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolXteachingAchievementsVo schoolXteachingAchievementsVo)
    {
        int i = 0;

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()) {
            List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
            for (SchoolXteachingAchievementsVo schoolXteachingAchievementsVo1 : list) {
                i ++;
                schoolXteachingAchievementsVo1.setXh(i);
            }
            ExcelUtil<SchoolXteachingAchievementsVo> util = new ExcelUtil<SchoolXteachingAchievementsVo>(SchoolXteachingAchievementsVo.class);
            util.exportExcel(response, list, "教学成绩数据");
        }else {

            //全部权限
            List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("jxcj_admin")).collect(Collectors.toList());
            if (roleList.size() > 0){
                List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
                for (SchoolXteachingAchievementsVo schoolXteachingAchievementsVo1 : list) {
                    i ++;
                    schoolXteachingAchievementsVo1.setXh(i);
                }
                ExcelUtil<SchoolXteachingAchievementsVo> util = new ExcelUtil<SchoolXteachingAchievementsVo>(SchoolXteachingAchievementsVo.class);
                util.exportExcel(response, list, "教学成绩数据");
            }else{
                //部分权限
                List<SysRole> roleList1 = roles.stream().filter(role -> role.getRoleKey().equals("jsdnzj_admin")).collect(Collectors.toList());
                //查询是否包含学科组长角色
                List<SysRole> roleList2 = roles.stream().filter(role -> role.getRoleKey().equals("sub_leader")).collect(Collectors.toList());
                if (roleList1.size() > 0 ){
                    SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
                    //获取当前登陆人部门下所有人的手机号
                    List<String> userPhones = schoolXteachingAchievementsService.getUserPhonesByDeptId(sysDept.getDeptId());
                    //根据用户手机号查询用户身份证信息
                    List<String> userIdCards = basichlnformationService.selectIdCardsByDdPhone(userPhones);
                    if (userIdCards.size() > 0){
                        schoolXteachingAchievementsVo.setIdCards(userIdCards);
                    }
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        schoolXteachingAchievementsVo.setSub1(sub);
                    }
                    List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
                    for (SchoolXteachingAchievementsVo schoolXteachingAchievementsVo1 : list) {
                        i ++;
                        schoolXteachingAchievementsVo1.setXh(i);
                    }
                    ExcelUtil<SchoolXteachingAchievementsVo> util = new ExcelUtil<SchoolXteachingAchievementsVo>(SchoolXteachingAchievementsVo.class);
                    util.exportExcel(response, list, "教学成绩数据");
                }else {
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        schoolXteachingAchievementsVo.setSub1(sub);
                        List<SchoolXteachingAchievementsVo> list = schoolXteachingAchievementsService.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
                        for (SchoolXteachingAchievementsVo schoolXteachingAchievementsVo1 : list) {
                            i ++;
                            schoolXteachingAchievementsVo1.setXh(i);
                        }
                        ExcelUtil<SchoolXteachingAchievementsVo> util = new ExcelUtil<SchoolXteachingAchievementsVo>(SchoolXteachingAchievementsVo.class);
                        util.exportExcel(response, list, "教学成绩数据");
                    } else {
                        ExcelUtil<SchoolXteachingAchievementsVo> util = new ExcelUtil<SchoolXteachingAchievementsVo>(SchoolXteachingAchievementsVo.class);
                        util.exportExcel(response, new ArrayList<>(), "教学成绩数据");
                    }
                }
            }

        }
    }

    /*
     * 下载模板
     * */
    @PostMapping("/importTemplate")
    public void importTemplate (HttpServletResponse response) {
        schoolXteachingAchievementsService.importTemplate(response);
    }

    /**
     * 导入教学成绩
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:importData')")
    @PostMapping("/importData")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<SchoolXteachingAchievements> util = new ExcelUtil<SchoolXteachingAchievements>(SchoolXteachingAchievements.class);
        List<SchoolXteachingAchievements> list = util.importExcelNdkh(file.getInputStream());
        //先校验
        schoolXteachingAchievementsService.checkImport(list);
        //数据导入
        String message = schoolXteachingAchievementsService.importData(list);
        return AjaxResult.success(message);
    }

    /**
     * 获取教学成绩详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolXteachingAchievementsService.selectSchoolXteachingAchievementsById(id));
    }

    /**
     * 新增教学成绩
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:add')")
    @Log(title = "教学成绩", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SchoolXteachingAchievements schoolXteachingAchievements)
    {
        return toAjax(schoolXteachingAchievementsService.insertSchoolXteachingAchievements(schoolXteachingAchievements));
    }

    /**
     * 修改教学成绩
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:edit')")
    @Log(title = "教学成绩", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SchoolXteachingAchievements schoolXteachingAchievements)
    {
        return toAjax(schoolXteachingAchievementsService.updateSchoolXteachingAchievements(schoolXteachingAchievements));
    }

    /**
     * 删除教学成绩
     */
//    @PreAuthorize("@ss.hasPermi('system:achievements:remove')")
    @Log(title = "教学成绩", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolXteachingAchievementsService.deleteSchoolXteachingAchievementsByIds(ids));
    }

    /**
     * 获取所有用户
     */
    @GetMapping("/getUserList")
    public TableDataInfo getUserList(SysUser sysUser){
        startPage();
        List<Map<String, Object>> list = schoolXteachingAchievementsService.getUserList(sysUser);
        return getDataTable(list);
    }
}
