package com.zd.laboratory.service.impl;

import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.DictUtils;
import com.zd.laboratory.domain.*;
import com.zd.laboratory.domain.dto.LabBlacklistDTO;
import com.zd.laboratory.domain.dto.LabViolationDTO;
import com.zd.laboratory.domain.vo.*;
import com.zd.laboratory.mapper.*;
import com.zd.laboratory.service.ILabBlacklistService;
import com.zd.laboratory.service.ILabNegativelistHistoryService;
import com.zd.laboratory.service.ILabViolationService;
import com.zd.laboratory.service.ILabViolationSiteService;
import com.zd.system.api.domain.SysDictData;
import com.zd.system.api.exam.RemoteExamService;
import com.zd.system.api.laboratory.domain.LabMessageContent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;

/**
 * 违规记录Service业务层处理
 *
 * @author zd
 * @date 2021-09-01
 */
@Service
public class LabViolationServiceImpl implements ILabViolationService {
    @Autowired
    private LabViolationMapper labViolationMapper;

    @Autowired
    private LabSubjectManagerService subjectManagerService;

    @Autowired
    private LabNegativeListRecordsMapper negativeListRecordsMapper;

    @Autowired
    private LabNegativelistHistoryMapper negativelistHistoryMapper;

    @Autowired
    private ILabBlacklistService labBlacklistService;

    @Autowired
    private RemoteExamService remoteExamService;

    @Autowired
    private LabViolationHistoryRecordMapper violationHistoryMapper;

    @Autowired
    private ILabNegativelistHistoryService nhistoryService;
    @Autowired
    private LabMessageContentMapper labMessageContentMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LabViolationScoreSiteMapper scoreSiteMapper;

    @Autowired
    private ILabViolationSiteService violationSiteService;

    @Autowired
    private LabViolationScoreSiteMapper selectLabScoreSiteList;

    @Autowired
    private LabNegativelistHistoryMapper labNegativelistHistoryMapper;



    /**
     * 查询违规记录
     *
     * @param id 违规记录主键
     * @return
     */
    @Override
    public LabViolation selectLabViolationById(Long id) {
        return labViolationMapper.selectLabViolationById(id);
    }

    /**
     * 查询违规记录列表
     *
     * @param labViolation 违规记录
     * @return 违规记录
     */
    @Override
    @DataScope(deptAlias = "v")
    public List<LabViolationVO> selectLabViolationList(LabViolationVO labViolation) {

        return labViolationMapper.selectLabViolationList(labViolation);
    }


    /**
     * 查询违规记录详细列表
     *
     * @param labViolation 违规记录
     * @return 违规记录
     */
    @Override
    public List<LabViolationVO> getDetailList(LabViolationVO labViolation) {
        return labViolationMapper.getDetailList(labViolation);
    }

    /**
     * 查询违规记录列表VO
     *
     * @param labViolation
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<LabViolationVO> selectLabViolationVOList(LabViolationDTO labViolation) {


        return labViolationMapper.selectLabViolationVOList(labViolation);
    }

    /**
     * 查询自己的违规记录
     *
     * @param labViolation
     * @return
     */
    @Override
    public List<LabViolationVO> selectMyLabViolationVOList(LabViolationDTO labViolation) {

        return labViolationMapper.selectLabViolationVOList(labViolation);
    }


    /**
     * 新增违规记录
     *
     * @param labViolationVO 违规记录
     * @return 结果
     */
    @Override
    public int insertLabViolation(LabViolationVO labViolationVO) {

        long[] violationTypes = labViolationVO.getViolationTypes();
        int flag = 0;
        for (int i = 0; i < violationTypes.length; i++) {
            LabViolation labViolation = new LabViolation();
            BeanUtils.copyProperties(labViolationVO, labViolation);
            labViolation.setViolationType(violationTypes[i]);
            labViolation.setCreateTime(DateUtils.getNowDate());
            labViolation.setIsHandle(0L);
            labViolation.setViolationNum(labViolationVO.getViolationNum());
            labViolation.setNegativeListNum(labViolationVO.getNegativeListNum());
            labViolation.setBlackListNum(labViolationVO.getBlackListNum());
            List<SysDictData> dictList = DictUtils.getDictCache("lab_violation_rules");
            for (SysDictData dict : dictList) {
                if (dict.getDictValue().equals((labViolation.getViolationType() + ""))) {
                    labViolation.setViolationContent(dict.getDictLabel());
                }
            }
            flag = labViolationMapper.insertLabViolation(labViolation);
        }
        return flag;
    }

    /**
     * 修改违规记录
     *
     * @param labViolation 违规记录
     * @return 结果
     */
    @Override
    public int updateLabViolation(LabViolation labViolation) {
        labViolation.setUpdateTime(DateUtils.getNowDate());
        return labViolationMapper.updateLabViolation(labViolation);
    }

    /**
     * 批量删除违规记录
     *
     * @param ids 需要删除的违规记录主键
     * @return 结果
     */
    @Override
    public int deleteLabViolationByIds(Long[] ids) {
        return labViolationMapper.deleteLabViolationByIds(ids);
    }

    /**
     * 删除违规记录信息
     *
     * @param id 违规记录主键
     * @return 结果
     */
    @Override
    public int deleteLabViolationById(Long id) {
        return labViolationMapper.deleteLabViolationById(id);
    }

    /**
     * 小程序工作台，查询违规记录统计
     *
     * @param labViolation
     * @return 小程序工作台，查询违规记录统计
     */
    @Override
    public Map<String, Object> myViolationCount(LabViolation labViolation) {
        int count = labViolationMapper.myViolationCount(labViolation);
        Map<String, Object> map = new HashMap<>();
        map.put("violationCount", count);
        labViolation.setPenaltyType(1L);
        int teacherSee = labViolationMapper.myViolationCount(labViolation);
        if(teacherSee>0){
            map.put("teacherSee", true);
        }else{
            map.put("teacherSee", false);
        }
        return map;
    }


