package com.zehong.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.page.PageDomain;
import com.zehong.common.core.page.TableSupport;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.sql.SqlUtil;
import com.zehong.system.domain.*;
import com.zehong.system.domain.vo.DangerApprovalVo;
import com.zehong.system.mapper.*;
import com.zehong.system.service.ISysUserService;
import com.zehong.system.service.ITDangerApprovalRecordService;
import com.zehong.system.service.ITDangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 安检隐患整改Service业务层处理
 * 
 * @author zehong
 * @date 2023-11-09
 */
@Service
public class TDangerServiceImpl implements ITDangerService 
{
    @Autowired
    private TDangerMapper tDangerMapper;

    @Autowired
    private TDangerStatusMapper tDangerStatusMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private TTaskInspectMapper taskInspectMapper;

    @Autowired
    private TIndustryMapper industryMapper;

    @Autowired
    private TBusinessMapper businessMapper;

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private ITDangerApprovalRecordService tDangerApprovalRecordService;

    @Resource
    private TRectifyGroupMemberInfoMapper tRectifyGroupMemberInfoMapper;

    @Autowired
    private ISysUserService sysUserService;

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


    /**
     * 查询安检隐患整改
     * 
     * @param id 安检隐患整改ID
     * @return 安检隐患整改
     */
    @Override
    public TDanger selectTDangerById(Long id)
    {
        TDanger danger = tDangerMapper.selectTDangerById(id);
        if(null != danger.getInspectId() && (1 == danger.getType() || 2 == danger.getType() || 3 == danger.getType())){
            TTaskInspect inspect = taskInspectMapper.selectTTaskInspectById(danger.getInspectId());
            danger.settTaskInspect(inspect);
        }
        return danger;
    }

    /**
     * 查询安检隐患整改列表
     * 
     * @param tDanger 安检隐患整改
     * @return 安检隐患整改
     */
    @Override
    public List<TDanger> selectTDangerList(TDanger tDanger)
    {
        return tDangerMapper.selectTDangerList(tDanger);
    }

    /**
     * 新增安检隐患整改
     * 
     * @param tDanger 安检隐患整改
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTDanger(TDanger tDanger)
    {
        tDanger.setCreateTime(DateUtils.getNowDate());
        tDanger.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId().intValue());
        //2025-03-06需求 某些登录人员新增隐患直接拥有游客访问权限
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysPost> posts = postMapper.selectUserPostList(user.getUserId());
        if(!CollectionUtils.isEmpty(posts)){
            if(posts.stream().map(SysPost::getPostCode).collect(Collectors.toList()).contains("kefu")){
                tDanger.setIsVisitor("1");
            }
        }
        if(tDanger.getReceiveId()!=null){
            if(tDanger.getType()==1){
                TUser u = userMapper.selectTUserById(tDanger.getReceiveId());
                tDanger.setBranch(u.getBranch());
            }else if(tDanger.getType()==2){
                TBusiness bu = businessMapper.selectTBusinessById(tDanger.getReceiveId());
                tDanger.setBranch(bu.getBranch());
            }else{
                TIndustry iu = industryMapper.selectTIndustryById(tDanger.getReceiveId());
                tDanger.setBranch(iu.getBranch());
            }
        }
        int result = tDangerMapper.insertTDanger(tDanger);
        TDangerStatus tDangerStatus = new TDangerStatus();
        tDangerStatus.setDangerId(tDanger.getId());
        tDangerStatus.setStatus(null == tDanger.getStatus()? 0 :tDanger.getStatus());
        tDangerStatus.setOptime(new Date());
        tDangerStatus.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
        tDangerStatusMapper.insertTDangerStatus(tDangerStatus);
        return result;
    }

    /**
     * 修改安检隐患整改
     * 
     * @param tDanger 安检隐患整改
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTDanger(TDanger tDanger)
    {
        if(null != tDanger.getStatus() && "2".equals(tDanger.getStatus().toString())){
            tDanger.setReformTime(new Date());
        }
        if(null != tDanger.getStatus() && "3".equals(tDanger.getStatus().toString())){
            tDanger.setCheckTime(new Date());
        }
        if(null != tDanger.getStatus() && "4".equals(tDanger.getStatus().toString())){
            tDanger.setFileTime(new Date());
        }
        TDangerStatus tDangerStatus = new TDangerStatus();
        tDangerStatus.setDangerId(tDanger.getId());
        tDangerStatus.setStatus(tDanger.getStatus());
        tDangerStatus.setOptime(new Date());
        tDangerStatus.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
        tDangerStatusMapper.insertTDangerStatus(tDangerStatus);
        return tDangerMapper.updateTDanger(tDanger);
    }

    /**
     * 批量删除安检隐患整改
     * 
     * @param ids 需要删除的安检隐患整改ID
     * @return 结果
     */
    @Override
    public int deleteTDangerByIds(Long[] ids)
    {
        return tDangerMapper.deleteTDangerByIds(ids);
    }

