package com.zd.laboratory.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.datascope.annotation.DataScope;
import com.zd.common.security.utils.SaveUtil;

import com.zd.laboratory.domain.LabBlackdetail;
import com.zd.laboratory.domain.LabBlacklist;
import com.zd.laboratory.domain.LabNegativelistHistory;
import com.zd.laboratory.domain.vo.LabBlackdetailVO;
import com.zd.laboratory.domain.vo.LabNegativeListRecordsVO;
import com.zd.laboratory.mapper.LabNegativelistHistoryMapper;
import com.zd.laboratory.mapper.LabViolationMapper;
import com.zd.laboratory.service.ILabViolationService;
import com.zd.system.api.exam.RemoteExamService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.laboratory.mapper.LabNegativeListRecordsMapper;
import com.zd.laboratory.domain.LabNegativeListRecords;
import com.zd.laboratory.service.ILabNegativeListRecordsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 负面清单列表Service业务层处理
 *
 * @author zd
 * @date 2021-12-15
 */
@Service
public class LabNegativeListRecordsServiceImpl implements ILabNegativeListRecordsService
{
    @Autowired
    private LabNegativeListRecordsMapper labNegativeListRecordsMapper;

    @Autowired
    private LabNegativelistHistoryServiceImpl negativelistHistoryService;

    @Autowired
    private LabNegativelistHistoryMapper labNegativelistHistoryMapper;

    @Autowired
    private RemoteExamService remoteExamService;

    @Autowired
    private LabNegativelistHistoryMapper negativeHistoryMapper;

    @Autowired
    ILabViolationService violationService;

    @Autowired
    private LabViolationMapper labViolationMapper;

    /**
     * 查询负面清单列表
     *
     * @param id 负面清单列表主键
     * @return 负面清单列表
     */
    @Override
    public LabNegativeListRecords selectLabNegativeListRecordsById(Long id)
    {
        return labNegativeListRecordsMapper.selectLabNegativeListRecordsById(id);
    }

    /**
     * 查询负面清单列表列表
     *
     * @param labNegativeListRecords 负面清单列表
     * @return 负面清单列表
     */
    @Override
    @DataScope(deptAlias = "d" , permi = PerPrefix.LABORATORY_NEGATIVELISTRECORDS)
    public List<LabNegativeListRecords> selectLabNegativeListRecordsList(LabNegativeListRecordsVO labNegativeListRecords)
    {
        return labNegativeListRecordsMapper.selectLabNegativeListRecordsList(labNegativeListRecords);
    }

    /**
     * 新增负面清单列表
     *
     * @param history 负面清单列表
     * @return 结果
     */
    @Override
    public R insertLabNegativeListRecords(LabNegativelistHistory history)
    {
        LabNegativeListRecords negativeListRecords = labNegativeListRecordsMapper.findByUserId(history.getUserId());
        if (negativeListRecords!=null){
            Map map = new HashMap();
            map.put("joinUserId",history.getUserId());
            map.put("deductPoints",history.getCreditScore());
            map.put("pointsType","2");
            map.put("reason",history.getReason());
            remoteExamService.deductionPoints(map);
            Integer val = (negativeListRecords.getCeditScore())-(history.getCreditScore().intValue());
            negativeListRecords.setCeditScore(val);
            negativeListRecords.setViolationNum(1L);
            labNegativeListRecordsMapper.updateLabNegativeListRecords(negativeListRecords);
        }else{
            negativeListRecords = new LabNegativeListRecords();
            negativeListRecords.setUserId(history.getUserId());
            negativeListRecords.setViolationNum(1L);
            negativeListRecords.setCeditScore(history.getCreditScore().intValue());
            labNegativeListRecordsMapper.insertLabNegativeListRecords(negativeListRecords);
            history.setBlackId(negativeListRecords.getId());
        }

        //设置其他公共字段
       // SaveUtil.setCommonAttr(history);
        //给历史记录插入一条记录
        history.setDataType(1);
        int row = negativelistHistoryService.insertLabNegativelistHistory(history);
        if (row > 0) return R.ok();
        return R.fail();
    }

