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.SecurityConstants;
import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.*;
import com.zd.laboratory.domain.vo.LabCheckRecordDetailsVO;
import com.zd.laboratory.domain.vo.LabCheckRecordVO;
import com.zd.laboratory.domain.vo.LabSecurityApplyVO;
import com.zd.laboratory.service.*;
import com.zd.system.api.RemoteUserService;
import com.zd.system.api.domain.SysUser;
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.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.zd.common.core.web.page.TableDataInfo;

/**
 * 安全检查Controller
 *
 * @author zd
 * @date 2021-12-30
 */
@RestController
@Api(tags = "【安全检查】")
@RequestMapping("/checkRecord")
public class LabCheckRecordController extends BaseController {
    @Autowired
    private ILabCheckRecordService labCheckRecordService;
    @Autowired
    private ILabCheckRecordDetailsService labCheckRecordDetailsService;
    @Autowired
    private ILabCheckMachineMsgService checkMachineMsgService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ILabSubjectService labSubjectService;
    @Autowired
    private ILabCheckRecordReleaseService iLabCheckRecordReleaseService;
    @Autowired
    private ILabCheckRecordDetailslogService iLabCheckRecordDetailslogService;
    @Autowired
    private ILabSecurityApplyService labSecurityApplyService;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询安全检查列表 问题整改小程序
     */
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:list")
    @GetMapping("/list")
    @ApiOperation(value = "查询安全检查列表")
    public TableDataInfo<LabCheckRecord> list(LabCheckRecordVO labCheckRecord) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecord.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            if(sysUser.getIsCheck() == 1){
                // 检查者只能查到自己创建的数据
                labCheckRecord.setFzrId(null);
                labCheckRecord.setCreateUserId(sysUser.getUserId());
            }else{
                labCheckRecord.setFzrId(sysUser.getUserId());//负责人
            }
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){ //学生
            //查询学生有效期内的申请集合
            LabSecurityApplyVO applyvo = new LabSecurityApplyVO();
            applyvo.setUserId(sysUser.getUserId());
            List<LabSecurityApplyVO> applist = labSecurityApplyService.selectApplyListEffective(applyvo);
            //获取实验室集合
            if(applist.size()>0){
                List<Long> ids = new ArrayList<>();
                for (int i=0;i<applist.size();i++){
                    ids.add(applist.get(i).getSubjectId());
                }
                labCheckRecord.setSubjectIds(ids);
            }else{
                //没有准入的实验室 返回空
                return getDataTable(new ArrayList<>());
            }
        }
        startPage();
        labCheckRecord.setIsFabu(1);//已发布的数据
        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
        return getDataTable(list);
    }

    /**
     * 查询安全检查列表 检查记录PC端
     */
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:list")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.LIST)
    @GetMapping("/listJcjl")
    @ApiOperation(value = "查询安全检查记录列表")
    public TableDataInfo<LabCheckRecord> listJcjl(LabCheckRecordVO labCheckRecord) {
        /*SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecord.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            labCheckRecord.setCreateUserId(sysUser.getUserId());//创建人
        }*/

        //labCheckRecord.setIsFabu(1);//已发布的数据
        //labCheckRecord.setIsCg(0);//已提交 非草稿数据
        startPage();
        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
        return getDataTable(list);
    }

    /***
     * 检测用户是否上传电子签章
     * @return
     */
    @GetMapping("/checkSign")
    public AjaxResult checkSign() {
        boolean flg=false;
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        //根据id查询用户信息
        R<SysUser> rDate = remoteUserService.getUserInfoByUserId(sysUser.getUserId(), SecurityConstants.INNER);
        SysUser user = rDate.getData();
        if( StringUtils.isNotBlank(user.getSignature())){
            flg=true;
        }
        return AjaxResult.success(flg);
    }


    /**
     * 查询安全检查列表 问题整改PC端
     */
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:list")
//    @GetMapping("/listWtzg")
//    @ApiOperation(value = "查询安全检查列表")
//    public TableDataInfo<LabCheckRecord> listWtzg(LabCheckRecordVO labCheckRecord) {
//        SysUser sysUser = tokenService.getLoginUser().getSysUser();
//
//        if("00".equals(sysUser.getUserType())){ //系统用户
//            if(sysUser.getDeptId()!=null ){
//                labCheckRecord.setBuildingId(String.valueOf(sysUser.getDeptId()));
//            }
//        }else if("11".equals(sysUser.getUserType())){ //教职工
//            labCheckRecord.setFzrId(sysUser.getUserId());
//        }
//        startPage();
//        labCheckRecord.setIsFabu(1);//已发布的数据
//        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
//        return getDataTable(list);
//    }

    /**
     * 查询安全检查待整改列表
     */
   /* @GetMapping("/listDzg")
    @ApiOperation(value = "查询安全检查列表")
    public TableDataInfo<LabCheckRecordVO> listDzg(LabCheckRecordVO labCheckRecord) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecord.setBuildingId(String.valueOf(sysUser.getDeptId()));
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            labCheckRecord.setCreateUserId(sysUser.getUserId());//创建人
        }

        startPage();
        labCheckRecord.setIsFabu(1);//已发布的数据
        List<LabCheckRecordVO> list = labCheckRecordService.selectLabCheckRecordZgshList(labCheckRecord);
        return getDataTable(list);
    }*/

    /**
     * 小程序安全检查 按照时间分组查询
     */
    @GetMapping("/listOrderByYyyymmdd")
    @ApiOperation(value = "查询安全检查列表")
    public TableDataInfo<Map<String,Object>> selectLabCheckRecordListOrderBydate(LabCheckRecordVO labCheckRecord) {
        startPage();
        List<LabCheckRecordVO> list = labCheckRecordService.selectLabCheckRecordListOrderBydate(labCheckRecord);
        for (int i=0;i<list.size();i++){
            labCheckRecord.setCreateTime(list.get(i).getCreateTime());
            List<LabCheckRecord> list2=labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
            list.get(i).setRecordList(list2);
        }
        return getDataTable(list);
    }

    /**
     * 查询安全检查列表总数
     */
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:list")
    @GetMapping("/listCount")
    @ApiOperation(value = "查询安全检查列表")
    public AjaxResult listCount(LabCheckRecordVO labCheckRecord) {
        /*SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecord.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            labCheckRecord.setCreateUserId(sysUser.getUserId());//创建人
        }*/
        //labCheckRecord.setIsFabu(1);//已发布的数据
        labCheckRecord.setIsCg(1);//草稿
        List<LabCheckRecord> listCount = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
        return AjaxResult.success(listCount.size());
    }

    /**
     * 导出安全检查列表
     */
    @ApiOperation(value = "导出安全检查列表")
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:export")
    @Log(title = "安全检查", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabCheckRecordVO labCheckRecord) throws IOException {
        labCheckRecord.setIsFabu(1);//已发布的数据
        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);
        ExcelUtil<LabCheckRecord> util = new ExcelUtil<LabCheckRecord>(LabCheckRecord.class);
        util.exportExcel(response, list, "安全检查数据");
    }

    /**
     * 获取安全检查详细信息
     */
    @ApiOperation(value = "获取安全检查详细信息")
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:query")
    @GetMapping(value = "/{id}")
    public ResultData<LabCheckRecord> getInfo(@PathVariable("id") Long id) {
        return ResultData.success(labCheckRecordService.selectLabCheckRecordById(id));
    }

    /**
     * 新增安全检查
     */
    @ApiOperation(value = "新增安全检查")