    /**
     * 删除安检隐患整改信息
     * 
     * @param id 安检隐患整改ID
     * @return 结果
     */
    @Override
    public int deleteTDangerById(Long id)
    {
        return tDangerMapper.deleteTDangerById(id);
    }

    /**
     * 游客数据权限设置
     * @param isVisitor 游客是否可访问
     * @param ids 隐患主键
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int dangerDataVisitorPermission(String isVisitor,Long[] ids){
        int num = 0;
        for(Long id : ids){
            TDanger danger = new TDanger();
            danger.setId(id);
            danger.setIsVisitor(isVisitor);
            tDangerMapper.updateTDanger(danger);
            num++;
        }
        return num;
    }


    /**
     * 根据隐患来源查询隐患
     * @param tDanger
     * @return
     */
    @Override
    public List<TDanger> selectTDangerListByType(TDanger tDanger)
    {
        return tDangerMapper.selectTDangerListByType(tDanger);
    }

    /**
     * 隐患审核
     * @param approvalList 隐患审核信息
     * @return
     */
    public int dangerApproval(List<DangerApprovalVo> approvalList){
        for(DangerApprovalVo approvalVo : approvalList){
            //获取隐患信息
            TDanger danger = tDangerMapper.selectTDangerById(approvalVo.getId());
            TDanger update = new TDanger();
            update.setId(danger.getId());
            if("0".equals(approvalVo.getState())){
                //审核通过
                //获取隐患级别
                if(1 == danger.getLevel()){
                    int status = Integer.parseInt(danger.getApprovalStatus());
                    //重大隐患
                    if(status < 6){
                        update.setApprovalStatus(String.valueOf(status+1));
                    }else{
                        //update.setApprovalStatus(String.valueOf(status+1));
                        update.setStatus(4);
                        //设置归档人归档时间
                        update.setFileId(SecurityUtils.getLoginUser().getUser().getUserId());
                        update.setFileTime(new Date());
                    }

                }else{
                    //一般隐患
                    int status = Integer.parseInt(danger.getApprovalStatus());
                    if(status < 3){
                        update.setApprovalStatus(String.valueOf(status+1));
                    }else{
                        //update.setApprovalStatus(String.valueOf(status+1));
                        update.setStatus(4);
                        //设置归档人归档时间
                        update.setFileId(SecurityUtils.getLoginUser().getUser().getUserId());
                        update.setFileTime(new Date());
                    }
                }
            }else{
                update.setStatus(0);
            }
            //更新隐患信息
            int result = tDangerMapper.updateTDanger(update);
            if (result == 0) throw new CustomException(danger.getTitle() + "隐患信息更新失败");
            //隐患记录
            TDangerApprovalRecord tDangerApprovalRecord = new TDangerApprovalRecord();
            tDangerApprovalRecord.setDangerId(approvalVo.getId());
            tDangerApprovalRecord.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            tDangerApprovalRecord.setApprovalStatus(approvalVo.getState());
            tDangerApprovalRecord.setSuggestion(approvalVo.getSuggestion());
            tDangerApprovalRecordService.insertTDangerApprovalRecord(tDangerApprovalRecord);
        }
        return 1;
    }