    /**
     * 修改负面清单列表
     *
     * @param labNegativeListRecords 负面清单列表
     * @return 结果
     */
    @Override
    public int updateLabNegativeListRecords(LabNegativeListRecords labNegativeListRecords)
    {
        return labNegativeListRecordsMapper.updateLabNegativeListRecords(labNegativeListRecords);
    }

    /**
     * 批量删除负面清单列表
     *
     * @param ids 需要删除的负面清单列表主键
     * @return 结果
     */
    @Override
    public int deleteLabNegativeListRecordsByIds(Long[] ids)
    {
        return labNegativeListRecordsMapper.deleteLabNegativeListRecordsByIds(ids);
    }

    /**
     * 删除负面清单列表信息
     *
     * @param id 负面清单列表主键
     * @return 结果
     */
    @Override
    public int deleteLabNegativeListRecordsById(Long id)
    {
        return labNegativeListRecordsMapper.deleteLabNegativeListRecordsById(id);
    }

    @Override
    public int updateStatus(Long userId) {

        return 0;/*labNegativeListRecordsMapper.deleteLabNegativeListRecordsById();*/
    }

    @Override
    public int updateIsNegative(Long joinUserId, Long i) {
        return labNegativeListRecordsMapper.updateIsNegative(joinUserId,i);
    }

    @Override
    public R negativelistCompletionLearningRules(Map map) {

        return null;
    }


    public void overBlackLearn(Long negativeId,Long joinUserId){
//        LabNegativelistHistory labBlackdetail = negativeHistoryMapper.selectLabNegativelistHistoryById(negativeId);
        LabNegativelistHistory labBlackdetail = labNegativelistHistoryMapper.selectLabNegativelistHistoryByUserId(joinUserId);
        if(labBlackdetail!=null && labBlackdetail.getOverStatus()==0){
            int maxCount = 0;
            int nowCount = 0;
            if(labBlackdetail.getLearnStatus()!=-1){
                if(labBlackdetail.getLearnStatus()==1){
                    nowCount++;
                }
                maxCount++;
            }
            if(labBlackdetail.getTestStatus()!=-1){
                if(labBlackdetail.getTestStatus()==1){
                    nowCount++;
                }
                maxCount++;
            }
            if(labBlackdetail.getPracticeStatus()!=-1){
                if(labBlackdetail.getPracticeStatus()==1){
                    nowCount++;
                }
                maxCount++;
            }
            if(maxCount!=0){
                if(nowCount==maxCount){
                    LabNegativelistHistory labBlackdetailNew = new LabNegativelistHistory();
                    labBlackdetailNew.setId(labBlackdetail.getId());
                    labBlackdetailNew.setOverStatus(1);
                    labBlackdetailNew.setUpdateBy("系统执行");
                    labBlackdetailNew.setUpdateTime(new Date());
                    negativeHistoryMapper.updateLabNegativelistHistory(labBlackdetailNew);
                    LabNegativeListRecordsVO vo = new LabNegativeListRecordsVO();
                    vo.setUserId(joinUserId);
                    vo.setId(negativeId);
                    vo.setReason("完成规定内容:"+labBlackdetail.getTreatmentMethod()+",系统自动复原信用分.");
                   // removeBlacklist(labBlacklist);
                    violationService.updateNegiveStatus(vo);
                }
            }

        }
    }

    /**
     * 获取过期时间的数据
     *
     * @return
     */
    @Override
    public R getExpireTimeData() {
       /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(new Date());*/
        return R.ok(negativeHistoryMapper.getExpireTimeData());
    }

    @Override
    public R delNegivelist(LabNegativeListRecordsVO vo) {
        //增加一条记录
      /*  LabNegativelistHistory history = negativelistHistoryService.selectLabNegativelistHistoryById(vo.getId());
        history.setReason(vo.getReason());
        negativelistHistoryService.insertLabNegativelistHistory(history);*/
        //更改按钮状态

        Map<String,Object> recoveryMap = new HashMap<>();
        recoveryMap.put("joinUserId",vo.getUserId()+"");
        recoveryMap.put("pointsType","1");
        recoveryMap.put("reason",vo.getReason());
        //恢复积分
        R <Object> data = remoteExamService.recoveryPoints(recoveryMap);
        if (data.getCode()==200) return R.ok();
        return R.fail();

    }