//    @PreAuthorize(hasPermi = "laboratory:checkRecord:add")
    @Log(title = "安全检查", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData add(@RequestBody LabCheckRecordVO labCheckRecordVo) {
        return ResultData.result(labCheckRecordService.insertLabCheckRecord(labCheckRecordVo));
    }

    /**
     * 新增安全检查草稿保存-PC
     */
    //@PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.ADD)
    @ApiOperation(value = "新增安全检查（草稿）")
    @Log(title = "安全检查", businessType = BusinessType.INSERT)
    @PostMapping("/addCg")
    public ResultData addCg(@RequestBody LabCheckRecordVO labCheckRecordVo) {
        return ResultData.result(labCheckRecordService.insertLabCheckRecordCg(labCheckRecordVo));
    }

    /**
     * 新增安全检查提交保存-PC
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.ADD)
    @ApiOperation(value = "新增安全检查（提交）")
    @Log(title = "安全检查", businessType = BusinessType.INSERT)
    @PostMapping("/addTj")
    public ResultData addTj(@RequestBody LabCheckRecordVO labCheckRecordVo) {
        //检查项录入
       int id = labCheckRecordService.insertLabCheckRecordTj(labCheckRecordVo);
       //if(id>0){
           // 整改通知 传参时需要将  0一般整改改为1，否则为2 重大整改
           //int type = labCheckRecordVo.getZgType()==0?1:2;
           //checkMachineMsgService.insertLabCheckMachineMsg(type, labCheckRecordVo.getId());
           // 整改通知发送给 实验室负责人
           //checkMachineMsgService.insertLabCheckMachineTjz(labCheckRecordVo.getZgType()==0?1:2, labCheckRecordVo.getId(),1);
       //}
        return ResultData.result(id);
    }


    /**
     * 新增安全检查提交保存草稿 - 小程序
     */
    @ApiOperation(value = "新增安全检查草稿-小程序")
    @Log(title = "安全检查", businessType = BusinessType.INSERT)
    @PostMapping("/addCgApp")
    public ResultData addCgApp(@RequestBody LabCheckRecordVO labCheckRecordVo) {
        //检查项录入
        int id = labCheckRecordService.insertLabCheckRecordCg(labCheckRecordVo);
        return ResultData.result(id);
    }


    /**
     * 新增安全检查提交保存 - 小程序
     */
    @ApiOperation(value = "新增安全检查-小程序")
    @Log(title = "安全检查", businessType = BusinessType.INSERT)
    @PostMapping("/addTjApp")
    public ResultData addTjApp(@RequestBody LabCheckRecordVO labCheckRecordVo) {
        //检查项录入
        int id = labCheckRecordService.insertLabCheckRecordTj(labCheckRecordVo);
        return ResultData.result(id);
    }

    /**
     * 修改安全检查
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.EDIT)
    @Log(title = "安全检查", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData edit(@RequestBody LabCheckRecordVO labCheckRecord) {
        return ResultData.result(labCheckRecordService.updateLabCheckRecord(labCheckRecord));
    }

    /**
     * 修改安全检查
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.EDIT)
    @ApiOperation(value = "修改安全检查")
    @Log(title = "安全检查", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public ResultData edupdateit(@RequestBody LabCheckRecordVO labCheckRecord) {
        int id = updateCheck(labCheckRecord);
        return ResultData.result(id);
    }

    /***
     * 修改安全检查-小程序
     * @param labCheckRecord
     * @return
     */
    @ApiOperation(value = "修改安全检查-小程序")
    @Log(title = "修改安全检查", businessType = BusinessType.UPDATE)
    @PostMapping("/updateApp")
    public ResultData updateApp(@RequestBody LabCheckRecordVO labCheckRecord) {
        int id = updateCheck(labCheckRecord);
        return ResultData.result(id);
    }

    /***
     * 安全检查修改
     * @param labCheckRecord
     * @return
     */
    public int updateCheck(LabCheckRecordVO labCheckRecord){
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if(sysUser==null){
            throw new ServiceException("没有查询到用户相关信息");
        }else if(sysUser.getIsCheck()==0){
            throw new ServiceException("该用户非检查人员，无权限保存");
        }

        int id = labCheckRecordService.updateLabCheckRecord(labCheckRecord);
        //修改成功 并且整改类型为1 提交时发送通知消息
        LabCheckRecord clr=labCheckRecordService.selectLabCheckRecordById(labCheckRecord.getId());
        if(id>0 &&  clr.getZgStatus()==1){
            // 整改通知，提交时发送给检查者 传参时需要将 0一般整改改为1，否则为2 重大整改
            checkMachineMsgService.insertLabCheckMachineJcz(clr.getZgType()==0?1:2, labCheckRecord.getId());
        }else if(id>0 &&  clr.getZgStatus()==2){
            // 整改通知发送给 实验室负责人
            checkMachineMsgService.insertLabCheckMachineTjz(clr.getZgType()==0?1:2, labCheckRecord.getId(),2);
        }else if(id>0 &&  clr.getZgStatus()==4){
            // 整改通知发送给 实验室负责人
            checkMachineMsgService.insertLabCheckMachineTjz(clr.getZgType()==0?1:2, labCheckRecord.getId(),4);
        }
        return id;
    }
    /**
     * 删除安全检查
     */
    @ApiOperation(value = "删除安全检查")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.REMOVE)
    @Log(title = "安全检查", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData remove(@PathVariable Long[] ids) {
        return ResultData.result(labCheckRecordService.deleteLabCheckRecordByIds(ids));
    }

    /****
     * 安全检查项 逾期消息发送
     * @return
     */
    @GetMapping("/checkSendMsgBeOverdue")
    public void checkSendMsgBeOverdue() {
        labCheckRecordService.checkSendMsgBeOverdue();
    }


    /**
     * 查询安全检查列表-小程序按时间分组
     */
    @GetMapping("/listGroupBy")
    @ApiOperation(value = "小程序未安全检查列表")
    public AjaxResult  listGroupBy(LabCheckRecordVO labCheckRecord) {
        labCheckRecord.setIsFabu(1);//已发布的数据
        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecord);

        Map<String,Object> maplist = new HashMap<String,Object>();
        //按照日期对数据分组
        if(list!=null){
            Map<String, List<LabCheckRecord>> map = new HashMap<String, List<LabCheckRecord>>();
            for (LabCheckRecord record : list) {
                String date = DateUtils.dateTime(record.getCreateTime());
                List<LabCheckRecord> tmpList = map.get(date);
                if (tmpList == null) {
                    tmpList = new ArrayList<>();
                    tmpList.add(record);
                    map.put(date, tmpList);

                    //maplist.put("list",tmpList);
                    //maplist.put("date",date);

                }else {
                    tmpList.add(record);
                }
            }
            return AjaxResult.success(map);
        }
        return AjaxResult.error("没有相关信息");
    }


    /***
     * 根据房间号查询实验室信息
     * @param room
     * @param name
     * @param userName
     * @return
     */
    @GetMapping("/selectInfoByRoom")
    @ApiOperation(value = "小程序未安全检查列表")
    public AjaxResult selectInfoByRoom(String room,String name,String userName) {
        Map<String,Object> map = new HashMap<String, Object>();

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

        //既是检查者 又是管理员
         if(1==sysUser.getIsCheck() && labSubjectService.isadmin(labSubject)){
             map.put("remark",sysUser.getUserId());
         }

        //按学校（数据逻辑过滤）
        R<List<Long>> listdeptids = remoteUserService.getLogingUserDeptids();
        List<Long> deptIds= listdeptids.getData();
        map.put("deptIds", deptIds);

         // TODO 白老师证号特殊处理
        if(sysUser.getUserId() == 92612){
            map.put("deptId", sysUser.getDept().getDeptId());
            map.put("remark", null);
        }

        map.put("room",room);
        map.put("name",name);
        map.put("userName",userName);
        return AjaxResult.success(labCheckRecordService.selectInfoByRoom(map));
    }

    /***
     * 根据检查项ID获取 隐患整改集合 PC
     * @param id
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.QUERY)
    @GetMapping("/recordDettailsList")
    public AjaxResult recordDettailsList( Long id) {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getRecordDettailsList(id);
        return AjaxResult.success(map);
    }

    /***
     * 根据检查项ID获取 隐患整改集合- 小程序
     * @param id
     * @return
     */
    @GetMapping("/recordDettailsListApp")
    public AjaxResult recordDettailsListApp( Long id) {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getRecordDettailsList(id);
        return AjaxResult.success(map);
    }

    public Map<String, Object> getRecordDettailsList(Long id){
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        Map<String, Object> map =new HashMap<String, Object>();
        //检查记录
        LabCheckRecord labCheckRecord = labCheckRecordService.selectLabCheckRecordById(id);
        if(labCheckRecord==null){
            throw new ServiceException("未获取到相关信息");
        }
        //判断负责人是否第一次查看
        if(sysUser.getUserId().equals(labCheckRecord.getFzrId()) && labCheckRecord.getFirstTime()==null ){
            int flg= labCheckRecordService.updateFirstTimeById(labCheckRecord.getId());
            System.out.println(flg);
        }

        //隐患详情
        /*LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
        labCheckRecordDetails.setCheckId(id);
        List<LabCheckRecordDetails> list= labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails);
        */
        LabCheckRecordDetailsVO dzgDetailsVo = new LabCheckRecordDetailsVO();
        dzgDetailsVo.setCheckId(id);
        List<LabCheckRecordDetailsVO> list= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(dzgDetailsVo);

        if(list.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<list.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(list.get(i).getId());
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                list.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                /*if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        flg=0;//重新赋值
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    list.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }*/
            }
        }

        //处理掉最后一级子项
        /*if(list!=null && list.size()>0){
            for (int i=0;i<list.size();i++){
                String str=  list.get(i).getAllCheckOptionName();
                if(str!=null && str.contains("-")){
                    list.get(i).setAllCheckOptionName(str.substring(0,str.lastIndexOf("-")));
                }
            }
        }*/
        map.put("yhlist",list);
        map.put("record",labCheckRecord);
        return map;
    }

    /***
     * 待整改详情
     * @param id
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.LIST)
    @ApiOperation(value = "待整改详情")
    @GetMapping("/recordDetails")
    public AjaxResult recordDetails( Long id) {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        Map<String, Object> map =new HashMap<String, Object>();
        //检查记录
        LabCheckRecord labCheckRecord = labCheckRecordService.selectLabCheckRecordById(id);
        if(labCheckRecord==null){
            throw new ServiceException("未获取到相关信息");
        }
        //判断负责人是否第一次查看
        if(sysUser.getUserId().equals(labCheckRecord.getFzrId()) && labCheckRecord.getFirstTime()==null ){
            int flg= labCheckRecordService.updateFirstTimeById(labCheckRecord.getId());
            System.out.println(flg);
        }

        //隐患详情
        /*LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
        labCheckRecordDetails.setCheckId(id);
        List<LabCheckRecordDetails> list= labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails);
        //处理掉最后一级子项
        if(list!=null && list.size()>0){
            for (int i=0;i<list.size();i++){
                String str=  list.get(i).getAllCheckOptionName();
                if(str!=null && str.contains("-")){
                    list.get(i).setAllCheckOptionName(str.substring(0,str.lastIndexOf("-")));
                }
            }
        }*/

       //待整改
        LabCheckRecordDetailsVO dzgDetailsVo = new LabCheckRecordDetailsVO();
        dzgDetailsVo.setCheckId(id);
        dzgDetailsVo.setIsZg(1L);//待整改
        dzgDetailsVo.setIsZgStatus(0);//不包含无法整改的数据
        List<LabCheckRecordDetailsVO> dzglist= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(dzgDetailsVo);
       /* //对象复制
        LabCheckRecordVO checkRecordVO = new LabCheckRecordVO();
        BeanUtils.copyProperties(checkRecordVO,labCheckRecord);
        //添加整改项详情集合
        checkRecordVO.setDetailsListVo(dzglist);*/

        if(dzglist.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<dzglist.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(dzglist.get(i).getId());
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                dzglist.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                /*if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        flg=0;//重新赋值
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    dzglist.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }*/
            }
         }

        //已整改
        LabCheckRecordDetailsVO yzgDetailsVo = new LabCheckRecordDetailsVO();
        yzgDetailsVo.setCheckId(id);
        yzgDetailsVo.setIsZg(0L);//已整改
        yzgDetailsVo.setIsZgStatus(0);//非无法整改
        List<LabCheckRecordDetailsVO> yzglist= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(yzgDetailsVo);
        //对象复制
        /*LabCheckRecordVO checkRecordVO = new LabCheckRecordVO();
        BeanUtils.copyProperties(checkRecordVO,labCheckRecord);
        //添加整改项详情集合
        checkRecordVO.setDetailsListVo(yzglist);*/

        if(yzglist.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<yzglist.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(yzglist.get(i).getId());
                //detailslog.setSpStatus(4L);//整改完成
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                yzglist.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                /*if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        flg=0;//重新赋值
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    yzglist.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }*/
            }
        }

        //暂不整改
        LabCheckRecordDetailsVO wfzgDetailsVo = new LabCheckRecordDetailsVO();
        wfzgDetailsVo.setCheckId(id);
        wfzgDetailsVo.setIsZgStatus(1);//暂不整改
        List<LabCheckRecordDetailsVO> wfzglist= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(wfzgDetailsVo);

        if(wfzglist.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<wfzglist.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(wfzglist.get(i).getId());
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                wfzglist.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                /*if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        flg=0;//重新赋值
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    dzglist.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }*/
            }
        }

        map.put("dzglist",dzglist);
        map.put("yzglist",yzglist);
        map.put("wfzglist",wfzglist);
        map.put("record",labCheckRecord);
        return AjaxResult.success(map);
    }


    /***
     * 驳回 详情
     * @param id
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.LIST)
    @ApiOperation(value = "驳回详情")
    @GetMapping("/recordDettailsBh")
    public AjaxResult recordDettailsBh( Long id) {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        Map<String, Object> map =new HashMap<String, Object>();

        //检查记录
        LabCheckRecord labCheckRecord = labCheckRecordService.selectLabCheckRecordById(id);
        if(labCheckRecord==null){
            throw new ServiceException("未获取到相关信息");
        }
        //判断负责人是否第一次查看
        /*if(sysUser.getUserId().equals(labCheckRecord.getFzrId()) && labCheckRecord.getFirstTime()==null ){
            int flg= labCheckRecordService.updateFirstTimeById(labCheckRecord.getId());
            System.out.println(flg);
        }*/

        //待整改
        LabCheckRecordDetailsVO dzgDetailsVo = new LabCheckRecordDetailsVO();
        dzgDetailsVo.setCheckId(id);
        List<LabCheckRecordDetailsVO> dzglist= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(dzgDetailsVo);

        if(dzglist.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<dzglist.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(dzglist.get(i).getId());
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                dzglist.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        flg=0;//重新赋值
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    dzglist.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }
            }
        }
        map.put("bhlist",dzglist);
        map.put("record",labCheckRecord);
        return AjaxResult.success(map);
    }

    /***
     * 整改完成详情
     * @param id
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.LIST)
    @ApiOperation(value = "整改完成详情")
    @GetMapping("/recordDettailsWc")
    public AjaxResult recordDettailsWc( Long id) {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        Map<String, Object> map =new HashMap<String, Object>();

        //检查记录
        LabCheckRecord labCheckRecord = labCheckRecordService.selectLabCheckRecordById(id);
        if(labCheckRecord==null){
            throw new ServiceException("未获取到相关信息");
        }
        //判断负责人是否第一次查看
        /*if(sysUser.getUserId().equals(labCheckRecord.getFzrId()) && labCheckRecord.getFirstTime()==null ){
            int flg= labCheckRecordService.updateFirstTimeById(labCheckRecord.getId());
            System.out.println(flg);
        }*/

        //待整改
        LabCheckRecordDetailsVO dzgDetailsVo = new LabCheckRecordDetailsVO();
        dzgDetailsVo.setCheckId(id);
        List<LabCheckRecordDetailsVO> dzglist= labCheckRecordDetailsService.selectLabCheckRecordDetailsListVo(dzgDetailsVo);

        if(dzglist.size()>0){
            LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
            //循环查询操作日志信息
            for (int i=0;i<dzglist.size();i++){
                detailslog.setCheckId(id);
                detailslog.setCheckDetailsId(dzglist.get(i).getId());
                List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
                dzglist.get(i).setDetailslogList(deatlog);

                //判断该条检查项的驳回次数
                if(deatlog.size()>0){
                    int flg=0;
                    for (int k=0;k<deatlog.size();k++){
                        if("2".equals(deatlog.get(k).getSpStatus())){
                            flg++;
                        }
                    }
                    dzglist.get(i).setCheckZs(flg);//该条检查项的驳回次数
                }
            }
        }
        map.put("wclist",dzglist);
        map.put("record",labCheckRecord);
        return AjaxResult.success(map);
    }

    /***
     *查询各个状态 检查记录总数
     * @return
     */
    @GetMapping("/selectStatusList")
    public AjaxResult selectStatusList( ) {
        List<Map<String, Object>> map =labCheckRecordService.selectStatusList();
        return AjaxResult.success(map);
    }


    /***
     * 根据登录用户获取学院部门
     * @return
     */
    @GetMapping("/selectUserDept")
    public AjaxResult selectUserDept( ) {
        List<Map<String, Object>> map =labCheckRecordService.selectUserDept();
        return AjaxResult.success(map);
    }

    /***
     * 根据登录用户部门id获取 该部门下所有单位
     * @return
     */
    @GetMapping("/selectDeptListUserDeptId")
    public AjaxResult selectDeptListUserDeptId( ) {
        List<Map<String, Object>> map =labCheckRecordService.selectDeptListUserDeptId();
        return AjaxResult.success(map);
    }

    @GetMapping("/getLoginUserInfo")
    public AjaxResult getLoginUserInfo( ) {

        Map<String, Object> map =new HashMap<String, Object>();
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        //查看当前用户是否实验室管理员
        LabSubject labSubject = new LabSubject();
        labSubject.setAdminId(sysUser.getUserId());
        boolean flg= labSubjectService.isadmin(labSubject);
        sysUser.setWorkStatus( String.valueOf(flg));

        //查询该用户下是否有未提交的检查记录
        LabCheckRecordVO labCheckRecordvo = new LabCheckRecordVO();
        labCheckRecordvo.setFzrId(sysUser.getUserId());
        labCheckRecordvo.setZgStatus(1);
        labCheckRecordvo.setIsFabu(1);//已发布的数据
        List<LabCheckRecord> list = labCheckRecordService.selectLabCheckRecordList(labCheckRecordvo);
        //map.put("sysUser",sysUser);
        map.put("isadmin",flg); //是否实验室管理员
        map.put("ischeck",sysUser.getIsCheck());//是否检查者
        map.put("list",list!=null?list.size():0);//未提交的检查记录
        return AjaxResult.success(map);
    }
    /***
     * 根据检查项ID获取检查记录
     * @return
     */
    @GetMapping("/getCheckIdByoptionId")
    public AjaxResult getCheckIdByoptionId( Long jcxId) {
        Map<String, Object> map =new HashMap<String, Object>();
        Long checkid=0L;
        boolean flg=false;
        //根据检查项id模糊匹配
        List<LabCheckRecordDetails> list =labCheckRecordDetailsService.selectListByJcxId(String.valueOf(jcxId));
        if(list!=null && list.size()>0){
            // 因为存在4、14、34 这类数据 需要循环找出具体对应的id（此集合值不会太多）
            for (int i=0;i<list.size();i++) {
                if(flg){
                    break;
                }
                String[] ids =  list.get(i).getJcxId().split(",");
                for (int k=0;k<ids.length;k++){
                    if(flg){
                        break;
                    }
                    if(ids[k].equals(String.valueOf(jcxId))){
                        checkid=list.get(i).getCheckId();
                        flg=true;
                        break;
                    }
                }
            }
        }
        map.put("id",checkid);
       return AjaxResult.success(map);
    }

    /**
     * 检查 实验室是否已发布
     */
    @GetMapping("/checkFabu")
    public AjaxResult checkFabu(LabCheckRecordRelease labCheckRecordRelease) {
        // 参数 checkId 实验室id
        List<LabCheckRecordRelease> list= iLabCheckRecordReleaseService.selectLabCheckRecordReleaseListExist(labCheckRecordRelease);
        return AjaxResult.success(list.size());
    }

    /***
     * 校级 -大屏安全检查
     * @param
     * @return
     */
    @GetMapping("/indexSchoolListCheck")
    public TableDataInfo<LabCheckRecordDetailsVO> indexSchoolListCheck(LabCheckRecordDetailsVO labCheckRecordDetailsVO)
    {
        List<LabCheckRecordDetailsVO> list= new ArrayList<>();
        //获取最新一条的发布检查记录
        LabCheckRecordRelease labCheckRecordRelease =iLabCheckRecordReleaseService.selectLabCheckRecordReleaseFirst();
        if(labCheckRecordRelease!=null && labCheckRecordRelease.getCheckId()!=null){
            String[] strids=  labCheckRecordRelease.getCheckId().split(",");
            //Long[] ids = new Long[strids.length];
            List<Long> ids= new ArrayList<>();
            for (int i=0;i<strids.length;i++){
                ids.add(Long.valueOf(strids[i]));
            }
            labCheckRecordDetailsVO.setIds(ids);

            //历史遗留问题总数
            labCheckRecordDetailsVO.setId(labCheckRecordRelease.getId());//最新一条发布记录id
            LabCheckRecordDetailsVO historyCount= labCheckRecordDetailsService.selectLabCheckRecordHistoryQuestionCount(labCheckRecordDetailsVO);

            //查询隐患整改统计数量
            LabCheckRecordDetailsVO count= labCheckRecordDetailsService.selectLabCheckRecordCountIndex(labCheckRecordDetailsVO);
            count.setCheckWzg(historyCount.getCheckWzg());//首页历史遗留问题总数
            List<LabCheckRecordDetailsVO> listVo = new ArrayList<>();
            listVo.add(count);

            startPage();
            list = labCheckRecordDetailsService.selectLabCheckRecordListVoIndex(labCheckRecordDetailsVO);
            if(list.size()>0){
                //list.get(0).setListVo(listCount);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String remarkDate = sdf.format(labCheckRecordRelease.getCreateTime());
                list.get(0).setListVo(listVo);
                list.get(0).setRemark(remarkDate);//检查时间
                list.get(0).setLaboratoryId(labCheckRecordRelease.getCheckId());//本批次发布的实验室安全检查id集合
                list.get(0).setId(labCheckRecordRelease.getId());//发布批次id
          /*list.get(0).setCheckZs(count.getCheckZs());//隐患总数
          list.get(0).setCheckYzg(count.getCheckYzg());//已整改
          list.get(0).setCheckWzg(count.getCheckWzg());//未整改*/
            }
        }



        return getDataTable(list);
    }

    /***
     * 校级 -大屏安全检查
     * @param
     * @return
     */
    @GetMapping("/indexCollegeListCheck")
    public TableDataInfo<LabCheckRecordDetailsVO> indexCollegeListCheck(LabCheckRecordDetailsVO labCheckRecordDetailsVO)
    {
        List<LabCheckRecordDetailsVO> list= new ArrayList<>();
        //获取最新一条的发布检查记录
        LabCheckRecordRelease labCheckRecordRelease =iLabCheckRecordReleaseService.selectLabCheckRecordReleaseFirst();
        if(labCheckRecordRelease!=null && labCheckRecordRelease.getCheckId()!=null){
            String[] strids=  labCheckRecordRelease.getCheckId().split(",");
            //Long[] ids = new Long[strids.length];
            List<Long> ids= new ArrayList<>();
            for (int i=0;i<strids.length;i++){
                ids.add(Long.valueOf(strids[i]));
            }
            labCheckRecordDetailsVO.setIds(ids);


        //历史遗留问题总数
        labCheckRecordDetailsVO.setId(labCheckRecordRelease.getId());//最新一条发布记录id
        LabCheckRecordDetailsVO historyCount= labCheckRecordDetailsService.selectLabCheckRecordHistoryQuestionCount(labCheckRecordDetailsVO);

        //查询隐患整改统计数量
        LabCheckRecordDetailsVO count= labCheckRecordDetailsService.selectLabCheckRecordCountIndex(labCheckRecordDetailsVO);
        count.setCheckWzg(historyCount.getCheckWzg());//首页历史遗留问题总数
        List<LabCheckRecordDetailsVO> listVo = new ArrayList<>();
        listVo.add(count);

        startPage();
        list = labCheckRecordDetailsService.selectLabCheckRecordListVoIndex(labCheckRecordDetailsVO);
        //list.get(0).setListVo(listCount);
            if(list.size()>0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String remarkDate = sdf.format(labCheckRecordRelease.getCreateTime());
                list.get(0).setListVo(listVo);
                list.get(0).setRemark(remarkDate);//检查时间
                list.get(0).setLaboratoryId(labCheckRecordRelease.getCheckId());//本批次发布的实验室安全检查id集合
                list.get(0).setId(labCheckRecordRelease.getId());//发布批次id
            /*list.get(0).setCheckZs(count.getCheckZs());//隐患总数
            list.get(0).setCheckYzg(count.getCheckYzg());//已整改
            list.get(0).setCheckWzg(count.getCheckWzg());//未整改*/
            }

        }

        return getDataTable(list);
    }

    /***
     * 校级 -大屏安全检查下面-根据发布id获取发布实验室详细情况(校、院可以共用)
     * @param
     * @return
     */
    @GetMapping("/indexGetCheckDetals")
    public TableDataInfo<LabCheckRecordVO> indexGetCheckDetals(LabCheckRecordVO labCheckRecordVO)
    {
        //根据id查询检查发布详情信息
        LabCheckRecordRelease labCheckRecordRelease =iLabCheckRecordReleaseService.selectLabCheckRecordReleaseById(labCheckRecordVO.getId());
        if(labCheckRecordRelease.getCheckId()!=null){
            String[] strids=  labCheckRecordRelease.getCheckId().split(",");
            //Long[] ids = new Long[strids.length];
            List<Long> ids= new ArrayList<>();
            for (int i=0;i<strids.length;i++){
                ids.add(Long.valueOf(strids[i]));
            }
            labCheckRecordVO.setIds(ids);
        }

        startPage();
        List<LabCheckRecordVO> list = labCheckRecordService.selectLabCheckRecordIndexDetals(labCheckRecordVO);
        //List<LabCheckRecordDetailsVO> listCount = iLabCheckRecordDetailsService.selectLabCheckRecordCountIndex(new LabCheckRecordDetailsVO());
        return getDataTable(list);
    }

    /****
     * 撤销发布
     * @param labCheckRecord
     * @return
     */
    @PostMapping("/revoke")
    public ResultData revoke(@RequestBody LabCheckRecordVO labCheckRecord) {
        List<Long> idsvo = labCheckRecord.getIds();
        Long[] idscheck = new Long[idsvo.size()];
        for (int i=0;i<idsvo.size();i++){
            idscheck[i]= idsvo.get(i) ;
        }
        return ResultData.result(labCheckRecordService.updateLabCheckRecordBack(idscheck));
    }

    /**
     * 此检查项 在当前实验室累计出现的隐患次数
     * laboratoryId 实验室id
     * checkId 检查项id
     */
    @GetMapping("/hiddenDangerCount")
    public AjaxResult selectHiddenDangerCount(Integer laboratoryId,Integer checkId) {
        if(laboratoryId==null || checkId==null ){
            throw new ServiceException("参数不能为空！");
        }
        // 参数 检查项checkId  ,实验室id laboratoryId
        Map<String, Object> map =new HashMap<String, Object>();
        map.put("laboratoryId",String.valueOf(laboratoryId));
        map.put("checkId", String.valueOf(checkId));
        List<LabCheckRecordVO> list = labCheckRecordService.selectHiddenDangerCount(map);

        //判断该检查项是否有未整改记录
        boolean flg =false;
        if(list.size()>0){
            for (int i=0;i<list.size();i++){
                if(1==list.get(i).getIsZg()){
                    flg=true;
                    break;
                }
            }
        }

        Map<String, Object> backmap =new HashMap<String, Object>();
        backmap.put("yhcount",list.size());
        backmap.put("yhlist",list);
        backmap.put("yhflg",flg);
        return AjaxResult.success(backmap);
    }

}