    /**
     * 小程序查询违规记录列表
     *
     * @param labViolation 违规记录
     * @return 违规记录
     */
    @Override
    public List<LabViolationVO> mylist(LabViolationVO labViolation) {
        return labViolationMapper.mylist(labViolation);
    }

    /**
     * 大屏 人员违规统计
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<Map<String, Object>> statistics(LabViolation labViolation) {
        List<Map<String, Object>>  list = labViolationMapper.statistics(labViolation);
        return list;
    }

    /**
     * 大屏 人员违规统计
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public LinkedHashMap<String,Object> newStatistics(LabViolation labViolation) {
        List<Map<String, Object>>  list = labViolationMapper.statistics(labViolation);
        LongAdder result = new LongAdder();
        Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().filter(a->a.size()>0).forEach(a->{
            result.add(Long.parseLong(a.get("count")+""));
        });
        LinkedHashMap<String,Object> allList = new LinkedHashMap<>();
        allList.put("resultCount",result.sum());
        allList.put("list",list);
        return allList;
    }

    /**
     * 大屏详情 人员违规柱状图统计
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<Object> columnar(LabViolationVO labViolationVO) {
        List<Object> returnAllList = new ArrayList<>();

        List<LabViolationColumnarVO>  list = new ArrayList<>();
        if(labViolationVO.getDeptLevel()!=null && labViolationVO.getDeptLevel().equals(1)){
            list = labViolationMapper.columnar(labViolationVO);
        }else if(labViolationVO.getDeptLevel()!=null && labViolationVO.getDeptLevel().equals(2)){
            list = labViolationMapper.columnarBySub(labViolationVO);
        }
        Map<Long,String> groupDeptMap = new HashMap<>();
        LinkedHashMap<Long, List<LabViolationColumnarVO>> collect = Optional.ofNullable(list)
                .filter(a -> a.size() > 0)
                .orElseGet(Collections::emptyList)
                .stream().map(a->{
                    groupDeptMap.put(a.getCurrencyid(),a.getCurrencyName());
                    return a;
                })
                .collect(Collectors.groupingBy(LabViolationColumnarVO::getCurrencyid,LinkedHashMap::new,Collectors.toList()));


        List<LabViolationScoreSite> scoreSites = selectLabScoreSiteList.selectLabScoreSiteList();

//        List<SysDictData> dictList = DictUtils.getDictCache("lab_violation_rules");
        List<Object> violationList = new ArrayList<>();
        for(LabViolationScoreSite score:scoreSites){
            violationList.add(score.getViolationName());
        }
        returnAllList.add(violationList);

        collect.forEach((key,value)->{
            List<LabViolationColumnarVO> allList = new ArrayList<>();
            Optional.ofNullable(scoreSites).orElseGet(Collections::emptyList)
                    .stream().forEach(a->allList.add(initViolation(a.getId()+"",a.getViolationName())));
            Optional.ofNullable(value).orElseGet(Collections::emptyList).stream()
                    .forEach(a-> Optional.ofNullable(allList).orElseGet(Collections::emptyList).stream()
                            .filter(b-> b.getType().equals(a.getType())).forEach(b->{
                                    b.setNum(a.getNum());
                                    b.setCurrencyid(a.getCurrencyid());
                                    b.setCurrencyName(a.getCurrencyName());
                            }));

            List<Object> changeList = new ArrayList<>();
            for(int i=0;i<allList.size();i++){
                if(i==0){
                    changeList.add(groupDeptMap.get(key));
                }
                changeList.add(allList.get(i).getNum());
            }
            returnAllList.add(changeList);
        });



//        for(Long key:collect.keySet()){
//            List<LabViolationColumnarVO> allList = new ArrayList<>();
//            List<SysDictData> dictList = DictUtils.getDictCache("lab_violation_rules");
//            List<LabViolationColumnarVO> columnarList = collect.get(key);
//            for(SysDictData sysDictData:dictList){
//                LabViolationColumnarVO labViolationColumnarVO = new LabViolationColumnarVO();
//                labViolationColumnarVO.setType(sysDictData.getDictValue());
//                labViolationColumnarVO.setContent(sysDictData.getDictLabel());
//                labViolationColumnarVO.setNum(0L);
//                allList.add(labViolationColumnarVO);
//            }
//            String currencyName = "";
//            for(LabViolationColumnarVO columnarVO:columnarList){
//                for(LabViolationColumnarVO allColumnar:allList){
//                    if(columnarVO.getType()!=null && columnarVO.getType().equals(allColumnar.getType())){
//                        allColumnar.setNum(columnarVO.getNum());
//                        allColumnar.setCurrencyid(columnarVO.getCurrencyid());
//                        allColumnar.setCurrencyName(columnarVO.getCurrencyName());
//                    }
//                    if(columnarVO.getCurrencyName()!=null){
//                        currencyName = columnarVO.getCurrencyName();
//                    }
//                }
//            }
//            allMap.put(currencyName,allList);
//        }
        return returnAllList;
    }


    /**
     * 大屏详情 实验室人员违规统计列表（校级）
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<LabViolationColumnarVO> subListBySchool(LabViolationVO labViolationVO) {
        List<LabViolationColumnarVO>  list = labViolationMapper.columnar(labViolationVO);
        List<LabViolationColumnarVO>  allList = new ArrayList<>();
        for(LabViolationColumnarVO columnarVO:list){
            if(columnarVO.getNum()>0){
                allList.add(columnarVO);
            }
        }
        return allList;
    }

    public LabViolationColumnarVO initViolation(String type,String content){
        LabViolationColumnarVO labViolationColumnarVO = new LabViolationColumnarVO();
        labViolationColumnarVO.setType(type);
        labViolationColumnarVO.setContent(content);
        labViolationColumnarVO.setNum(0L);
        return labViolationColumnarVO;
    }


    /**
     * 大屏详情 实验室人员违规统计列表（院级）
     * @return
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<LabViolationSubListVO> subList(LabViolationVO labViolationVO) {
        List<LabViolationSubListVO>  list = labViolationMapper.subList(labViolationVO);
        return list;
    }


    @Override
    @DataScope(deptAlias = "d" , permi = PerPrefix.LABORATORY_VIOLATION)
    public List<LabViolationVO> pageList(LabViolationVO labViolation) {
        return labViolationMapper.pageList(labViolation);
    }

    @Override
    public R removeNegativelist(LabViolationVO labViolation) {
        /*LabNegativelistHistory history = new LabNegativelistHistory();
        history.setUserId(labViolation.getUserId());
        history.setUserName(labViolation.getUserName());
        history.setReason(labViolation.getReason());*/
       int row = negativeListRecordsMapper.delByUserId(labViolation.getUserId());
       if (row > 0) {
         int rows = labViolationMapper.updateviolaton(labViolation.getUserId());
         if (rows >0) return R.ok();
         else return R.fail();
       }
       return R.fail();
    }

    /**
     * 新增违规记录new
     * @param vo
     * @return
     */
    @Override
    public R addViolationHistory(ViolationNewVo vo) {
        if (vo.getUserId()==null) return R.fail("用户id不能为空");
        if (vo.getDeptId()==null) return R.fail("关联学院不能为空");
        Boolean b = this.checkDeptId(vo.getDeptId());
        if (!b) return R.fail("该人员所属学院学院未找到");
        //校验规则
        Map<String, Object> p = new HashMap<>();
        p.put("userId",vo.getUserId());
        R r = remoteExamService.findByUserId(p);
        List<Map> list = (List<Map>) r.getData();
        Integer total = 0;Integer creditScore = 0;
        if (list!=null&& list.size()>0) {
            total = Integer.valueOf(list.get(0).get("totalPoints").toString());
            creditScore = Integer.valueOf(list.get(0).get("creditScore").toString());
        }
        if (r.getData()==null || ((List) r.getData()).size()<1)
            return R.fail("没有实验室安全准入资格");

        LabViolationScoreSite scoreSite = scoreSiteMapper.selectLabViolationScoreSiteById(Long.valueOf(vo.getReason()));
        Map map = new HashMap();
        map.put("joinUserId",vo.getUserId());
        if(vo.getReason().equals("-1")){
            map.put("deductPoints",vo.getDeductionVal());
        }else{
            map.put("deductPoints",scoreSite.getViolationVal());
        }
        map.put("pointsType","1");
        map.put("reason","手动新增违规记录");
        remoteExamService.deductionPoints(map);
        LabViolation labViolation = labViolationMapper.selectByUserId(vo.getUserId());
        LabNegativeListRecords records = negativeListRecordsMapper.findByUserId(vo.getUserId());

        Map<String, Object> mapscore = (Map<String, Object>) scoreData().getData();
        Integer hmdval = Integer.valueOf(mapscore.get("blackScore").toString());
        if (labViolation!=null) {

            Integer score = 0;
            LabNegativelistHistory history = CovertHistory(vo);
            if(vo.getReason().equals("-1")){
                score = creditScore - Integer.parseInt(vo.getDeductionVal()+"");
                history.setReason(vo.getViolationReasons());
                history.setDeductionVal(Long.valueOf(vo.getDeductionVal()));
            }else{
                score = creditScore - Integer.parseInt(scoreSite.getViolationVal());
                history.setReason(scoreSite.getViolationName());
                history.setDeductionVal(Long.valueOf(scoreSite.getViolationVal()));
            }
            history.setCreditScore(Long.valueOf(score));
            if(records==null){
                LabNegativeListRecords records1 = new LabNegativeListRecords();
                records1.setUserId(vo.getUserId());
                records1.setJoinUserId(vo.getUserId());
                records1.setStatus("2");
                records1.setCeditScore(score);
                records1.setBlackListNum("0");
                records1.setIsNegative(1);
                records1.setCreact_id(vo.getCreact_id());
                records1.setCreateTime(new Date());
                negativeListRecordsMapper.insertLabNegativeListRecords(records1);
                history.setBlackId(records1.getId());
            }else{
                history.setBlackId(records.getId());
            }

            history.setCreateTime(new Date());
            if(tokenService.getLoginUser()!=null){
                history.setCreateBy(tokenService.getLoginUser().getNickName());
            }else{
                history.setCreateBy("系统");
            }
            negativelistHistoryMapper.insertLabNegativelistHistory(history);


            //对比进入负面清单的次数如果达到直接进入黑名单
            if (labViolation.getNegativeListNum()+1>=getCount()){
                labViolation.setStatus(3);
                labViolation.setCreditScore(labViolation.getCreditScore());
                labViolationMapper.updateLabViolation(labViolation);
                comperAndExitsBlackList(vo.getUserId());
                return R.ok(200,"达到负面清单设定次数，直接加入黑名单成功");
            }else if(score <= hmdval) {//积分达到黑名单设定分值进入黑名单
//                comperAndExitsBlackList(vo.getUserId());
                labViolation.setCreditScore(labViolation.getCreditScore());
                labViolation.setViolationNum(labViolation.getViolationNum() + 1);
                if (records != null) {
                    labViolation.setBlackListNum(Long.valueOf(records.getBlackListNum()) + 1);
                }
                labViolation.setSubjectId(vo.getLaboratoryId());
                labViolation.setDeptName(vo.getDeptName());
                labViolation.setDeptId(vo.getDeptId());
                labViolation.setStatus(3);
                labViolation.setIsNegative(0);
                labViolation.setIsBlackList(1);
                labViolation.setCreact_id(vo.getCreact_id());
                labViolationMapper.updateLabViolation(labViolation);

                Integer passMark = Integer.valueOf(mapscore.get("passMark").toString());
                Integer newCreditScore = passMark-creditScore;
                violationBlack(vo.getUserId(),String.valueOf(newCreditScore),creditScore+"");
                return R.ok(200,"积分达到黑名单设定值，加入黑名单成功");
            }else{
                labViolation.setCreditScore(labViolation.getCreditScore());
                labViolation.setViolationNum(labViolation.getViolationNum() + 1);
                if (labViolation != null) {
                    labViolation.setNegativeListNum(Long.valueOf(labViolation.getNegativeListNum()) + 1);
                }
                labViolation.setSubjectId(vo.getLaboratoryId());
                labViolation.setDeptName(vo.getDeptName());
                labViolation.setDeptId(vo.getDeptId());
                labViolation.setStatus(2);
                labViolation.setIsNegative(1);
                labViolation.setCreact_id(vo.getCreact_id());
                labViolationMapper.updateLabViolation(labViolation);
                if (records != null) {
                    records.setViolationNum(records.getViolationNum() + 1);
                    Long num = Long.valueOf(records.getNegativeListNum()) + 1;
                    records.setNegativeListNum(num + "");
                    records.setDeptName(vo.getDeptName());
                    records.setIsNegative(1);
                    if(vo.getReason().equals("-1")){
                        records.setCeditScore(records.getCeditScore() - vo.getDeductionVal().intValue());
                    }else{
                        records.setCeditScore(records.getCeditScore()  - Integer.parseInt(scoreSite.getViolationVal()));
                    }

                    records.setStatus("2");
                    records.setCreact_id(vo.getCreact_id());
                    negativeListRecordsMapper.updateLabNegativeListRecords(records);
                }
            }
            return R.ok();
        }else{
            Integer score = 0;
            if(vo.getReason().equals("-1")){
                score = creditScore - Integer.parseInt(vo.getDeductionVal()+"");
            }else{
                score = creditScore - Integer.parseInt(scoreSite.getViolationVal());
            }
            if(score <= hmdval) {//积分达到黑名单设定分值进入黑名单
                Integer passMark = Integer.valueOf(mapscore.get("passMark").toString());
                Integer newCreditScore = passMark-creditScore;
                violationBlack(vo.getUserId(),String.valueOf(newCreditScore),creditScore+"");
                //违规记录
                labViolation = new LabViolation();
                labViolation.setUserId(vo.getUserId());
                labViolation.setJoinUserId(vo.getUserId());
                labViolation.setStatus(3);
                labViolation.setDeptName(vo.getDeptName());
                labViolation.setCreditScore(score);
                labViolation.setIsNegative(0);
                labViolation.setIsBlackList(1);
                labViolation.setNegativeListNum(0L);
                labViolation.setBlackListNum(1L);
                labViolation.setCreact_id(vo.getCreact_id());
                labViolation.setCreateTime(new Date());
                labViolationMapper.insertLabViolation(labViolation);
                records = new LabNegativeListRecords();
                records.setUserId(vo.getUserId());
                records.setJoinUserId(vo.getUserId());
                records.setStatus("2");
                records.setCeditScore(score);
                records.setNegativeListNum("0");
                records.setBlackListNum("1");
                records.setIsNegative(0);
                records.setIsBlackList(1);
                records.setCreact_id(vo.getCreact_id());
                records.setCreateTime(new Date());
                negativeListRecordsMapper.insertLabNegativeListRecords(records);
                vo.setCreditScore(Long.valueOf(score));
                LabNegativelistHistory nhistory = CovertHistory(vo);
                nhistory.setBlackId(records.getId());
                nhistory.setCreateTime(new Date());

                nhistory.setCreditScore(Long.valueOf(score));
                if(vo.getReason().equals("-1")){
                    nhistory.setReason(vo.getViolationReasons());
                    nhistory.setDeductionVal(Long.valueOf(vo.getDeductionVal()));
                }else{
                    nhistory.setReason(scoreSite.getViolationName());
                    nhistory.setDeductionVal(Long.valueOf(scoreSite.getViolationVal()));
                }
                if(tokenService.getLoginUser()!=null){
                    nhistory.setCreateBy(tokenService.getLoginUser().getNickName());
                }else{
                    nhistory.setCreateBy("系统");
                }
                negativelistHistoryMapper.insertLabNegativelistHistory(nhistory);
            }else{
                //违规记录
                labViolation = new LabViolation();
                labViolation.setUserId(vo.getUserId());
                labViolation.setJoinUserId(vo.getUserId());
                labViolation.setStatus(2);
                labViolation.setDeptName(vo.getDeptName());
                labViolation.setCreditScore(score);
                labViolation.setIsNegative(1);
                labViolation.setBlackListNum(0L);
                labViolation.setCreact_id(vo.getCreact_id());
                labViolation.setCreateTime(new Date());
                labViolationMapper.insertLabViolation(labViolation);
                records = new LabNegativeListRecords();
                records.setUserId(vo.getUserId());
                records.setJoinUserId(vo.getUserId());
                records.setStatus("2");
                records.setCeditScore(score);
                records.setBlackListNum("0");
                records.setIsNegative(1);
                records.setCreact_id(vo.getCreact_id());
                records.setCreateTime(new Date());
                negativeListRecordsMapper.insertLabNegativeListRecords(records);
                vo.setCreditScore(Long.valueOf(score));
                LabNegativelistHistory nhistory = CovertHistory(vo);
                nhistory.setBlackId(records.getId());
                nhistory.setCreateTime(new Date());

                nhistory.setCreditScore(Long.valueOf(score));
                if(vo.getReason().equals("-1")){
                    nhistory.setReason(vo.getViolationReasons());
                    nhistory.setDeductionVal(Long.valueOf(vo.getDeductionVal()));
                }else{
                    nhistory.setReason(scoreSite.getViolationName());
                    nhistory.setDeductionVal(Long.valueOf(scoreSite.getViolationVal()));
                }
                if(tokenService.getLoginUser()!=null){
                    nhistory.setCreateBy(tokenService.getLoginUser().getNickName());
                }else{
                    nhistory.setCreateBy("系统");
                }
                negativelistHistoryMapper.insertLabNegativelistHistory(nhistory);
            }



            return R.ok();
        }

       }


   public void comperAndExitsBlackList(Long userId){
       LabBlacklistVO vo = new LabBlacklistVO();
       vo.setJoinUserId(userId);
       this.blackAdd(vo);
    }


       public Long getCount(){
       List<LabViolationSite> violationSites = violationSiteService.selectLabViolationSite();
           if (violationSites!=null && violationSites.size() > 0){
              LabViolationSite site = violationSites.get(0);
              return Long.valueOf(site.getRemake());
           }
           return 0L;
       }




       public Boolean checkDeptId(Long deptId){
         Integer num = labViolationMapper.checkDeptId(deptId);
        if (num!=null){
            return true;
        }
        return false;
    }

    public LabNegativelistHistory CovertHistory(ViolationNewVo vo){
        LabNegativelistHistory history = new LabNegativelistHistory();
        history.setBlackId(vo.getId());
        history.setUserId(vo.getUserId());
        history.setReason(vo.getReason());
        history.setUserName(vo.getUserName());
        history.setDeductionVal(vo.getCreditScore());
        if(history.getTreatmentMethod()==null){
            history.setTreatmentMethod("");
        }
        Calendar handleDay = Calendar.getInstance();
        handleDay.setTime(getExpireDate(vo.getHandleDay()));
        //警告消息通知
        if(vo.getWarningStatus()!=null && vo.getWarningStatus()==1){
            //这里需要通知警告
            LabMessageContent labMessageContent = new LabMessageContent();
//            labMessageContent.setSendMode(1);
            labMessageContent.setSendRange(3);
            labMessageContent.setMessClass(1);
            labMessageContent.setContent("违规行为警告，请严格遵守实验室安全管理制度。");
            labMessageContent.setUserIds(vo.getUserId()+"");
            labMessageContent.setUserId(-2L);
            labMessageContent.setCreateTime(new Date());
            labMessageContent.setCreateBy("系统");
            labMessageContentMapper.insertLabMessageContent(labMessageContent);
            history.setTreatmentMethod(history.getTreatmentMethod()+"警告,");
            history.setWarningStatus(vo.getWarningStatus());
        }
        //约谈通知
        if(vo.getInterviewStatus()!=null && vo.getInterviewStatus()==1){
            //这里需要约谈通知，具体需不需要保存字段，等周一讨论
            LabMessageContent labMessageContent = new LabMessageContent();
//            labMessageContent.setSendMode(1);
            labMessageContent.setSendRange(3);
            labMessageContent.setMessClass(1);
            labMessageContent.setContent("联系负责老师进行安全教育约谈，请与"+handleDay.get(Calendar.YEAR)+"年"+(handleDay.get(Calendar.MONTH)+1)+"月"+(handleDay.get(Calendar.DAY_OF_MONTH))+"日之前完成。");
            labMessageContent.setUserIds(vo.getUserId()+"");
            labMessageContent.setUserId(-2L);
            labMessageContent.setCreateTime(new Date());
            labMessageContent.setCreateBy("系统");
            labMessageContentMapper.insertLabMessageContent(labMessageContent);
            history.setTreatmentMethod(history.getTreatmentMethod()+"约谈,");
            history.setInterviewStatus(vo.getInterviewStatus());
        }
        //学习状态
        if(vo.getLearnStatus()!=null && vo.getLearnStatus()==1){

            LabMessageContent labMessageContent = new LabMessageContent();
//            labMessageContent.setSendMode(1);
            labMessageContent.setSendRange(3);
            labMessageContent.setMessClass(1);
            labMessageContent.setContent("完成课程学习，时长要求："+vo.getLearnHour()+"小时"+vo.getLearnMinute()+"分钟" +
                    "，请与"+handleDay.get(Calendar.YEAR)+"年"+(handleDay.get(Calendar.MONTH)+1)+"月"+(handleDay.get(Calendar.DAY_OF_MONTH))+"日之前完成。");
            labMessageContent.setUserIds(vo.getUserId()+"");
            labMessageContent.setUserId(-2L);
            labMessageContent.setCreateTime(new Date());
            labMessageContent.setCreateBy("系统");
            labMessageContentMapper.insertLabMessageContent(labMessageContent);

            history.setLearnStatus(0);
            history.setTreatmentMethod(history.getTreatmentMethod()+"学习,");
            //处理小时和分钟，计算成秒
            history.setLearnTime(vo.getLearnHour()*60*60+vo.getLearnMinute()*60);
        }
        //考试状态
        if(vo.getTestStatus()!=null && vo.getTestStatus()==1){
            LabMessageContent labMessageContent = new LabMessageContent();
//            labMessageContent.setSendMode(1);
            labMessageContent.setSendRange(3);
            labMessageContent.setMessClass(1);
            labMessageContent.setContent("完成负面清单考试并考试合格，请与"+handleDay.get(Calendar.YEAR)+"年"+(handleDay.get(Calendar.MONTH)+1)+"月"+(handleDay.get(Calendar.DAY_OF_MONTH))+"日之前完成。");
            labMessageContent.setUserIds(vo.getUserId()+"");
            labMessageContent.setUserId(-2L);
            labMessageContent.setCreateTime(new Date());
            labMessageContent.setCreateBy("系统");
            labMessageContentMapper.insertLabMessageContent(labMessageContent);
            history.setTestStatus(0);
            history.setTreatmentMethod(history.getTreatmentMethod()+"考试,");
        }
        //做题状态
        if(vo.getPracticeStatus()!=null && vo.getPracticeStatus()==1){
            LabMessageContent labMessageContent = new LabMessageContent();
//            labMessageContent.setSendMode(1);
            labMessageContent.setSendRange(3);
            labMessageContent.setMessClass(1);
            labMessageContent.setContent("模拟练习"+vo.getNumberTopics()+"道题，正确率："+vo.getNumberAccuracy()+"%，" +
                    "，请与"+handleDay.get(Calendar.YEAR)+"年"+(handleDay.get(Calendar.MONTH)+1)+"月"+(handleDay.get(Calendar.DAY_OF_MONTH))+"日之前完成。");
            labMessageContent.setUserIds(vo.getUserId()+"");
            labMessageContent.setUserId(-2L);
            labMessageContent.setCreateTime(new Date());
            labMessageContent.setCreateBy("系统");
            labMessageContentMapper.insertLabMessageContent(labMessageContent);

            history.setPracticeStatus(0);
            history.setTreatmentMethod(history.getTreatmentMethod()+"做题,");
            history.setNumberTopics(vo.getNumberTopics());
            history.setNumberAccuracy(vo.getNumberAccuracy());
        }
        //处理多余的，号
        if(history.getTreatmentMethod()!=null && !"".equals(history.getTreatmentMethod())){
            history.setTreatmentMethod(history.getTreatmentMethod().substring(0,history.getTreatmentMethod().length()-1));
        }


        //将天数转为时间
        history.setHandleDay(getExpireDate(vo.getHandleDay()));
        history.setLaboratoryId(vo.getLaboratoryId());
        history.setLaboratoryName(vo.getLaboratoryName());
//        Long time = (vo.getLearnHour()*60*60)+(vo.getLearnMinute()*60);
//        history.setLearnTime(time);
//        history.setNumberAccuracy(vo.getNumberAccuracy());
//        history.setNumberTopics(vo.getNumberTopics());
        history.setCreditScore(vo.getCreditScore());
        history.setOverStatus(0);
//        history.setPracticeStatus(0);
//        history.setTestStatus(0);
//        history.setLearnStatus(0);
//        history.setTreatmentMethod(vo.getTreatmentMethod());
        return history;
    }


     public LabViolationHistoryRecord  CovertViolatonHistory(ViolationNewVo vo){
         LabViolationHistoryRecord record = new LabViolationHistoryRecord();
         record.setUserId(vo.getUserId());
         record.setReason("添加违规记录");
         record.setLaboratorys(vo.getLaboratoryName());
         record.setDeductionValue(vo.getCreditScore());
         record.setUserName(vo.getUserName());
         record.setTreatmentMethod(vo.getTreatmentMethod());
         record.setTestStatus(0);
         record.setLearnStatus(0);
         record.setPracticeStatus(0);
         record.setOverStatus(0);
         Long time = (vo.getLearnHour()*60*60)+(vo.getLearnMinute()*60);
         record.setLearnTime(time);
         record.setHandleDay(getExpireDate(vo.getHandleDay()));
         record.setNumberTopics(vo.getNumberTopics());
         record.setNumberAccuracy(vo.getNumberAccuracy());
         record.setCreditScore(vo.getCreditScore());
        return record;
     }


    public Date getExpireDate(Integer handleDay){
        //计算到期时间
        Date date=new   Date();//取时间
        Calendar calendar   =   new   GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,handleDay);//把日期往后增加一天.整数往后推,负数往前移动
        date=calendar.getTime();   //这个时间就是日期往后推一天的结果
        return date;
    }

    @Override
    public int updateStatus(Long joinUserId, Long i) {
        return labViolationMapper.updateStatus(joinUserId,i);
    }

    @Override
    @Transactional
    public R updateNegiveStatus(LabNegativeListRecordsVO vo) {
       // LabNegativeListRecords records = negativeListRecordsMapper.findByUserId(vo.getId());
        negativeListRecordsMapper.deleteLabNegativeListRecordsById(vo.getId());

        LabNegativelistVO labNegativelistHistoryVo = new LabNegativelistVO();
        labNegativelistHistoryVo.setBlackId(vo.getId());
        List<LabNegativelistHistory> negativelistHistoryList = labNegativelistHistoryMapper.selectLabNegativelistHistoryList(labNegativelistHistoryVo);
//        int limit = 0;
        for(LabNegativelistHistory history : negativelistHistoryList){
//            if(limit==1){
//                break;
//            }
            if(history.getLearnStatus().equals(0)){
                history.setLearnStatus(1);
            }
            if(history.getTestStatus().equals(0)){
                history.setTestStatus(1);
            }
            if(history.getPracticeStatus().equals(0)){
                history.setPracticeStatus(1);
            }
            history.setUserId(null);
            history.setOverStatus(1);
            labNegativelistHistoryMapper.updateLabNegativelistHistory(history);
//            limit++;
        }

       //更改状态，恢复信用分(如果此时信用分大于0，恢复时是否要累加，目前未累加)
        resetCreditScore(vo.getUserId());

        Map<String,Object> recoveryMap = new HashMap<>();
        recoveryMap.put("joinUserId",vo.getUserId()+"");
        recoveryMap.put("pointsType","1");
        if(vo.getHandAct()){
            recoveryMap.put("reason","手动负面清单移除恢复信用分");
        }else{
            recoveryMap.put("reason","负面清单移除恢复信用分");
        }

        remoteExamService.recoveryPoints(recoveryMap);

        return R.ok();
      /*  labViolationMapper.updateviolaton(vo.getJoinUserId());
       int rows = negativeListRecordsMapper.updateNegativeStatus(vo.getJoinUserId());
        if (rows > 0) {
            this.resetCreditScore(vo.getJoinUserId());
            return R.ok();
        }
        return R.fail();*/
    }



    @Override
    @Transactional
    public R updateNegiveStatusByPc(LabNegativeListRecordsVO vo) {
        // LabNegativeListRecords records = negativeListRecordsMapper.findByUserId(vo.getId());
        negativeListRecordsMapper.deleteLabNegativeListRecordsById(vo.getId());

        LabNegativelistVO labNegativelistHistoryVo = new LabNegativelistVO();
        labNegativelistHistoryVo.setBlackId(vo.getId());
        List<LabNegativelistHistory> negativelistHistoryList = labNegativelistHistoryMapper.selectLabNegativelistHistoryList(labNegativelistHistoryVo);
//        int limit = 0;
        for(LabNegativelistHistory history : negativelistHistoryList){
//            if(limit==1){
//                break;
//            }
            if(history.getLearnStatus().equals(0)){
                history.setLearnStatus(2);
            }
            if(history.getTestStatus().equals(0)){
                history.setTestStatus(2);
            }
            if(history.getPracticeStatus().equals(0)){
                history.setPracticeStatus(2);
            }
            history.setUserId(null);
            history.setOverStatus(2);
            labNegativelistHistoryMapper.updateLabNegativelistHistory(history);
//            limit++;
        }

        //更改状态，恢复信用分(如果此时信用分大于0，恢复时是否要累加，目前未累加)
        resetCreditScore(vo.getUserId());

        Map<String,Object> recoveryMap = new HashMap<>();
        recoveryMap.put("joinUserId",vo.getUserId()+"");
        recoveryMap.put("pointsType","1");
        if(vo.getHandAct()){
            recoveryMap.put("reason","手动负面清单移除恢复信用分("+vo.getReason()+")");
        }else{
            recoveryMap.put("reason","负面清单移除恢复信用分");
        }

        remoteExamService.recoveryPoints(recoveryMap);

        return R.ok();
    }

    @Override
    @Transactional
    public R blackAdd(LabBlacklistVO labBlacklistVO) {
       LabViolation violation = labViolationMapper.selectByUserId(labBlacklistVO.getJoinUserId());
       moveBlackList(violation,labBlacklistVO.getReason());
       Map <String, Object> pointsConfig = (Map <String, Object>) scoreData().getData();
        Long deducPoints = violation.getCreditScore()- Long.parseLong(pointsConfig.get("blackScore")+"");
        resetNegative(labBlacklistVO.getJoinUserId(),deducPoints);
         return R.ok();
    }


    public void violationBlack(Long userId,String creditScore,String surplusCredit){
        //违规分值达到黑名单分值进入
        LabBlacklistVO labBlacklistVO = new LabBlacklistVO();
        labBlacklistVO.setJoinUserId(userId);
        labBlacklistVO.setCreditScore(creditScore);
        labBlacklistVO.setSurplusCreditScore(surplusCredit);
        labBlacklistVO.setReason("严重违规移入到黑名单");
        labBlacklistService.addBlacklist(labBlacklistVO);
    }



    //移入黑名单操作
    public void moveBlackList(LabViolation violation,String reason){
        Map <String,Object> markconfigMap = new HashMap <>();
        R<Object> data = remoteExamService.getPointsConfig(markconfigMap);
        if (data!=null) {
            String code = data.getCode() + "";
            if (code.equals("200")) {
                Map <String, Object> pointsConfig = (Map <String, Object>) data.getData();
                Long deducPoints = violation.getCreditScore() - Long.parseLong(pointsConfig.get("blackScore")+"");
                if(deducPoints>0){
                    //这里扣减信用分
                    if(deducPointsFun(violation.getUserId(),deducPoints,reason)){
                        //这里移入黑名单
                        LabBlacklistVO labBlacklistVO = new LabBlacklistVO();
                        labBlacklistVO.setJoinUserId(violation.getUserId());
                        labBlacklistVO.setCreditScore(deducPoints+"");
                        labBlacklistVO.setSurplusCreditScore((violation.getCreditScore()-deducPoints)+"");
                        labBlacklistVO.setReason("从负面清单移入到黑名单");
                        labBlacklistService.addBlacklist(labBlacklistVO);
                    }
                }
            }
        }
    }


    private boolean deducPointsFun(Long joinUserId,Long deductPoints,String reason){
        Map <String,Object> deducPointsMap = new HashMap <>();
        deducPointsMap.put("joinUserId",joinUserId);
        deducPointsMap.put("deductPoints",deductPoints);
        deducPointsMap.put("pointsType",1);
        if(StringUtils.isNotNull(reason)){
            deducPointsMap.put("reason","手动添加到黑名单("+reason+")");
        }else{
            deducPointsMap.put("reason","手动添加到黑名单");
        }

        R<Object> data = remoteExamService.deductionPoints(deducPointsMap);
        if (data!=null) {
            String code = data.getCode() + "";
            if (code.equals("200")) {
                return true;
            }
        }
        return false;
    }

    @Override
    public R userexist(Long userId) {
        LabBlacklistDTO labBlacklist = new LabBlacklistDTO();
        labBlacklist.setJoinUserId(userId);
        labBlacklist.setBlacklistStatus(1);
        boolean b = labBlacklistService.getUserBoolean(labBlacklist);
        if (b) return R.ok(2);
       LabNegativeListRecords records = negativeListRecordsMapper.findByUserId(userId);
       if (records!=null)
        return R.ok(1);
       return  R.ok(0);
    }

    /**
     * 根据用户id或数据id更新:1:正常，2：负面清单,3,黑名单
     *
     * @param userId
     * @param id
     * @return
     */
    @Override
    public int updateTabs(Long userId, Long id) {
        return 0;
    }

    @Override
    @Transactional
    public R delBlacklist(LabBlacklist labBlacklist) {
        if (labBlacklist.getJoinUserId()==null) return R.fail("条件不能为空");
      /*  LabViolation violation = labViolationMapper.selectByUserId(labBlacklist.getJoinUserId());
        if (violation!=null) labViolationMapper.delByUserId(labBlacklist.getJoinUserId());*/
        //Map <String, Object> pointsConfig = (Map <String, Object>) scoreData().getData();
        labBlacklistService.removeBlacklist(labBlacklist);
             //移除黑名单后更改状态并恢复信用分
             updateUsers(labBlacklist);
        return R.ok();
    }

    @Override
    @Transactional
    public R delBlacklistByPc(LabBlacklist labBlacklist) {
        if (labBlacklist.getJoinUserId()==null) return R.fail("条件不能为空");
      /*  LabViolation violation = labViolationMapper.selectByUserId(labBlacklist.getJoinUserId());
        if (violation!=null) labViolationMapper.delByUserId(labBlacklist.getJoinUserId());*/
        //Map <String, Object> pointsConfig = (Map <String, Object>) scoreData().getData();
        labBlacklistService.removeBlacklistByPc(labBlacklist);
        //移除黑名单后更改状态并恢复信用分
        updateUsers(labBlacklist);
        return R.ok();
    }

    private void updateUsers(LabBlacklist labBlacklist) {
        this.labViolationMapper.updateUser(labBlacklist.getJoinUserId(),Long.valueOf(getScore()));
        this.negativeListRecordsMapper.updateUser(labBlacklist.getJoinUserId(),Long.valueOf(getScore()));
    }


    public Integer getScore(){
        Map<String,Object> markconfig = new HashMap<>();
        R r = remoteExamService.getPointsConfig(markconfig);
        //获取设置积分进行扣减
        Map<String, Object> result = (Map<String, Object>) r.getData();
        return Integer.valueOf(result.get("passMark").toString());
    }

    public R scoreData(){
        Map<String,Object> markconfig = new HashMap<>();
        R r = remoteExamService.getPointsConfig(markconfig);
        if (r.getCode()==200) return R.ok((r.getData()));
        return  R.fail("获取积分扣减接口失败");
    }


    /**
     * 根据用户id恢复信用分
     * @return
     */
    public void resetCreditScore(Long userId){
        //恢复违规表
        labViolationMapper.updateCreditScore(userId,this.getScore());
        //恢复负面清单表
        negativeListRecordsMapper.updateCreditScore(userId,this.getScore());
    }

    /**
     * 根据用户id更改负面清单状态
     * @return
     */
    public void resetNegative(Long userId,Long deval){
        //更改负面清单状态及扣减积分
        labViolationMapper.updateblackStatus(userId,deval);
        //加入黑名单后，黑名单按钮隐藏
        negativeListRecordsMapper.updateblackStatus(userId,deval);
    }




    @Override
    public R getPersonInfo() {
        Long userId = tokenService.getLoginUser().getUserid();
        LabViolationInfoVO info = labViolationMapper.getInfo(userId);
        return R.ok(info);
    }

    @Override
    public R exist() {
        Long userId = tokenService.getLoginUser().getUserid();
//        Map<String, Object> p = new HashMap<>();
//        p.put("userId",userId);
        LabViolationVO labViolation = new LabViolationVO();
        labViolation.setJoinUserId(userId);
        List<LabViolationVO> voList = labViolationMapper.pageList(labViolation);
//        R r = remoteExamService.findByUserId(p);
//        List<Map> list = (List<Map>) r.getData();
        if (voList.size()>0){
            LabViolationVO violationVO = voList.get(0);
            if(violationVO.getStatus()==1){
                R.fail();
            }else{
                return R.ok();
            }
        }
        return R.fail();
       /* LabViolationVO vo = new LabViolationVO();
        vo.setUserId(userId);
       List<LabViolationVO> violationList = labViolationMapper.selectLabViolationList(vo);
        if (violationList!=null && violationList.size() > 0)*/
    }


    /**
     * 从黑名单移除后此用户恢复正常，不再出现在负面清单和违规列表
     *
     * @param userId
     * @param reason
     * @return
     */
    @Override
    @Transactional
    public R resetUserStatus(Long userId, String reason) {
        //后续 reason
        labViolationMapper.delByUserId(userId);
        negativeListRecordsMapper.delByUserId(userId);
        //修改负面清单所有未完成变为以完成状态。
        LabNegativelistVO labNegativelistVO = new LabNegativelistVO();
        labNegativelistVO.setOverStatus(0);
        labNegativelistVO.setJoinUserId(userId);
        List<LabNegativelistHistory> negativelistHistoryList = negativelistHistoryMapper.selectLabNegativelistHistoryList(labNegativelistVO);
        for(LabNegativelistHistory newHistory:negativelistHistoryList){
            if(newHistory.getLearnStatus()==0){
                newHistory.setLearnStatus(1);
            }
            if(newHistory.getTestStatus()==0){
                newHistory.setTestStatus(1);
            }
            if(newHistory.getPracticeStatus()==0){
                newHistory.setPracticeStatus(1);
            }
            newHistory.setOverStatus(1);
            newHistory.setUserId(null);
            negativelistHistoryMapper.updateLabNegativelistHistory(newHistory);
        }
        return R.ok();
    }


    /**
     * 从黑名单移除后此用户变为以恢复
     *
     * @param userId
     * @param reason
     * @return
     */
    @Override
    @Transactional
    public R resetUserRecovery(Long userId, String reason) {
        //后续 reason
        labViolationMapper.delByUserId(userId);
        negativeListRecordsMapper.delByUserId(userId);
        //修改负面清单所有未完成变为以完成状态。
        LabNegativelistVO labNegativelistVO = new LabNegativelistVO();
        labNegativelistVO.setOverStatus(0);
        labNegativelistVO.setJoinUserId(userId);
        List<LabNegativelistHistory> negativelistHistoryList = negativelistHistoryMapper.selectLabNegativelistHistoryList(labNegativelistVO);
        for(LabNegativelistHistory newHistory:negativelistHistoryList){
            if(newHistory.getLearnStatus()==0){
                newHistory.setLearnStatus(2);
            }
            if(newHistory.getTestStatus()==0){
                newHistory.setTestStatus(2);
            }
            if(newHistory.getPracticeStatus()==0){
                newHistory.setPracticeStatus(2);
            }
            newHistory.setOverStatus(2);
            newHistory.setUserId(null);
            negativelistHistoryMapper.updateLabNegativelistHistory(newHistory);
        }
        return R.ok();
    }
}