    @Override
    public R delexam(LabNegativeListRecordsVO vo) {
        LabNegativeListRecords records = this.labNegativeListRecordsMapper.findByUserId(vo.getUserId());
        if (records!=null){
            //恢复信用分，并且将状态置为正常，非负面清单
            violationService.resetCreditScore(vo.getUserId());
        }

        updateIsNegative(vo.getUserId(),0L);
        Map<String,Object> recoveryMap = new HashMap<>();
        recoveryMap.put("joinUserId",vo.getUserId()+"");
        recoveryMap.put("pointsType","1");
        recoveryMap.put("reason",vo.getReason());
        //恢复积分
        R <Object> data = remoteExamService.recoveryPoints(recoveryMap);
        if (data.getCode()==200) return R.ok();
        return R.ok();
    }

    @Override
   public R updateByUserId(Long userId,Long deducPoints){
       this.labNegativeListRecordsMapper.updateByUserId(userId);
       int row = labNegativeListRecordsMapper.updateblackStatus(userId,deducPoints);
       if (row > 0) return R.ok();
       return R.fail();
   }

    @Override
    public int negivelistLearningRules(LabBlackdetailVO blackdetailVO) {
        int flag = 0;
        LabNegativeListRecords labNegativeListRecords =  labNegativeListRecordsMapper.findByUserId(blackdetailVO.getJoinUserId());
        if(labNegativeListRecords!=null){
            LabNegativelistHistory labNegativedetail = labNegativelistHistoryMapper.selectLabNegativelistHistoryByUserId(blackdetailVO.getJoinUserId());
//            LabNegativelistHistory labNegativedetail = negativeHistoryMapper.selectLabNegativelistHistoryById(labNegativeListRecords.getId());
            LabNegativelistHistory labNegativedetailNew = new LabNegativelistHistory();
            if(blackdetailVO.getLearnStatus()!=null && blackdetailVO.getLearnStatus()==labNegativedetail.getLearnStatus()){
                if(blackdetailVO.getLearnTime()>=labNegativedetail.getLearnTime()){
                    labNegativedetailNew.setLearnStatus(1);
                    labNegativedetailNew.setId(labNegativedetail.getId());
                }
            }
            if(blackdetailVO.getTestStatus()!=null && blackdetailVO.getTestStatus()==labNegativedetail.getTestStatus()){
                labNegativedetailNew.setTestStatus(1);
                labNegativedetailNew.setId(labNegativedetail.getId());
            }
            if(blackdetailVO.getPracticeStatus()!=null && blackdetailVO.getPracticeStatus()==labNegativedetail.getPracticeStatus()){
                if(blackdetailVO.getNumberTopics()>=labNegativedetail.getNumberTopics()){
                    if(blackdetailVO.getNumberAccuracy()>=labNegativedetail.getNumberAccuracy()){
                        labNegativedetailNew.setPracticeStatus(1);
                        labNegativedetailNew.setId(labNegativedetail.getId());
                    }
                }
            }
            if(labNegativedetailNew.getId()!=null){
                labNegativedetailNew.setUpdateBy("系统执行");
                labNegativedetailNew.setUpdateTime(new Date());
                labNegativelistHistoryMapper.updateLabNegativelistHistory(labNegativedetailNew);
            }

            overBlackLearn(labNegativeListRecords.getId(),blackdetailVO.getJoinUserId());
            flag = 200;
        }
        return flag;
    }

    @Override
    public LabNegativelistHistory getNegiveTimeArea(LabBlackdetailVO blackdetailVO) {
        return  labNegativelistHistoryMapper.selectLabNegativelistHistoryByUserId(blackdetailVO.getJoinUserId());
    }


}
