package com.zd.laboratory.controller;

import cn.hutool.core.util.StrUtil;
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.enums.HazardTypeEnum;
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.LabHazard;
import com.zd.laboratory.domain.LabHazardSubjectRelation;
import com.zd.laboratory.domain.LabQpSubjectRelation;
import com.zd.laboratory.domain.LabSubject;
import com.zd.laboratory.domain.vo.LabHazardSubjectRelationVO;
import com.zd.laboratory.domain.vo.LabSubjectVO;
import com.zd.laboratory.mapper.LabSubjectMapper;
import com.zd.laboratory.mqtt.constants.MqttConstants;
import com.zd.laboratory.mqtt.service.impl.CommonSend;
import com.zd.laboratory.service.ILabHazardSubjectRelationService;
import com.zd.laboratory.service.ILabQpSubjectRelationService;
import com.zd.laboratory.service.ILabSubjectService;
import com.zd.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;


/**
 * 实验室Controller
 *
 * @author zd
 * @date 2021-08-30
 */
@RestController
@RequestMapping("/subject")
public class LabSubjectController extends BaseController {
    @Autowired
    private ILabSubjectService labSubjectService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ILabHazardSubjectRelationService labHazardSubjectRelationService;

    @Autowired
    private LabSubjectMapper labSubjectMapper;

    @Autowired
    private CommonSend commonSend;

