package com.zd.laboratory.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
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.exception.ServiceException;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.LabCheckRecord;
import com.zd.laboratory.domain.LabCheckRecordDetailslog;
import com.zd.laboratory.domain.LabCheckRecordRelease;
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.domain.SysUser;
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.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.laboratory.domain.LabCheckRecordDetails;
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.swagger.config.Knife4jConfiguration;

import com.zd.common.core.web.page.TableDataInfo;

/**
 * 安全检查隐患表Controller
 *
 * @author zd
 * @date 2021-12-30
 */
@RestController
@Api(tags = "【安全检查隐患表】")
@RequestMapping("/checkRecordDetails")
public class LabCheckRecordDetailsController extends BaseController {
    @Autowired
    private ILabCheckRecordDetailsService labCheckRecordDetailsService;
    @Autowired
    private ILabCheckRecordReleaseService labCheckRecordReleaseService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ILabSecurityApplyService labSecurityApplyService;
    @Autowired
    private ILabCheckRecordService labCheckRecordService;
    @Autowired
    private ILabCheckRecordDetailslogService iLabCheckRecordDetailslogService;

    /**
     * 查询安全检查隐患表列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "查询安全检查隐患表列表")
    public TableDataInfo<LabCheckRecordDetails> list(LabCheckRecordDetails labCheckRecordDetails) {
        startPage();
        List<LabCheckRecordDetails> list = labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails);
        return getDataTable(list);
    }

    /**
     * 查询安全检查隐患表列表 - 小程序接口,无分页
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.LIST)
    @GetMapping("/listXcx")
    @ApiOperation(value = "查询安全检查隐患表列表")
    public AjaxResult listXcx(LabCheckRecordDetails labCheckRecordDetails) {
        List<LabCheckRecordDetails> list = labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails);
        return AjaxResult.success(list);
    }

    /**
     * 导出安全检查隐患表列表
     */
    @ApiOperation(value = "导出安全检查隐患表列表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.EXPORT)
    @Log(title = "安全检查隐患表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabCheckRecordDetails labCheckRecordDetails) throws IOException {
        List<LabCheckRecordDetails> list = labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails);
        ExcelUtil<LabCheckRecordDetails> util = new ExcelUtil<LabCheckRecordDetails>(LabCheckRecordDetails.class);
        util.exportExcel(response, list, "安全检查隐患表数据");
    }

    /**
     * 获取安全检查隐患表详细信息
     */
    @ApiOperation(value = "获取安全检查隐患表详细信息")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public ResultData<LabCheckRecordDetails> getInfo(@PathVariable("id") Long id) {
        return ResultData.success(labCheckRecordDetailsService.selectLabCheckRecordDetailsById(id));
    }

    /**
     * 获取安全检查隐患表详细信息 和 安全检查信息
     */
    @ApiOperation(value = "获取安全检查隐患表详细信息 和 安全检查信息")
    //@PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.QUERY)
    @GetMapping(value = "/getInfoById")
    public AjaxResult getInfoById( Long id) {
        Map<String,Object> map = new HashMap<String,Object>();
        //隐患项详情
        LabCheckRecordDetails details = labCheckRecordDetailsService.selectLabCheckRecordDetailsById(id);

        //检查单详情
        LabCheckRecord check = labCheckRecordService.selectLabCheckRecordById(details.getCheckId());
        map.put("check",check);
        map.put("details",details);
        return AjaxResult.success(map);
    }

