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

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
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.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.*;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolAclassTeacherAssessmentService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXteachingAchievementsService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.SchoolTeacherBasichlnformationService;

import javax.servlet.http.HttpServletResponse;

/**
 * 班主任考核Controller
 *
 * @author ruoyi
 * @date 2023-12-12
 */
@RestController
@RequestMapping("/assessment")
public class SchoolAclassTeacherAssessmentController extends BaseController
{
    @Autowired
    private ISchoolAclassTeacherAssessmentService schoolAclassTeacherAssessmentService;
    private Logger log = LoggerFactory.getLogger(SchoolAworkloadController.class);
    @Autowired
    private ISchoolXteachingAchievementsService schoolXteachingAchievementsService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SchoolTeacherBasichlnformationService basichlnformationService;

    /**
     * 查询班主任考核列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolAclassTeacherAssessmentReq req)
    {

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()){
            startPage();
            List<SchoolAclassTeacherAssessmentVo> list = schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentList(req);
            return getDataTable(list);
        }
        //全部权限
        List<SysRole> rolesList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("bzrkh_admin")).collect(Collectors.toList());
        if (rolesList.size() > 0){
            startPage();
            List<SchoolAclassTeacherAssessmentVo> list = schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentList(req);
            return getDataTable(list);
        }
        //本部门权限
        List<SysRole> rolesList1 = 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 (rolesList1.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){
                req.setIdCards(userIdCards);
            }
            if (roleList2.size() > 0){
                //根据当前登陆人手机号查询任教学科
                String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                req.setSub1(sub);
            }
            startPage();
            List<SchoolAclassTeacherAssessmentVo> list = schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentList(req);
            return getDataTable(list);
        }
        if (roleList2.size() > 0){
            //根据当前登陆人手机号查询任教学科
            String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
            req.setSub1(sub);
            startPage();
            List<SchoolAclassTeacherAssessmentVo> list = schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentList(req);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

    /**
     * 查询班主任考核列表 无权限过滤
     */
    @GetMapping("/listAll")
    public TableDataInfo listAll(SchoolAclassTeacherAssessmentReq req)
    {

        startPage();
        List<SchoolAclassTeacherAssessmentVo> list = schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentList(req);
        return getDataTable(list);

    }


