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.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.ISchoolAworkloadService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXteachingAchievementsService;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.SchoolTeacherBasichlnformationService;

/**
 * 工作量信息Controller
 *
 * @author ruoyi
 * @date 2023-12-11
 */
@RestController
@RequestMapping("/aworkload")
public class SchoolAworkloadController extends BaseController
{
    @Autowired
    private ISchoolAworkloadService schoolAworkloadService;
    private Logger log = LoggerFactory.getLogger(SchoolAworkloadController.class);
    @Autowired
    private ISchoolXteachingAchievementsService schoolXteachingAchievementsService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SchoolTeacherBasichlnformationService basichlnformationService;

    /**
     * 查询工作量信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolAworkloadVo schoolAworkloadVo)
    {

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()){
            startPage();
            List<SchoolAworkloadVo> list = schoolAworkloadService.selectSchoolAworkloadList(schoolAworkloadVo);
            return getDataTable(list);
        }
        //全部权限
        List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("gzl_admin")).collect(Collectors.toList());
        if (roleList.size() > 0){
            startPage();
            List<SchoolAworkloadVo> list = schoolAworkloadService.selectSchoolAworkloadList(schoolAworkloadVo);
            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){
            //教师电子档案中级管理员只能看本部门及以下的数据
            //获取当前登陆人的部门信息
            SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
            //获取当前登陆人部门下所有人的手机号
            List<String> userPhones = schoolXteachingAchievementsService.getUserPhonesByDeptId(sysDept.getDeptId());
            //根据用户手机号查询用户身份证信息
            List<String> userIdCards = basichlnformationService.selectIdCardsByDdPhone(userPhones);
            if (userIdCards.size() > 0){
                schoolAworkloadVo.setIdCards(userIdCards);
            }
            if (roleList2.size() > 0){
                //根据当前登陆人手机号查询任教学科
                String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                schoolAworkloadVo.setSub1(sub);
            }
            startPage();
            List<SchoolAworkloadVo> list = schoolAworkloadService.selectSchoolAworkloadList(schoolAworkloadVo);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }


    /**
     * 获取工作量信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolAworkloadService.selectSchoolAworkloadById(id));
    }

    /**
     * 新增工作量信息
     */
    @Log(title = "工作量信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SchoolAworkload schoolAworkload)
    {
        return toAjax(schoolAworkloadService.insertSchoolAworkload(schoolAworkload));
    }

    /**
     * 修改工作量信息
     */
    @Log(title = "工作量信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SchoolAworkload schoolAworkload)
    {
        return toAjax(schoolAworkloadService.updateSchoolAworkload(schoolAworkload));
    }

    /**
     * 删除工作量信息
     */
    @Log(title = "工作量信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolAworkloadService.deleteSchoolAworkloadByIds(ids));
    }

    @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<SchoolAworkload> list = new ArrayList<>();
        ExcelUtil<SchoolAworkloadExport> util = new ExcelUtil<SchoolAworkloadExport>(SchoolAworkloadExport.class);
        List<SchoolAworkloadExport> detailList = util.importExceltoRow(file.getInputStream(),1);
        //1.导入
        for (SchoolAworkloadExport date :detailList){
            SchoolAworkload schoolAworkload = new SchoolAworkload();
            BeanUtils.copyProperties(date,schoolAworkload);
            list.add(schoolAworkload);
        }
        return schoolAworkloadService.saveAndChecked(list);
    }

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

        //获取当前登陆人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取当前登陆人的角色信息
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()){
            List<SchoolAworkloadExport> schoolAworkloadVos = schoolAworkloadService.selectAworkloadList(schoolAworkloadVo);
            List<SchoolAworkloadDc> list =  new ArrayList<>();
            for (SchoolAworkloadExport aworkloadVo : schoolAworkloadVos) {
                SchoolAworkloadDc schoolAworkloadDc = new SchoolAworkloadDc();
                BeanUtils.copyProperties(aworkloadVo,schoolAworkloadDc);
                list.add(schoolAworkloadDc);
            }
            ExcelUtil<SchoolAworkloadDc> util = new ExcelUtil<>(SchoolAworkloadDc.class);
            util.exportExcel(response, list, "工作量内容");
        }else {

            //全部权限
            List<SysRole> roleList = roles.stream().filter(role -> role.getRoleKey().equals("jsdzdncj_admin") || role.getRoleKey().equals("gzl_admin")).collect(Collectors.toList());
            if (roleList.size() > 0){
                List<SchoolAworkloadExport> schoolAworkloadVos = schoolAworkloadService.selectAworkloadList(schoolAworkloadVo);
                List<SchoolAworkloadDc> list =  new ArrayList<>();
                for (SchoolAworkloadExport aworkloadVo : schoolAworkloadVos) {
                    SchoolAworkloadDc schoolAworkloadDc = new SchoolAworkloadDc();
                    BeanUtils.copyProperties(aworkloadVo,schoolAworkloadDc);
                    list.add(schoolAworkloadDc);
                }
                ExcelUtil<SchoolAworkloadDc> util = new ExcelUtil<>(SchoolAworkloadDc.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){
                        schoolAworkloadVo.setIdCards(userIdCards);
                    }
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        schoolAworkloadVo.setSub1(sub);
                    }
                    List<SchoolAworkloadExport> schoolAworkloadVos = schoolAworkloadService.selectAworkloadList(schoolAworkloadVo);
                    List<SchoolAworkloadDc> list =  new ArrayList<>();
                    for (SchoolAworkloadExport aworkloadVo : schoolAworkloadVos) {
                        SchoolAworkloadDc schoolAworkloadDc = new SchoolAworkloadDc();
                        BeanUtils.copyProperties(aworkloadVo,schoolAworkloadDc);
                        list.add(schoolAworkloadDc);
                    }
                    ExcelUtil<SchoolAworkloadDc> util = new ExcelUtil<>(SchoolAworkloadDc.class);
                    util.exportExcel(response, list, "工作量内容");
                }else {
                    if (roleList2.size() > 0){
                        //根据当前登陆人手机号查询任教学科
                        String sub = basichlnformationService.selectSubByDdPhone(user.getPhonenumber());
                        schoolAworkloadVo.setSub1(sub);
                        List<SchoolAworkloadExport> schoolAworkloadVos = schoolAworkloadService.selectAworkloadList(schoolAworkloadVo);
                        List<SchoolAworkloadDc> list =  new ArrayList<>();
                        for (SchoolAworkloadExport aworkloadVo : schoolAworkloadVos) {
                            SchoolAworkloadDc schoolAworkloadDc = new SchoolAworkloadDc();
                            BeanUtils.copyProperties(aworkloadVo,schoolAworkloadDc);
                            list.add(schoolAworkloadDc);
                        }
                        ExcelUtil<SchoolAworkloadDc> util = new ExcelUtil<>(SchoolAworkloadDc.class);
                        util.exportExcel(response, list, "工作量内容");
                    }else {
                        ExcelUtil<SchoolAworkloadDc> util = new ExcelUtil<>(SchoolAworkloadDc.class);
                        util.exportExcel(response, new ArrayList<>(), "工作量内容");
                    }
                }
            }
        }
    }
}