    /**
     * 新增安全检查隐患表
     */
    @ApiOperation(value = "新增安全检查隐患表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.ADD)
    @Log(title = "安全检查隐患表", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData add(@RequestBody LabCheckRecordDetails labCheckRecordDetails) {
        return ResultData.result(labCheckRecordDetailsService.insertLabCheckRecordDetails(labCheckRecordDetails));
    }

    /**
     * 修改安全检查隐患表
     */
    @ApiOperation(value = "修改安全检查隐患表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.EDIT)
    @Log(title = "安全检查隐患表", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData edit(@RequestBody LabCheckRecordDetails labCheckRecordDetails) {
        return ResultData.result(labCheckRecordDetailsService.updateLabCheckRecordDetails(labCheckRecordDetails));
    }

    /**
     * 删除安全检查隐患表
     */
    @ApiOperation(value = "删除安全检查隐患表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.REMOVE)
    @Log(title = "安全检查隐患表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData remove(@PathVariable Long[] ids) {
        return ResultData.result(labCheckRecordDetailsService.deleteLabCheckRecordDetailsByIds(ids));
    }

    /**
     * 审核、驳回操作方法 PC
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.APPROVE)
    @ApiOperation(value = "审核、驳回操作方法")
    @PostMapping("/editList")
    public ResultData editList(@RequestBody LabCheckRecordDetails details) {
        return ResultData.result(labCheckRecordDetailsService.updateLabCheckRecordDetailsList(details));
    }

    /***
     * 问题整改 （无法整改、整改完成）操作方法 -PC
     * @param details
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.RECTIFICATION)
    @ApiOperation(value = "审核操作方法")
    @PostMapping("/rectification")
    public ResultData rectification(@RequestBody LabCheckRecordDetails details) {
        return ResultData.result(labCheckRecordDetailsService.updateLabCheckRecordDetailsList(details));
    }

    /**
     * 审核、驳回操作方法 -小程序
     */
    @ApiOperation(value = "整改完成、无法整改作方法")
    @PostMapping("/editListApp")
    public ResultData editListApp(@RequestBody LabCheckRecordDetails details) {
        return ResultData.result(labCheckRecordDetailsService.updateLabCheckRecordDetailsList(details));
    }

    /***
     *整改审核列表
     * @param labCheckRecordDetailsVo
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORD + PerFun.LIST)
    @GetMapping("/listDzg")
    @ApiOperation(value = "整改审核列表")
    public TableDataInfo<LabCheckRecordDetailsVO> listDzg(LabCheckRecordDetailsVO labCheckRecordDetailsVo) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecordDetailsVo.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            labCheckRecordDetailsVo.setCreateUserId(sysUser.getUserId());
        }else{
            return getDataTable(new ArrayList<>());
        }

        startPage();
        List<LabCheckRecordDetailsVO> list = labCheckRecordDetailsService.selectLabCheckRecordDzg(labCheckRecordDetailsVo);
        return getDataTable(list);
    }

    /***
     * 问题整改列表-PC
     * @param labCheckRecordDetailsVO
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.LIST)
    @GetMapping("/listWtzg")
    @ApiOperation(value = "查询安全检查列表-PC")
    public TableDataInfo<LabCheckRecordDetailsVO> listWtzg(LabCheckRecordDetailsVO labCheckRecordDetailsVO) {
        List<LabCheckRecordDetailsVO> list=selectlistWtzg(labCheckRecordDetailsVO);
        return getDataTable(list);
    }

    /***
     * 问题整改列表-小程序
     * @param labCheckRecordDetailsVO
     * @return
     */
    @GetMapping("/listWtzgApp")
    @ApiOperation(value = "查询安全检查列表-小程序")
    public TableDataInfo<LabCheckRecordDetailsVO> listWtzgApp(LabCheckRecordDetailsVO labCheckRecordDetailsVO) {
        List<LabCheckRecordDetailsVO> list=selectlistWtzg(labCheckRecordDetailsVO);
        return getDataTable(list);
    }

    private  List<LabCheckRecordDetailsVO> selectlistWtzg(LabCheckRecordDetailsVO labCheckRecordDetailsVO){
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if("00".equals(sysUser.getUserType())){
            // 系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecordDetailsVO.setDeptId(sysUser.getDeptId());
            }
        }else  if("11".equals(sysUser.getUserType())){
            // 教职工
            labCheckRecordDetailsVO.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());
                }
                labCheckRecordDetailsVO.setIds(ids);
            }else{
                //没有准入的实验室 返回空
               return new ArrayList<>();
            }
        }
        startPage();
        labCheckRecordDetailsVO.setIsFabu(1);//已发布的数据
        List<LabCheckRecordDetailsVO> list = labCheckRecordDetailsService.selectLabCheckRecordWtzg(labCheckRecordDetailsVO);
        return  list;
    }
    /***
     * 根据隐患项id查询详情 - PC
     * @param id
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_CHECKRECORDDETAILS + PerFun.QUERY)
    @GetMapping("/dettailsList")
    public AjaxResult dettailsList( Long id) {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getDettailsList(id);
        return AjaxResult.success(map);
    }

    /***
     * 根据隐患项id查询详情 - 小程序
     * @param id
     * @return
     */
    @GetMapping("/dettailsListApp")
    public AjaxResult dettailsListApp( Long id) {
        Map<String, Object> map =new HashMap<String, Object>();
        map = getDettailsList(id);
        return AjaxResult.success(map);
    }

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

         //查询隐患项详情
         LabCheckRecordDetails details = labCheckRecordDetailsService.selectLabCheckRecordDetailsById(id);
         LabCheckRecordDetailsVO detailsVO = new LabCheckRecordDetailsVO();
         BeanUtils.copyProperties(details ,detailsVO);

         //检查记录
         LabCheckRecord labCheckRecord = labCheckRecordService.selectLabCheckRecordById(details.getCheckId());
         if(labCheckRecord==null || details==null){
             throw new ServiceException("未获取到相关信息");
         }

         LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
         detailslog.setCheckDetailsId(id);
         List<LabCheckRecordDetailslog> deatlog= iLabCheckRecordDetailslogService.selectLabCheckRecordDetailslogList(detailslog);
         detailsVO.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++;
                }
            }
            detailsVO.setCheckZs(flg);
        }*/

         map.put("details",detailsVO);
         map.put("record",labCheckRecord);
         return map;
     }
    /***
     *查询各个状态 检查记录总数
     * @return
     */
    @GetMapping("/selectDetailsStatusList")
    public AjaxResult selectDetailsStatusList() {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        LabCheckRecordVO labCheckRecordVo = new LabCheckRecordVO();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecordVo.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            labCheckRecordVo.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());
                }
                labCheckRecordVo.setIds(ids);
            }else{
                //没有准入的实验室 返回空
                return AjaxResult.success(new ArrayList<>());
            }
        }
        List<Map<String, Object>> map =labCheckRecordDetailsService.selectDetailsStatusList(labCheckRecordVo);
        return AjaxResult.success(map);
    }


    /**
     *  PC安全检查-院级-遗留问题
     */
    @GetMapping("/ResidualProblemList")
    @ApiOperation(value = "PC安全检查-院级-遗留问题")
    public TableDataInfo<LabCheckRecordDetailsVO> ResidualProblemList(LabCheckRecordDetailsVO labCheckRecordDetailsVO) {
        startPage();
        List<LabCheckRecordDetailsVO> list = labCheckRecordDetailsService.selectLabCheckRecordListVoIndex(labCheckRecordDetailsVO);
        return getDataTable(list);
    }

    /***
     *大屏安全检查批次列表 详情跳转遗留问题
     * @param labCheckRecordDetailsVO
     * @return
     */
    @GetMapping("/indexCheckDetalsWzg")
    public TableDataInfo<LabCheckRecordDetailsVO> indexCheckDetalsWzg(LabCheckRecordDetailsVO labCheckRecordDetailsVO) {
        LabCheckRecordRelease labCheckRecordRelease=new LabCheckRecordRelease();
        if(labCheckRecordDetailsVO.getId()==null){
            //获取最新一条的发布检查记录
            labCheckRecordRelease =labCheckRecordReleaseService.selectLabCheckRecordReleaseFirst();
        }else{
            //根据id查村实体
            labCheckRecordRelease =labCheckRecordReleaseService.selectLabCheckRecordReleaseById(labCheckRecordDetailsVO.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]));
            }
            labCheckRecordDetailsVO.setIds(ids);
        }*/

        //查询该条发布的检查详情 查询除最新检查发布外的所有数据
        startPage();
        labCheckRecordDetailsVO.setId(labCheckRecordRelease.getId());//最新一次发布的检查记录id
        labCheckRecordDetailsVO.setIsZg(1L);//未整改
        labCheckRecordDetailsVO.setRemark("1");//遗留问题条件
        List<LabCheckRecordDetailsVO> list = labCheckRecordDetailsService.selectLabCheckRecordIndexDetals(labCheckRecordDetailsVO);
        return getDataTable(list);
    }

    /***
     *大屏安全检查批次列表 详情跳转已整改
     * @param labCheckRecordDetailsVO
     * @return
     */
    @GetMapping("/indexCheckDetalsYzg")
    public TableDataInfo<LabCheckRecordDetailsVO> indexCheckDetalsYzg(LabCheckRecordDetailsVO labCheckRecordDetailsVO) {
        LabCheckRecordRelease labCheckRecordRelease=new LabCheckRecordRelease();
        if(labCheckRecordDetailsVO.getId()==null){
            //获取最新一条的发布检查记录
            labCheckRecordRelease =labCheckRecordReleaseService.selectLabCheckRecordReleaseFirst();
        }else{
            //根据id查村实体
            labCheckRecordRelease =labCheckRecordReleaseService.selectLabCheckRecordReleaseById(labCheckRecordDetailsVO.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]));
            }
            labCheckRecordDetailsVO.setIds(ids);
        }

        //查询该条发布的检查详情 查询本次发布检查所有详情
        startPage();
        //labCheckRecordDetailsVO.setIsZg(0L);//已整改
        List<LabCheckRecordDetailsVO> list = labCheckRecordDetailsService.selectLabCheckRecordIndexDetals(labCheckRecordDetailsVO);
        return getDataTable(list);
    }
}