    @Autowired
    private ILabQpSubjectRelationService labQpSubjectRelationService;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询实验室列表
     */
    @GetMapping("/list")
    @Deprecated
    public TableDataInfo<LabSubject> list(LabSubject labSubject) {
        startPage();
        List<LabSubject> list = labSubjectService.selectLabSubjectList(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询未关联负责人的实验室列表
     */
    @GetMapping("/list/noadmin")
    @Deprecated
    public TableDataInfo<LabSubject> listNoAdmin(LabSubject labSubject) {
        startPage();
        labSubject.setAdminId(-1L);
        List<LabSubject> list = labSubjectService.selectLabSubjectList(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询有权限的实验室列表（数据权限）
     */
    @Deprecated
    @GetMapping("/list/nopage")
    public List<LabSubject> listNoPage(LabSubject labSubject) {
//        startPage();
//        labSubject.setAdminId(-1L);
        List<LabSubject> list = labSubjectService.selectLabSubjectList(labSubject);
        return list;
    }

    /**
     * 查询有权限的实验室列表
     */
    @Deprecated
    @GetMapping("/list/security")
    public List<LabSubject> listSecurity(LabSubject labSubject) {
        List<LabSubject> list = labSubjectService.selectLabSubjectListSecurity(labSubject);
        return list;
    }

    @GetMapping("/list/listAdmin")
    public List<LabSubject> listAdmin(LabSubject labSubject) {
        //获取当前登录用户所属学校和学院的deptid
        R<List<Long>> listdeptids = remoteUserService.getLogingUserDeptids();
        List<Long> deptIds= listdeptids.getData();
        labSubject.setDeptIds(deptIds);
        List<LabSubject> list = labSubjectService.selectLabSubjectListByadminidNotnull(labSubject);
        return list;
    }

    /**
     * 查询登录用户是否是实验室管理员（数据权限）
     */
    @RequestMapping("/my/isadmin")
    public AjaxResult isadmin(@RequestBody LabSubject labSubject) {
        return AjaxResult.success(labSubjectService.isadmin(labSubject));
    }

    /**
     * 导出实验室列表
     */
    @Log(title = "实验室", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabSubject labSubject) throws IOException {
        List<LabSubject> list = labSubjectService.selectLabSubjectList(labSubject);
        ExcelUtil<LabSubject> util = new ExcelUtil<LabSubject>(LabSubject.class);
        util.exportExcel(response, list, "实验室数据");
    }

    /**
     * 获取实验室详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(labSubjectService.selectLabSubjectById(id));
    }

    /**
     * 获取实验室详细信息
     */
    @GetMapping(value = "/vo/{id}")
    public AjaxResult getVoInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(labSubjectService.selectLabSubjectVoById(id));
    }

    /**
     * 查询实验室
     *
     * @param id 实验室主键
     * @return 实验室
     */
    @RequestMapping(value = "/check/{id}")
    public AjaxResult getCheckInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(labSubjectService.selectLabSubjectCheckById(id));
    }

    /**
     * 获取管理实验室数量-通过用户ids
     */
//    @PreAuthorize(hasPermi = "laboratory:subject:query")
    @GetMapping(value = "/count/{ids}")
    public ResultData<List<LabSubjectVO>> getInfoByUserIds(@PathVariable("ids") Long... ids) {
        List<LabSubjectVO> labSubjectVOS = labSubjectService.selectLabSubjectListByAdminIds(ids);
        return ResultData.success(labSubjectVOS);
    }


    /**
     * 新增实验室
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.ADD)
    @Log(title = "实验室", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabSubject labSubject) {
        labSubject.setUserId(tokenService.getLoginUser().getUserid());
        labSubject.setCreateBy(tokenService.getLoginUser().getUsername());
        return toAjax(labSubjectService.insertLabSubject(labSubject));
    }

    /**
     * 修改实验室
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.EDIT)
    @Log(title = "实验室", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody LabSubject labSubject) {
        labSubjectService.updateLabSubject(labSubject);
        commonSend.send(MqttConstants.LAB_SUB_INFO + labSubject.getId(), labSubject.getId() + "实验室信息变更通知！");
        return R.ok();
    }


    /**
     * 修改实验室
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.EDIT)
    @Log(title = "实验室", businessType = BusinessType.UPDATE)
    @PutMapping("/editJoinHazard")
    public R editJoinHazard(@RequestBody LabSubject labSubject) {
        labSubjectService.editJoinHazard(labSubject);
        commonSend.send(MqttConstants.LAB_SUB_INFO + labSubject.getId(), labSubject.getId() + "实验室信息变更通知！");
        return R.ok();
    }

    /**
     * 给实验室关联用户
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.EDIT)
    @Log(title = "给实验室关联用户", businessType = BusinessType.UPDATE)
    @PutMapping("/{userId}/{subId}")
    public AjaxResult setAdmin(@PathVariable Long userId, @PathVariable Long subId) {
        if (userId.equals(-1L)) {
            LabSubject labSubject = new LabSubject();
            labSubject.setId(subId);
            labSubject.setAdminId(userId);
            return toAjax(labSubjectService.updateLabSubject(labSubject));
        } else {

            return toAjax(labSubjectService.setSubjectAdmin(userId, subId));
        }

    }


//    /**
//     * 删除实验室
//     */
//    @PreAuthorize(hasPermi = "laboratory:subject:remove")
//    @Log(title = "实验室", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        return toAjax(labSubjectService.deleteLabSubjectByIds(ids));
//    }
    /**
     * 禁用/启用实验室
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.REMOVE)
    @Log(title = "实验室", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}/{f}")
    public AjaxResult remove(@PathVariable("f") Boolean f,@PathVariable("id") Long id) {
        LabSubject labSubject = new LabSubject();
        labSubject.setId(id);
        labSubject.setIsDel(f);
        return toAjax(labSubjectService.updateLabSubject(labSubject));

    }
    /**
     * 新增危险源和实验室绑定数据
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.ADDSUB)
    @Log(title = "危险源和实验室绑定", businessType = BusinessType.INSERT)
    @PostMapping("/setHazard")
    public AjaxResult addSubjectByHazard(@RequestBody LabHazardSubjectRelationVO labHazardSubjectRelationVO) {
        for (LabHazard hazard : labHazardSubjectRelationVO.getHazardList()) {
            LabHazardSubjectRelation labHazardSubjectRelation = new LabHazardSubjectRelation();
            labHazardSubjectRelation.setHazardId(hazard.getId());
            labHazardSubjectRelation.setSubjectId(labHazardSubjectRelationVO.getSubjectId());
            labHazardSubjectRelation.setHazardType(HazardTypeEnum.HAZARD);
            labHazardSubjectRelationService.insertLabHazardSubjectRelation(labHazardSubjectRelation);
        }
        return toAjax(200);
    }

    /**
     * 查询实验室字典表
     */
    @GetMapping("/getSubjectDict")
    public AjaxResult getSubjectDict(LabSubject labSubject) {
        List<LabSubject> list = labSubjectService.getSubjectDict(labSubject);
        return AjaxResult.success(list);
    }

    /**
     * 查询实验室字典表
     */
    @GetMapping("/getSubjectDictByViolation")
    public AjaxResult getSubjectDictByViolation(LabSubject labSubject) {
        List<LabSubject> list = labSubjectService.getSubjectDictByViolation(labSubject);
        return AjaxResult.success(list);
    }

    /**
     * 查询实验室字典表
     */
    @GetMapping("/getFilterSubjectDict")
    public AjaxResult getFilterSubjectDict(LabSubjectVO labSubject) {
        List<LabSubject> list = labSubjectService.getFilterSubjectDict(labSubject);
        return AjaxResult.success(list);
    }

    /**
     * 获取实验室负责人手机号
     * @return
     */
    @GetMapping("/{subId}/admin/phone")
    public R getAdminPhone(@PathVariable Long  subId)
    {
        LabSubject labSubject = new LabSubject();
        labSubject.setId(subId);
        List<LabSubjectVO> labSubjectVOS = labSubjectMapper.selectLabSubjectVOList(labSubject);
        String s = Optional.ofNullable(labSubjectVOS)
                .filter(a -> a.size() > 0)
                .map(a -> a.get(0).getAdminPhone())
                .filter(a-> StrUtil.isNotBlank(a))
                .orElse(null);
        return R.ok(s);
    }



    /**
     * 实验室弹框选择器接口
     */
    @GetMapping("/listInfo")
    public TableDataInfo getListInfo(LabSubjectVO labSubject) {
        startPage();
        List<LabSubjectVO> list =labSubjectService.selectLabSubjectListAUTH(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询实验室根据实验室管理员用户权限过滤数据
     */
    @GetMapping("/getUserRoleBySub")
    public TableDataInfo getUserRoleBySub(LabSubjectVO labSubject) {
        startPage();
        List<LabSubject> list = labSubjectService.getUserRoleBySub(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询根据实验室管理员查询预案绑定的数据
     */
    @GetMapping("/getUserRoleBySubBindRisk")
    public TableDataInfo getUserRoleBySubBindRisk(LabSubjectVO labSubject) {
        startPage();
        List<LabSubject> list = labSubjectService.getUserRoleBySubBindRisk(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询实验室根据实验室管理员用户权限过滤数据
     */
    @GetMapping("/getAllSubjectByParame")
    public TableDataInfo getAllSubjectByParame(LabSubjectVO labSubject) {
        //获取当前登录用户所属学校和学院的deptid
        R<List<Long>> listdeptids = remoteUserService.getLogingUserDeptids();
        if(200==listdeptids.getCode()){
            //按部门集合查询
            List<Long> deptIds= listdeptids.getData();
            labSubject.setDeptIds(deptIds);
            labSubject.setDeptId(null);
        }

        startPage();
        List<LabSubject> list = labSubjectService.getAllSubjectByParame(labSubject);
        return getDataTable(list);
    }

    /**
     * 查询实验室根据实验室管理员用户权限是否有操作权限
     */
    @GetMapping("/getUserRoleBySubOperation")
    public AjaxResult getUserRoleBySubOperation(LabSubjectVO labSubject) {
        List<LabSubject> list = labSubjectService.getUserRoleBySub(labSubject);
        Boolean subOperation = false;
        if(list.size()>0){
            subOperation = true;
        }
        return AjaxResult.success(subOperation);
    }


    /**
     * 查询多个院系下的实验室
     */
    @GetMapping("/multipleDetp/subList/{ids}")
    public List<LabSubject> multipleDeptBySubList(@PathVariable Long[] ids) {
        return labSubjectService.multipleDetpBysubList(ids);
    }

    /**
     * 获取实验室气瓶数量详细信息
     */
    @GetMapping(value = "/getBottleInfo")
    public AjaxResult getBottleInfo(Long subjectId) {
        //查询该实验室的气瓶配置数量
        LabQpSubjectRelation labQpSubjectRelation = new LabQpSubjectRelation();
        labQpSubjectRelation.setSubjectId(subjectId);
        List<LabQpSubjectRelation> list =labQpSubjectRelationService.selectLabQpSubjectRelationList(labQpSubjectRelation);
        if(!list.isEmpty()){
            labQpSubjectRelation = list.get(0);
        }
        return AjaxResult.success(labQpSubjectRelation);
    }

    /**
     * 查询首页分类统计
     */
    @GetMapping("/getTypeCount")
    public AjaxResult getTypeCount(LabSubjectVO labSubject) {
        return AjaxResult.success(labSubjectService.getTypeCount(labSubject));
    }

    /**
     * 查询首页分级统计
     */
    @GetMapping("/getFiedCount")
    public AjaxResult getFiedCount(LabSubjectVO labSubject) {
        return AjaxResult.success(labSubjectService.getFiedCount(labSubject));
    }
}
