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

import java.io.*;
import java.util.ArrayList;
import java.util.List;
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.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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 org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolAnnualAssessment.SchoolAnnualAssessment;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.SchoolXsyouthTeacher;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.SchoolXteachingAchievements;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXsyouthTeacherService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXteachingAchievementsService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.SchoolTeacherBasichlnformationService;
import yangtz.cs.liu.campus.vo.schoolAnnualAssessment.SchoolAnnualAssessmentVo;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXsyouthTeacherDrVo;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXsyouthTeacherVo;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXteachingAchievementsVo;

/**
 * 青年教师成长档案Controller
 *
 * @author ruoyi
 * @date 2024-01-29
 */
@Slf4j
@RestController
@RequestMapping("/school/youthTeacher")
public class SchoolXsyouthTeacherController extends BaseController
{
    @Autowired
    private ISchoolXsyouthTeacherService schoolXsyouthTeacherService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISchoolXteachingAchievementsService schoolXteachingAchievementsService;
    @Autowired
    private SchoolTeacherBasichlnformationService basichlnformationService;

    /**
     * 查询青年教师成长档案列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolXsyouthTeacherVo schoolXsyouthTeacherVo)
    {
        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()) {
            startPage();
            List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
            return getDataTable(list);
        }
        //全部权限
        List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("qnjscz_admin")).collect(Collectors.toList());
        if (roleList.size() > 0){
            startPage();
            List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
            return getDataTable(list);
        }
        //部分权限
        List<SysRole> roleList1 = roles.stream().filter(role -> role.getRoleKey().equals("jsdnzj_admin")).collect(Collectors.toList());
        if (roleList1.size() > 0 ){
            //教师电子档案中级管理员只能查看本部门及部门以下的数据
            //根据用户部门id查询用户部门信息
            SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
            //获取当前登陆人部门下所有人的手机号
            List<String> userPhones = schoolXteachingAchievementsService.getUserPhonesByDeptId(sysDept.getDeptId());
            //根据用户手机号查询用户身份证信息
            List<String> userIdCards = basichlnformationService.selectIdCardsByDdPhone(userPhones);
            if (userIdCards.size() > 0){
                schoolXsyouthTeacherVo.setIdCards(userIdCards);
            }
            startPage();
            List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

    /**
     * 下载附件
     * @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());
        }
    }

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

    /**
     * 导出青年教师成长档案列表
     */
    @Log(title = "青年教师成长档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolXsyouthTeacherVo schoolXsyouthTeacherVo)
    {
        int i = 0;

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()) {
            List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
            List<SchoolXsyouthTeacherVo> exportList = new ArrayList<>();
            for (SchoolXsyouthTeacher xsyouthTeacher : list) {
                //转vo
                SchoolXsyouthTeacherVo schoolXsyouthTeacherVo1 = new SchoolXsyouthTeacherVo();
                BeanUtils.copyProperties(xsyouthTeacher,schoolXsyouthTeacherVo1);
                i ++ ;
                schoolXsyouthTeacherVo1.setXh(i);
                exportList.add(schoolXsyouthTeacherVo1);
            }
            ExcelUtil<SchoolXsyouthTeacherVo> util = new ExcelUtil<SchoolXsyouthTeacherVo>(SchoolXsyouthTeacherVo.class);
            util.exportExcel(response, exportList, "青年教师成长档案数据");
        }else {
            //全部权限
            List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("qnjscz_admin")).collect(Collectors.toList());
            if (roleList.size() > 0){
                List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
                List<SchoolXsyouthTeacherVo> exportList = new ArrayList<>();
                for (SchoolXsyouthTeacher xsyouthTeacher : list) {
                    //转vo
                    SchoolXsyouthTeacherVo schoolXsyouthTeacherVo1 = new SchoolXsyouthTeacherVo();
                    BeanUtils.copyProperties(xsyouthTeacher,schoolXsyouthTeacherVo1);
                    i ++ ;
                    schoolXsyouthTeacherVo1.setXh(i);
                    exportList.add(schoolXsyouthTeacherVo1);
                }
                ExcelUtil<SchoolXsyouthTeacherVo> util = new ExcelUtil<SchoolXsyouthTeacherVo>(SchoolXsyouthTeacherVo.class);
                util.exportExcel(response, exportList, "青年教师成长档案数据");
            }else {
                //部分权限
                List<SysRole> roleList1 = roles.stream().filter(role -> role.getRoleKey().equals("jsdnzj_admin")).collect(Collectors.toList());
                if (roleList1.size() > 0){
                    //教师电子档案中级管理员只能查看本部门及部门以下的数据
                    //根据用户部门id查询用户部门信息
                    SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
                    //获取当前登陆人部门下所有人的手机号
                    List<String> userPhones = schoolXteachingAchievementsService.getUserPhonesByDeptId(sysDept.getDeptId());
                    //根据用户手机号查询用户身份证信息
                    List<String> userIdCards = basichlnformationService.selectIdCardsByDdPhone(userPhones);
                    if (userIdCards.size() > 0){
                        schoolXsyouthTeacherVo.setIdCards(userIdCards);
                    }
                    List<SchoolXsyouthTeacher> list = schoolXsyouthTeacherService.selectSchoolXsyouthTeacherList(schoolXsyouthTeacherVo);
                    List<SchoolXsyouthTeacherVo> exportList = new ArrayList<>();
                    for (SchoolXsyouthTeacher xsyouthTeacher : list) {
                        //转vo
                        SchoolXsyouthTeacherVo schoolXsyouthTeacherVo1 = new SchoolXsyouthTeacherVo();
                        BeanUtils.copyProperties(xsyouthTeacher,schoolXsyouthTeacherVo1);
                        i ++ ;
                        schoolXsyouthTeacherVo1.setXh(i);
                        exportList.add(schoolXsyouthTeacherVo1);
                    }
                    ExcelUtil<SchoolXsyouthTeacherVo> util = new ExcelUtil<SchoolXsyouthTeacherVo>(SchoolXsyouthTeacherVo.class);
                    util.exportExcel(response, exportList, "青年教师成长档案数据");
                }else{
                    ExcelUtil<SchoolXsyouthTeacherVo> util = new ExcelUtil<SchoolXsyouthTeacherVo>(SchoolXsyouthTeacherVo.class);
                    util.exportExcel(response, new ArrayList<>(), "青年教师成长档案数据");
                }
            }
        }
    }

    /**
     * 获取青年教师成长档案详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolXsyouthTeacherService.selectSchoolXsyouthTeacherById(id));
    }

    /**
     * 新增青年教师成长档案
     */
    @Log(title = "青年教师成长档案", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SchoolXsyouthTeacher schoolXsyouthTeacher)
    {
        return toAjax(schoolXsyouthTeacherService.insertSchoolXsyouthTeacher(schoolXsyouthTeacher));
    }

    /**
     * 修改青年教师成长档案
     */
    @Log(title = "青年教师成长档案", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SchoolXsyouthTeacher schoolXsyouthTeacher)
    {
        return toAjax(schoolXsyouthTeacherService.updateSchoolXsyouthTeacher(schoolXsyouthTeacher));
    }

    /**
     * 删除青年教师成长档案
     */
    @Log(title = "青年教师成长档案", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolXsyouthTeacherService.deleteSchoolXsyouthTeacherByIds(ids));
    }
}
