package com.zehong.web.controller.checktask;

import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.core.domain.entity.SysRole;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.enums.BusinessType;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.system.domain.SysPost;
import com.zehong.system.domain.TDanger;
import com.zehong.system.domain.TRectifyGroupMemberInfo;
import com.zehong.system.domain.vo.DangerApprovalVo;
import com.zehong.system.service.ISysUserService;
import com.zehong.system.service.ITDangerService;
import com.zehong.system.service.ITRectifyGroupMemberInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 安检隐患整改Controller
 * 
 * @author zehong
 * @date 2023-11-09
 */
@RestController
@RequestMapping("/checkTask/danger")
public class TDangerController extends BaseController
{
    @Autowired
    private ITDangerService tDangerService;

    @Autowired
    private ITRectifyGroupMemberInfoService tRectifyGroupMemberInfoService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 审核权限映射关系
     * 1.班长审核 2.部门经理审核 3.安全部审核 4.安全总监审核 5.常务副总审核 6.总经理审核结束
     */
    private final Map<String,String> approvalPermission = new HashMap<String,String>(){{
        put("2","minister");
        put("4","se");
        put("5","fuzong");
        put("6","manager");
    }};

    /**
     * 查询安检隐患整改列表
     */
   // @PreAuthorize("@ss.hasPermi('checkTask:danger:list')")
    @GetMapping("/list")
    public TableDataInfo list(TDanger tDanger)
    {
        startPage();
        List<SysRole> visitor = SecurityUtils.getLoginUser().getUser().getRoles().stream().filter(item ->"visitor".equals(item.getRoleKey())).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(visitor)){
            tDanger.setIsVisitor("1");
        }
        List<TDanger> list = tDangerService.selectTDangerList(tDanger);
        setApprovalPermission(list);
        return getDataTable(list);
    }

    /**
     * 设置审核权限
     * @param list 隐患列表
     */
    private void setApprovalPermission(List<TDanger> list){
        SysUser userInfo = SecurityUtils.getLoginUser().getUser();
        for(TDanger danger : list){
            //判断隐患为待审核状态
            if(3 == danger.getStatus()){
                if("1".equals(danger.getApprovalStatus())){
                    //上报人班长审核
                    Integer reportId = danger.getAdminId();
                    TRectifyGroupMemberInfo memberInfo = new TRectifyGroupMemberInfo();
                    memberInfo.setUserId(Long.valueOf(reportId));
                    List<TRectifyGroupMemberInfo> memberInfoList = tRectifyGroupMemberInfoService.selectTRectifyGroupMemberInfoList(memberInfo);
                    if(!CollectionUtils.isEmpty(memberInfoList)){
                        for(TRectifyGroupMemberInfo team : memberInfoList){
                            TRectifyGroupMemberInfo leader = new TRectifyGroupMemberInfo();
                            leader.setGroupId(team.getGroupId());
                            leader.setPost("1");
                            leader.setUserId(userInfo.getUserId());
                            List<TRectifyGroupMemberInfo> leaderInfo = tRectifyGroupMemberInfoService.selectTRectifyGroupMemberInfoList(leader);
                            if(!CollectionUtils.isEmpty(leaderInfo)){
                                danger.setHasApprovalPermission(true);
                                break;
                            }
                        }
                    }

                }else if("3".equals(danger.getApprovalStatus())){
                    //安全部审核
                    if("安全管理部".equals(userInfo.getDept().getDeptName())){
                        danger.setHasApprovalPermission(true);
                    }
                }else{
                    String post = approvalPermission.get(danger.getApprovalStatus());
                    //查询岗位信息
                    List<SysPost> userPost = sysUserService.selectPostsByUserName(userInfo.getUserName());
                    boolean flag = userPost.stream().anyMatch(item -> post.equals(item.getPostCode()));
                    if(flag){
                        danger.setHasApprovalPermission(true);
                    }
                }
            }
        }
    }

    @GetMapping("/dangerInfoList")
    public TableDataInfo dangerInfoList(TDanger tDanger){
        startPage();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //客服运营部
        if(200 == user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
            tDanger.setFlag(2);
        }
        //生产运营部
        if(102 == user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
            tDanger.setFlag(3);
        }

        //205 安全管理部
        if(205 != user.getDeptId() && 200 != user.getDeptId() && 102 != user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
        }
        List<TDanger> list = tDangerService.selectTDangerList(tDanger);
        return getDataTable(list);
    }

    /**
     * 导出安检隐患整改列表
     */
   // @PreAuthorize("@ss.hasPermi('checkTask:danger:export')")
    @Log(title = "安检隐患整改", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TDanger tDanger)
    {
        List<SysRole> visitor = SecurityUtils.getLoginUser().getUser().getRoles().stream().filter(item ->"visitor".equals(item.getRoleKey())).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(visitor)){
            tDanger.setIsVisitor("1");
        }
        List<TDanger> list = tDangerService.selectTDangerList(tDanger);
        ExcelUtil<TDanger> util = new ExcelUtil<TDanger>(TDanger.class);
        return util.exportExcel(list, "安检隐患整改数据");
    }

    /**
     * 获取安检隐患整改详细信息
     */
    //@PreAuthorize("@ss.hasPermi('checkTask:danger:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tDangerService.selectTDangerById(id));
    }

    /**
     * 新增安检隐患整改
     */
   // @PreAuthorize("@ss.hasPermi('checkTask:danger:add')")
    @Log(title = "安检隐患整改", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDanger tDanger)
    {
        Integer a = tDangerService.insertTDanger(tDanger);
        return AjaxResult.success(tDanger.getId());
    }

    /**
     * 修改安检隐患整改
     */
    //@PreAuthorize("@ss.hasPermi('checkTask:danger:edit')")
    @Log(title = "安检隐患整改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDanger tDanger)
    {
        return toAjax(tDangerService.updateTDanger(tDanger));
    }

    /**
     * 删除安检隐患整改
     */
    //@PreAuthorize("@ss.hasPermi('checkTask:danger:remove')")
    @Log(title = "安检隐患整改", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tDangerService.deleteTDangerByIds(ids));
    }


    /**
     * 游客数据权限设置
     * @param isVisitor 游客是否可访问
     * @param ids 隐患主键
     * @return
     */
    @GetMapping("/dangerDataPermission")
    public AjaxResult dangerDataVisitorPermission(@RequestParam(value="isVisitor")String isVisitor,@RequestParam(value="ids")Long[] ids){
        return toAjax(tDangerService.dangerDataVisitorPermission(isVisitor,ids));
    }


    /**
     * 根据隐患来源查询隐患
     * @param tDanger
     * @return
     */
    @GetMapping("/selectTDangerListByType")
    public TableDataInfo selectTDangerListByType(TDanger tDanger){
        startPage();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        /*//客服运营部
        if(200 == user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
            tDanger.setFlag(2);
        }
        //生产运营部
        if(102 == user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
            tDanger.setFlag(3);
        }

        //205 安全管理部
        if(205 != user.getDeptId() && 200 != user.getDeptId() && 102 != user.getDeptId()){
            tDanger.setAdminId(user.getUserId().intValue());
        }*/
        tDanger.setAdminId(user.getUserId().intValue());
        tDanger.setReformId(user.getUserId().intValue());
        List<TDanger> list = tDangerService.selectTDangerListByType(tDanger);
        return getDataTable(list);
    }

    /**
     * 隐患审核
     * @param approvalVo 隐患审核信息
     * @return
     */
    @PostMapping("/dangerApproval")
    public AjaxResult dangerApproval(@RequestBody List<DangerApprovalVo> approvalVo) {
        return toAjax(tDangerService.dangerApproval(approvalVo));
    }
}
