package com.zd.laboratory.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.constant.SecurityConstants;
import com.zd.common.core.domain.R;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.core.utils.UrlFormatUtils;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.LabSecurityApply;
import com.zd.laboratory.domain.LabSecurityMaterialrelation;
import com.zd.laboratory.domain.LabSubject;
import com.zd.laboratory.domain.vo.LabSecurityApplyExcelVO;
import com.zd.laboratory.domain.vo.LabSecurityApplyVO;
import com.zd.laboratory.domain.vo.LabSecurityMaterialDataVO;
import com.zd.laboratory.service.ILabSecurityApplyService;
import com.zd.laboratory.service.ILabSecurityMaterialDataService;
import com.zd.laboratory.service.ILabSecurityMaterialrelationService;
import com.zd.laboratory.service.ILabSubjectService;
import com.zd.system.api.RemoteUserService;
import com.zd.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 安全准入申请Controller
 *
 * @author zd
 * @date 2022-01-24
 */
@RestController
@Api(tags = "【安全准入申请】")
@RequestMapping("/apply")
public class LabSecurityApplyController extends BaseController
{
    @Autowired
    private ILabSecurityApplyService labSecurityApplyService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ILabSecurityMaterialDataService labSecurityMaterialDataService;

    @Autowired
    private ILabSubjectService iLabSubjectService;

    @Autowired
    private ILabSecurityMaterialrelationService iLabSecurityMaterialrelationService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private FileConfigUtils fileConfigUtils;