    /**
     * 获取待审核隐患
     * @param tDanger 隐患
     * @return
     */
    public List<TDanger> dangerPendingApprovalList(TDanger tDanger){

        /**
         * 隐患是待审核状态的
         * 1.审核状态是1 登录人是班长只查并且上报人在该组
         * 2.审核状态是3 判断登录人是否为安全管理部
         * 3.审核状态是2 4 5 6 判断登录人岗位
         */

        //查询权限
        String sqlCondition = buildSqlCondition();
        if(StringUtils.isEmpty(sqlCondition)){
            return new ArrayList<>();
        }
        //设置审核状态为待审核
        tDanger.setStatus(3);
        tDanger.getParams().put("approvalCondition",sqlCondition);

        //构建分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        return tDangerMapper.selectTDangerList(tDanger);
    }


    private String buildSqlCondition() {
        SysUser userInfo = SecurityUtils.getLoginUser().getUser();
        List<String> conditions = new ArrayList<>();

        // 1. 管理员条件
        TRectifyGroupMemberInfo queryParam = new TRectifyGroupMemberInfo();
        queryParam.setUserId(Long.valueOf(userInfo.getUserId()));
        List<TRectifyGroupMemberInfo> userInfoList = tRectifyGroupMemberInfoMapper.selectTRectifyGroupMemberInfoList(queryParam);
        if (!CollectionUtils.isEmpty(userInfoList)) {
            List<Long> userIdList = new ArrayList<>();
            for(TRectifyGroupMemberInfo user : userInfoList){
                if("1".equals(user.getPost()) && null != user.getGroupId()){
                    //查询组员信息
                    TRectifyGroupMemberInfo teamQuery = new TRectifyGroupMemberInfo();
                    teamQuery.setGroupId(user.getGroupId());
                    teamQuery.setPost("2");
                    List<TRectifyGroupMemberInfo> teamInfoList = tRectifyGroupMemberInfoMapper.selectTRectifyGroupMemberInfoList(teamQuery);
                    //查询组员信息
                    List<Long> teamUserIdList = teamInfoList.stream()
                            .map(TRectifyGroupMemberInfo::getUserId)
                            .filter(Objects::nonNull)
                            .distinct()
                            .collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(teamUserIdList)) userIdList.addAll(teamUserIdList);
                }

            }

            if (!CollectionUtils.isEmpty(userIdList)) {
                String userIds = userIdList.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
                conditions.add("(danger.admin_id IN (" + userIds + ") AND danger.approval_status = '1')");
            }
        }

        // 2. 部门条件
        if (userInfo != null && userInfo.getDept() != null && "安全管理部".equals(userInfo.getDept().getDeptName())) {
            conditions.add("danger.approval_status = '3'");
        }

        // 3. 岗位条件
        if (userInfo != null && StringUtils.isNotBlank(userInfo.getUserName())) {
            List<SysPost> userPostList = sysUserService.selectPostsByUserName(userInfo.getUserName());
            if (!CollectionUtils.isEmpty(userPostList)) {
                Set<String> statusSet = userPostList.stream()
                        .map(SysPost::getPostCode)
                        .map(approvalPermission::get)
                        .filter(StringUtils::isNotBlank)
                        .collect(Collectors.toSet());

                if (!CollectionUtils.isEmpty(statusSet)) {
                    String statuses = statusSet.stream()
                            .map(status -> "'" + status + "'")
                            .collect(Collectors.joining(","));
                    conditions.add("danger.approval_status IN (" + statuses + ")");
                }
            }
        }

        // 4. 组合所有条件
        if (conditions.isEmpty()) {
            return "";
        }
        if(conditions.size() == 1) return " AND " + conditions.get(0);
        return " AND (" + String.join(" OR ", conditions) + ")";
    }
}