    /**
     * 获取班主任考核详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolAclassTeacherAssessmentService.selectSchoolAclassTeacherAssessmentById(id));
    }

    /**
     * 新增班主任考核
     */
    @Log(title = "班主任考核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SchoolAclassTeacherAssessment schoolAclassTeacherAssessment)
    {
        return toAjax(schoolAclassTeacherAssessmentService.insertSchoolAclassTeacherAssessment(schoolAclassTeacherAssessment));
    }

    /**
     * 修改班主任考核
     */
    @Log(title = "班主任考核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SchoolAclassTeacherAssessment schoolAclassTeacherAssessment)
    {
        return toAjax(schoolAclassTeacherAssessmentService.updateSchoolAclassTeacherAssessment(schoolAclassTeacherAssessment));
    }

    /**
     * 删除班主任考核
     */
    @Log(title = "班主任考核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolAclassTeacherAssessmentService.deleteSchoolAclassTeacherAssessmentByIds(ids));
    }

    /**
     * 末班下载
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/download")
    public void downloadFile(HttpServletResponse response) throws Exception {
        // 以流的形式下载文件。
        try {
            //读取文件
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/班主任任职导入模板.xlsx");
            InputStream fis = new BufferedInputStream(resourceAsStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("班主任导入模板.xlsx", "utf-8"));
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        List<SchoolAclassTeacherAssessment> list = new ArrayList<>();
        ExcelUtil<SchoolAclassTeacherAssessment> util = new ExcelUtil<SchoolAclassTeacherAssessment>(SchoolAclassTeacherAssessment.class);
        List<SchoolAclassTeacherAssessment> detailList = util.importExceltoRow(file.getInputStream(),1);
        //1.导入
        return schoolAclassTeacherAssessmentService.saveCheckedDate(detailList);
    }

    /**
     * 导出
     * @param
     * @return
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolAclassTeacherAssessmentReq req ) throws Exception{

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()){
            List<SchoolAclassTeacherAssessment> schoolAclassTeacherAssessmentVos = schoolAclassTeacherAssessmentService.selectSchoolList(req);
            List<SchoolAclassTeacherAssessmentExport> list = new ArrayList<>();
            for (SchoolAclassTeacherAssessment schoolAclassTeacherAssessmentVo : schoolAclassTeacherAssessmentVos) {
                SchoolAclassTeacherAssessmentExport schoolAclassTeacherAssessmentExport = new SchoolAclassTeacherAssessmentExport();
                BeanUtils.copyProperties(schoolAclassTeacherAssessmentVo,schoolAclassTeacherAssessmentExport);
                list.add(schoolAclassTeacherAssessmentExport);
            }
            ExcelUtil<SchoolAclassTeacherAssessmentExport> util = new ExcelUtil<>(SchoolAclassTeacherAssessmentExport.class);
            util.exportExcel(response, list, "老师考核");
        }else {
            //全部权限
            List<SysRole> rolesList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("bzrkh_admin")).collect(Collectors.toList());
            if (rolesList.size() > 0){
                List<SchoolAclassTeacherAssessment> schoolAclassTeacherAssessmentVos = schoolAclassTeacherAssessmentService.selectSchoolList(req);
                List<SchoolAclassTeacherAssessmentExport> list = new ArrayList<>();
                for (SchoolAclassTeacherAssessment schoolAclassTeacherAssessmentVo : schoolAclassTeacherAssessmentVos) {
                    SchoolAclassTeacherAssessmentExport schoolAclassTeacherAssessmentExport = new SchoolAclassTeacherAssessmentExport();
                    BeanUtils.copyProperties(schoolAclassTeacherAssessmentVo,schoolAclassTeacherAssessmentExport);
                    list.add(schoolAclassTeacherAssessmentExport);
                }
                ExcelUtil<SchoolAclassTeacherAssessmentExport> util = new ExcelUtil<>(SchoolAclassTeacherAssessmentExport.class);
                util.exportExcel(response, list, "老师考核");
            }else {
                //本部门权限
                List<SysRole> rolesList1 = 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 (rolesList1.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){
                        req.setIdCards(userIdCards);
                    }
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        req.setSub1(sub);
                    }
                    List<SchoolAclassTeacherAssessment> schoolAclassTeacherAssessmentVos = schoolAclassTeacherAssessmentService.selectSchoolList(req);
                    List<SchoolAclassTeacherAssessmentExport> list = new ArrayList<>();
                    for (SchoolAclassTeacherAssessment schoolAclassTeacherAssessmentVo : schoolAclassTeacherAssessmentVos) {
                        SchoolAclassTeacherAssessmentExport schoolAclassTeacherAssessmentExport = new SchoolAclassTeacherAssessmentExport();
                        BeanUtils.copyProperties(schoolAclassTeacherAssessmentVo,schoolAclassTeacherAssessmentExport);
                        list.add(schoolAclassTeacherAssessmentExport);
                    }
                    ExcelUtil<SchoolAclassTeacherAssessmentExport> util = new ExcelUtil<>(SchoolAclassTeacherAssessmentExport.class);
                    util.exportExcel(response, list, "老师考核");
                }else{
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        req.setSub1(sub);
                        List<SchoolAclassTeacherAssessment> schoolAclassTeacherAssessmentVos = schoolAclassTeacherAssessmentService.selectSchoolList(req);
                        List<SchoolAclassTeacherAssessmentExport> list = new ArrayList<>();
                        for (SchoolAclassTeacherAssessment schoolAclassTeacherAssessmentVo : schoolAclassTeacherAssessmentVos) {
                            SchoolAclassTeacherAssessmentExport schoolAclassTeacherAssessmentExport = new SchoolAclassTeacherAssessmentExport();
                            BeanUtils.copyProperties(schoolAclassTeacherAssessmentVo,schoolAclassTeacherAssessmentExport);
                            list.add(schoolAclassTeacherAssessmentExport);
                        }
                        ExcelUtil<SchoolAclassTeacherAssessmentExport> util = new ExcelUtil<>(SchoolAclassTeacherAssessmentExport.class);
                        util.exportExcel(response, list, "老师考核");
                    }else {
                        ExcelUtil<SchoolAclassTeacherAssessmentExport> util = new ExcelUtil<>(SchoolAclassTeacherAssessmentExport.class);
                        util.exportExcel(response, new ArrayList<>(), "老师考核");
                    }
                }
            }
        }
    }
}
