package com.zehong.system.service.impl;

import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.system.domain.*;
import com.zehong.system.domain.vo.DangerApprovalVo;
import com.zehong.system.mapper.*;
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.Date;
import java.util.List;
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;


    /**
     * 查询安检隐患整改
     * 
     * @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;
    }
}