    /**
     * 查询安全准入申请列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "查询安全准入申请列表")
    public TableDataInfo<LabSecurityApplyVO> list(LabSecurityApplyVO labSecurityApplyVO)
    {
        //获取登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        if("00".equals(sysUser.getUserType())){
            //系统用户按部门查询
            labSecurityApplyVO.setDeptId(sysUser.getDeptId());
        }else if("11".equals(sysUser.getUserType())){
            //教职工登录，实验室负责人为当前用户的数据
            labSecurityApplyVO.setSubjectAdminid(sysUser.getUserId());
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            //labSecurityApply.setUserId(sysUser.getUserId());// 学生登录(学生无审核权限)，申请人id 为当前用户id的数据
            return getDataTable(new ArrayList());
        }

        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     *  审批 列表
     */
    //@PreAuthorize(hasPermi = "laboratory:apply:list")
    @GetMapping("/listapproval")
    public TableDataInfo<LabSecurityApplyVO> listapproval(LabSecurityApplyVO labSecurityApplyVO)
    {
        //获取登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        labSecurityApplyVO.setAuditId(sysUser.getUserId());// 审核人id 为当前用户id的数据
        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     *  申请 列表
     */
    //@PreAuthorize(hasPermi = "laboratory:apply:list")
    @GetMapping("/listapply")
    public TableDataInfo<LabSecurityApplyVO> listapply(LabSecurityApplyVO labSecurityApplyVO)
    {
        //获取登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        //判断当前登录用户角色
        /*if("00".equals(sysUser.getUserType())){
            labSecurityApplyVO.setDeptId(sysUser.getDeptId());// 系统用户按部门查询
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            // 申请人id 为当前用户id的数据
        }*/
        // 只查自己数据
        labSecurityApplyVO.setUserId(sysUser.getUserId());
        //labSecurityApplyVO.setRemark("1");//标注查询未通过的审核 0待审核 1驳回 的数据 (2022-04-08 需求突然变更去除校验)

        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     * 导出安全准入申请列表
     */
    @ApiOperation(value = "导出安全准入申请列表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.EXPORT)
    @Log(title = "安全准入申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabSecurityApplyVO labSecurityApplyVO) throws IOException
    {
        //获取登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){
            labSecurityApplyVO.setDeptId(sysUser.getDeptId());// 系统用户按部门查询
        }else if("11".equals(sysUser.getUserType())){
            labSecurityApplyVO.setSubjectAdminid(sysUser.getUserId());// 教职工登录，实验室负责人为当前用户的数据
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            //labSecurityApply.setUserId(sysUser.getUserId());// 学生登录(学生无审核权限)，申请人id 为当前用户id的数据
        }
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVO);
        List<LabSecurityApplyExcelVO> excelList = new ArrayList<>();
        Optional.ofNullable(list).orElseGet(Collections::emptyList).stream()
                .forEach(a->{
                    LabSecurityApplyExcelVO securityApplyExcelVO = new LabSecurityApplyExcelVO();
                    BeanUtils.copyProperties(a,securityApplyExcelVO);
                    if(StringUtils.isNotEmpty(a.getUserType())){
                        if(a.getUserType().equals("00")){
                            securityApplyExcelVO.setUserType("系统");
                        }else if(a.getUserType().equals("11")){
                            securityApplyExcelVO.setUserType("教职工");
                        }else if(a.getUserType().equals(UserConstants.USER_TYPE_STUDENT)){
                            securityApplyExcelVO.setUserType("学生");
                        }else if(a.getUserType().equals("99")){
                            securityApplyExcelVO.setUserType("大屏");
                        }
                    }
                    excelList.add(securityApplyExcelVO);
                });


        ExcelUtil<LabSecurityApplyExcelVO> util = new ExcelUtil<LabSecurityApplyExcelVO>(LabSecurityApplyExcelVO.class);
        util.exportExcel(response, excelList, "安全准入申请数据");
    }

    /**
     * 获取安全准入申请详细信息
     */
    @ApiOperation(value = "获取安全准入申请详细信息")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public ResultData<LabSecurityApply> getInfo(@PathVariable("id") Long id)
    {
        return ResultData.success(labSecurityApplyService.selectLabSecurityApplyById(id));
    }

    /**
     * 获取安全准入申请详细信息 PC
     */
    @ApiOperation(value = "获取安全准入申请详细信息")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.QUERY)
    @GetMapping(value = "/getDetails")
    public AjaxResult  getDetails( Long id)
    {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getDetailsById(id);
        return AjaxResult.success(map);
    }

    /**
     * 获取安全准入申请详细信息- 小程序
     * @param id
     * @return
     */
    @GetMapping(value = "/getDetailsApp")
    public AjaxResult  getDetailsApp( Long id)
    {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getDetailsById(id);
        return AjaxResult.success(map);
    }

    public Map<String, Object> getDetailsById( Long id){
        Map<String, Object> map =new HashMap<String, Object>();
        //查询申请信息
        LabSecurityApplyVO labSecurityApply= labSecurityApplyService.selectLabSecurityApplyById(id);

        //根据id查询用户信息
        R<SysUser> rDate =remoteUserService.getUserInfoByUserId(labSecurityApply.getUserId(), SecurityConstants.INNER);
        SysUser  sysUser = rDate.getData();

        /*if("login".equals(userType)){
            //查询登录用户信息
            sysUser = tokenService.getLoginUser().getSysUser();
        }else{
            //根据id查询用户信息
            R<SysUser> rDate =remoteUserService.getUserInfoByUserId(labSecurityApply.getUserId(), SecurityConstants.INNER);
            sysUser = rDate.getData();
        }*/
        List<LabSecurityMaterialDataVO> listTemp=Collections.emptyList();//模板
        List<Map<String, Object>> listcert = Collections.emptyList();//学生考试证数
        List<Map<String, Object>> fzrsysUser = Collections.emptyList();//实验室负责人

        //根据实验室ID查询实验室信息
        LabSubject labSubject =iLabSubjectService.selectLabSubjectById(labSecurityApply.getSubjectId());
        if(labSubject!=null){
            //根据实验室负责人查询出负责人信息
            fzrsysUser=labSecurityApplyService.selectLabsubjectUserInfo(labSubject.getAdminId());
        }

        //获取学生考试证数
        listcert = labSecurityApplyService.selectUserCertList(labSecurityApply.getUserId());

        //学生登录
        if(UserConstants.USER_TYPE_STUDENT.equals(labSecurityApply.getUserType())){
            //获取学生考试证数
            listcert = labSecurityApplyService.selectUserCertList(labSecurityApply.getUserId());
            //模板查询
            listTemp =labSecurityMaterialDataService.selectLabSecurityMaterialDataStudent(labSecurityApply.getSubjectId());
            for (int i=0;i<listTemp.size();i++){
                //如果是关联模板 查询出具体关联的内容
                if(1==listTemp.get(i).getMaterialType()){
                    //上传材料查询
                    LabSecurityMaterialrelation lmr = new LabSecurityMaterialrelation();
                    lmr.setApplyId(labSecurityApply.getId());
                    lmr.setMaterialId(listTemp.get(i).getId());
                    List<LabSecurityMaterialrelation>  list =iLabSecurityMaterialrelationService.selectLabSecurityMaterialrelationList(lmr);
//                    for(LabSecurityMaterialrelation materialrelation: list){
//                        String splitUrl[]=materialrelation.getDataUrl().split(",");
//                        String finalUrl="";
//                        for(String sp:splitUrl){
//                            String dataUrl[]=sp.split(";");
//                            String newUrl=fileConfigUtils.getRemoteUrl().replace("http","https")+"/"+dataUrl[1];
//                            newUrl= UrlFormatUtils.getHttpsORHttpUrl(newUrl);
//                            String newDataUrl=dataUrl[0]+";"+newUrl;
//                            finalUrl+=newDataUrl+",";
//                        }
//                        finalUrl=finalUrl.substring(0,finalUrl.length()-1);
//                        materialrelation.setDataUrl(finalUrl);
//                    }
                    listTemp.get(i).setListMr(list);
                }
            }
        }else if("11".equals(labSecurityApply.getUserType())){
            //教职工 模板查询
            listTemp= labSecurityMaterialDataService.selectLabSecurityMaterialDataTeacher(labSecurityApply.getSubjectId());
            for (int i=0;i<listTemp.size();i++){
                //如果是关联模板 查询出具体关联的内容
                if(1==listTemp.get(i).getMaterialType()){
                    //上传材料查询
                    LabSecurityMaterialrelation lmr = new LabSecurityMaterialrelation();
                    lmr.setApplyId(labSecurityApply.getId());
                    lmr.setMaterialId(listTemp.get(i).getId());
                    List<LabSecurityMaterialrelation>  list =iLabSecurityMaterialrelationService.selectLabSecurityMaterialrelationList(lmr);
//                    for(LabSecurityMaterialrelation materialrelation: list){
//                        String splitUrl[]=materialrelation.getDataUrl().split(",");
//                        String finalUrl="";
//                        for(String sp:splitUrl){
//                            String dataUrl[]=sp.split(";");
//                            String newUrl=fileConfigUtils.getRemoteUrl().replace("http","https")+"/"+dataUrl[1];
//                            newUrl= UrlFormatUtils.getHttpsORHttpUrl(newUrl);
//                            String newDataUrl=dataUrl[0]+";"+newUrl;
//                            finalUrl+=newDataUrl+",";
//                        }
//                        finalUrl=finalUrl.substring(0,finalUrl.length()-1);
//                        materialrelation.setDataUrl(finalUrl);
//                    }
                    listTemp.get(i).setListMr(list);
                }
            }
        }

        map.put("listTemp",listTemp);
        map.put("sysUser",sysUser);
        map.put("listcert",listcert);
        map.put("labSecurityApply",labSecurityApply);
        map.put("fzrsysUser",fzrsysUser);
        return map;
    }
    /**
     * 新增安全准入申请
     */
    @ApiOperation(value = "新增安全准入申请")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.ADD)
    @Log(title = "安全准入申请", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData add(@RequestBody LabSecurityApply labSecurityApply)
    {
        return ResultData.result(labSecurityApplyService.insertLabSecurityApply(labSecurityApply));
    }

    /**
     * 修改安全准入修改-PC
     */
    @ApiOperation(value = "修改安全准入申请")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.EDIT)
    @Log(title = "安全准入申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData edit(@RequestBody LabSecurityApply labSecurityApply)
    {
        return  ResultData.result(labSecurityApplyService.updateLabSecurityApply(labSecurityApply));
    }

    /**
     * 修改安全准入修改-小程序
     */
    @ApiOperation(value = "修改安全准入修改")
    @Log(title = "安全准入申请", businessType = BusinessType.UPDATE)
    @PostMapping("/editApp")
    public ResultData editApp(@RequestBody LabSecurityApply labSecurityApply)
    {
        return  ResultData.result(labSecurityApplyService.updateLabSecurityApply(labSecurityApply));
    }

    /**
     * 删除安全准入申请 laboratory:apply:remove
     */
    @ApiOperation(value = "删除安全准入申请")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.REMOVE)
    @Log(title = "安全准入申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData remove(@PathVariable Long[] ids)
    {
        return ResultData.result(labSecurityApplyService.deleteLabSecurityApplyByIds(ids));
    }

    /****
     * 安全准入上传申请
     * subjectId 实验室ID
     * remark 申请过滤验证
     * @return
     */
    @GetMapping("/materialApply")
    public AjaxResult materialApply(Long subjectId,String remark,String beginTime, String endTime ) {
        Map<String, Object> map =new HashMap<String, Object>();
        //获取当前登录用户信息
        SysUser tokensysUser = tokenService.getLoginUser().getSysUser();

        if(!"22".equals(tokensysUser.getUserType())){
            throw new ServiceException("非学生，不允许申请准入。");
        }

        //根据id查询用户信息
        R<SysUser> rDate =remoteUserService.getUserInfoByUserId(tokensysUser.getUserId(), SecurityConstants.INNER);
        SysUser  sysUser = rDate.getData();

        //PC端根据条件校验，小程序端不做校验（操作流程不同）
        if(StringUtils.isNotBlank(remark)) {
            LabSecurityApplyVO labapplyVo = new LabSecurityApplyVO();
            labapplyVo.setBeginTime(beginTime);
            labapplyVo.setEndTime(endTime);
            labapplyVo.setSubjectId(subjectId);
            labapplyVo.setUserId(sysUser.getUserId());
            List<LabSecurityApplyVO> listapplyuser = labSecurityApplyService.selectLabSecurityApplyListByTime(labapplyVo);
            if (listapplyuser.size() > 0) {
                throw new ServiceException("该时间段已存在准入申请，请修改申请时间后在提交申请。");
            }
        }

        //申请时校验是否存在
        /*if(StringUtils.isNotBlank(remark)){
            //校验用户是否已有申请中的数据
            LabSecurityApplyVO labSecurityApplyVo = new LabSecurityApplyVO();
            labSecurityApplyVo.setSubjectId(subjectId);
            labSecurityApplyVo.setUserId(sysUser.getUserId());
            labSecurityApplyVo.setRemark(remark);
            List<LabSecurityApplyVO> listapp= labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVo);
            if(listapp!=null && listapp.size()>0){
                throw new ServiceException("已申请该实验室，无需重复申请！");
            }
        }*/

        List<LabSecurityMaterialDataVO> listTeacher=Collections.emptyList();//教职工
        List<LabSecurityMaterialDataVO> listStudent=Collections.emptyList();//学生
        List<Map<String, Object>> listcert = Collections.emptyList();//学生考试证数
        List<Map<String, Object>> fzrsysUser = null;//实验室负责人
        //学生登录
        if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            //获取学生考试证数
            listcert = labSecurityApplyService.selectUserCertList(sysUser.getUserId());
            //模板查询
            listStudent =labSecurityMaterialDataService.selectLabSecurityMaterialDataStudent(subjectId);
        }else if("11".equals(sysUser.getUserType())){
            //教职工 模板查询
            listTeacher= labSecurityMaterialDataService.selectLabSecurityMaterialDataTeacher(subjectId);
        }
        //根据实验室ID查询实验室信息
        LabSubject labSubject =iLabSubjectService.selectLabSubjectById(subjectId);
        if(labSubject!=null){
            //根据实验室负责人查询出负责人信息
            fzrsysUser=labSecurityApplyService.selectLabsubjectUserInfo(labSubject.getAdminId());
        }

        map.put("listcert",listcert);//学生考试证数
        map.put("listTeacher",listTeacher);//教职工模板
        map.put("listStudent",listStudent);//学生模板
        map.put("sysUser",sysUser);//登录用户信息
        map.put("fzrsysUser",fzrsysUser);//实验室负责人信息
        return AjaxResult.success(map);
    }

    /***
     * 安全准入申请添加
     * @param labSecurityApplyVO 申请表
     * @return
     */
    @PostMapping("/materialAdd")
//    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.ADD)
    public ResultData materialAdd(@RequestBody LabSecurityApplyVO labSecurityApplyVO)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(labSecurityApplyVO.getValidBeginTime());
        String endTime = sdf.format(labSecurityApplyVO.getValidEndTime());
        //校验申请时间是否有重叠
        LabSecurityApplyVO labapplyVo=new LabSecurityApplyVO();
        labapplyVo.setBeginTime(beginTime);
        labapplyVo.setEndTime(endTime);
        labapplyVo.setSubjectId(labSecurityApplyVO.getSubjectId());
        labapplyVo.setUserId(Long.valueOf(labSecurityApplyVO.getSysUser().getUserId()));
        List<LabSecurityApplyVO> listapplyuser = labSecurityApplyService.selectLabSecurityApplyListByTime(labapplyVo);
        if(listapplyuser.size()>0){
            throw new ServiceException("该时间段已存在准入申请，请修改申请时间后在提交申请！");
        }
        return  ResultData.result(labSecurityApplyService.materialAdd(labSecurityApplyVO));
    }

    /***
     * 安全准入申请修改
     * @param labSecurityApplyVO
     * @return
     */
    @PostMapping("/materialUpdate")
    //@PreAuthorize(hasPermi = PerPrefix.LABORATORY_APPLY + PerFun.ADD)
    public ResultData materialUpdate(@RequestBody LabSecurityApplyVO labSecurityApplyVO)
    {
        if(labSecurityApplyVO.getValidBeginTime()!=null && labSecurityApplyVO.getValidEndTime()!=null) {
            //校验申请时间是否有重叠
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String beginTime = sdf.format(labSecurityApplyVO.getValidBeginTime());
            String endTime = sdf.format(labSecurityApplyVO.getValidEndTime());

            LabSecurityApplyVO labapplyVo = new LabSecurityApplyVO();
            labapplyVo.setBeginTime(beginTime);
            labapplyVo.setEndTime(endTime);
            labapplyVo.setSubjectId(labSecurityApplyVO.getSubjectId());
            labapplyVo.setUserId(labSecurityApplyVO.getSysUser().getUserId());
            List<LabSecurityApplyVO> listapplyuser = labSecurityApplyService.selectLabSecurityApplyListByTime(labapplyVo);
            if (listapplyuser.size() > 0) {
                throw new ServiceException("该时间段已存在准入申请，请修改申请时间后在提交申请！");
            }
        }

        return  ResultData.result(labSecurityApplyService.materialUpdate(labSecurityApplyVO));
    }

    /**
     * 获取当前登录用户的可用模板
     */
    @GetMapping(value = "/getUserTemplate")
    public AjaxResult getUserTemplate(Long subjectId)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        //获取登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        List<LabSecurityMaterialDataVO> listTeacher=Collections.emptyList();//教职工
        List<LabSecurityMaterialDataVO> listStudent=Collections.emptyList();//学生

        if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            //学生登录
            listStudent =labSecurityMaterialDataService.selectLabSecurityMaterialDataStudent(subjectId);
        }else if("11".equals(sysUser.getUserType())){
            //教职工登录
            listTeacher= labSecurityMaterialDataService.selectLabSecurityMaterialDataTeacher(subjectId);
        }

        map.put("listTeacher",listTeacher);
        map.put("listStudent",listStudent);
        return AjaxResult.success(map);
    }


    /**
     * 修改安全准入申请 审批
     */
    @GetMapping(value = "/approval")
    public TableDataInfo<LabSecurityApply> approval(LabSecurityApplyVO labSecurityApplyVO)
    {
        ///获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        labSecurityApplyVO.setAuditId(sysUser.getUserId());
        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyList(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     * 小程序准入审核 按照时间分组查询
     */
    @GetMapping("/listOrderByYmd")
    @ApiOperation(value = "查询安全准入审核列表")
    public TableDataInfo<Map<String,Object>> selectLabCheckRecordListOrderBydate(LabSecurityApplyVO labSecurityApplyVO) {
        startPage();

        ///获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        if("00".equals(sysUser.getUserType())){
            //系统用户登录
            labSecurityApplyVO.setDeptId(sysUser.getDeptId());
        }else if("11".equals(sysUser.getUserType())){
            //教职工登录
            labSecurityApplyVO.setSubjectAdminid(sysUser.getUserId());
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            //学生登录
            labSecurityApplyVO.setUserId(sysUser.getUserId());
        }

        //查询日期
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectLabSecurityApplyListOrderBydate(labSecurityApplyVO);


        for (int i=0;i<list.size();i++){
            labSecurityApplyVO.setCreatTime(list.get(i).getCreatTime());
            List<LabSecurityApplyVO> list2=labSecurityApplyService.selectLabSecurityApplyListYmd(labSecurityApplyVO);
            list.get(i).setApplyList(list2);
        }
        return getDataTable(list);
    }


    /**
     * 首页校级 安全统计柱形图
     */
    @GetMapping(value = "/listSchoolApplyColumn")
    public AjaxResult listSchoolApplyColumn()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        LabSecurityApply labSecurityApply = new LabSecurityApply();
        //通过
        //labSecurityApply.setAuditStatus(2);
        List<Map<String, Object>> listTg = labSecurityApplyService.selectApplyListSchoolColumn(labSecurityApply);
        map.put("listTg",listTg);
        return AjaxResult.success(map);
    }

    /**
     * 首页院级 安全统计柱形图
     */
    @GetMapping(value = "/listCollegeApplyColumn")
    public AjaxResult listCollegeApplyColumn()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        LabSecurityApply labSecurityApply = new LabSecurityApply();
        //通过
        //labSecurityApply.setAuditStatus(2);
        List<Map<String, Object>> listTg = labSecurityApplyService.selectApplyListCollegelColumn(labSecurityApply);

        //计算申请总数
        Integer count=0;
        if(listTg.size()>0){
            for (int i=0;i<listTg.size();i++){
                count +=Integer.valueOf(listTg.get(i).get("applyNum").toString());
            }
        }
        map.put("listcount",count);
        map.put("listTg",listTg);
        return AjaxResult.success(map);
    }

    /**
     * 校级安全准入办理 统计列表
     */
    @GetMapping(value = "/listSchool")
    public TableDataInfo<LabSecurityApplyVO> listSchool(LabSecurityApplyVO labSecurityApplyVO)
    {   // beginTime endTime deptId
        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectApplyListSchool(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     * 校级安全准入办理跳转 统计柱形图
     */
    @GetMapping(value = "/listSchoolColumn")
    public AjaxResult listSchoolColumn()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        LabSecurityApply labSecurityApply = new LabSecurityApply();
        //申请
        List<Map<String, Object>> listSq = labSecurityApplyService.selectApplyListSchoolColumn(labSecurityApply);

        //通过
        labSecurityApply.setAuditStatus(2);
        List<Map<String, Object>> listTg = labSecurityApplyService.selectApplyListSchoolColumn(labSecurityApply);
        map.put("listTg",listTg);
        map.put("listSq",listSq);
        return AjaxResult.success(map);
    }

    /**
     * 院系详情统计列表
     */
    @GetMapping(value = "/listCollege")
    public TableDataInfo<LabSecurityApplyVO> listCollege(LabSecurityApplyVO labSecurityApplyVO)
    {
        // beginTime endTime subjectId
        startPage();
        List<LabSecurityApplyVO> list = labSecurityApplyService.selectApplyListCollege(labSecurityApplyVO);
        return getDataTable(list);
    }

    /**
     * 院级 安全准入办理跳转 统计柱形图
     */
    @GetMapping(value = "/listCollegeColumn")
    public AjaxResult listCollegeColumn()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        LabSecurityApply labSecurityApply = new LabSecurityApply();
        //申请
        List<Map<String, Object>> listSq = labSecurityApplyService.selectApplyListCollegelColumn(labSecurityApply);

        //通过
        labSecurityApply.setAuditStatus(2);
        List<Map<String, Object>> listTg = labSecurityApplyService.selectApplyListCollegelColumn(labSecurityApply);
        map.put("listTg",listTg);
        map.put("listSq",listSq);
        return AjaxResult.success(map);
    }


    @RequestMapping("/downloadwBatch")
    public void downloadwBatch(HttpServletRequest request, HttpServletResponse response,LabSecurityApplyVO securityApplyVO){
        Map<String, byte[]> files = new HashMap<String, byte[]>();
        String[] urls = securityApplyVO.getFileList().split("@@");
        String baseUrl=request.getServerName();
        for(int i=0;i<urls.length;i++){
            String[] dataUrl = urls[i].split(";");
            String newUrl = dataUrl[1].substring(0,dataUrl[1].length()-1);
            String fileUrl="";
            if(baseUrl.contains("192.168")){
                fileUrl=fileConfigUtils.getLocalUrl()+newUrl;
            }else{
                fileUrl=fileConfigUtils.getRemoteUrl()+newUrl;
            }
            fileUrl= UrlFormatUtils.getHttpsORHttpUrl(fileUrl);
            try {
                byte[] f = getFile(fileUrl);
                files.put(dataUrl[0], f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        Optional.ofNullable(securityApplyVO.getMrList()).orElseGet(Collections::emptyList)
//                .stream().forEach(a->{
//                    if(a.getDataUrl()!=null){
//                        String[] dataUrl = a.getDataUrl().split(";");
//                        String newUrl = dataUrl[1].substring(0,dataUrl[1].length()-1);
//                        try {
//                            byte[] f = getFile(newUrl);
//                            files.put(dataUrl[0], f);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//
//                    }
//        });

        //设置下载的压缩包名
        String zipName = securityApplyVO.getUserName() + "_"+ securityApplyVO.getUserNumber()+"_"+ securityApplyVO.getSubjectName() + ".zip";

        //根据文件，进行压缩，批量下载
        if(files.size() > 0){
            labSecurityApplyService.downloadBatchByFile(response, files, zipName);
        }

    }


    private byte[] getFile(String url) throws IOException{
        URL urlConet = new URL(url);
        HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(4 * 1000);
        InputStream inStream = con .getInputStream();    //通过输入流获取图片数据
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        byte[] data =  outStream.toByteArray();
        return data;
    }
}
