package com.pqs9300.serviceimpl.transaction;

import com.njcn.mapper.configuration.LineMapper;
import com.njcn.pojo.configuration.Line;
import com.njcn.pojo.user.Depts;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import com.pqs9300.mapper.transaction.OverRunLogMapper;
import com.pqs9300.mapper.transaction.SuperviseMapper;
import com.pqs9300.pojo.transaction.*;
import com.pqs9300.service.transaction.SuperviseService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author hongawen
 * @date: 2020/7/1 11:41
 */
@Service
public class SuperviseServiceImpl implements SuperviseService {

    @Resource
    private SuperviseMapper superviseMapper;

    @Resource
    private UserUtil userUtil;

    @Resource
    private OverRunLogMapper overRunLogMapper;

    @Resource
    private LineMapper lineMapper;

    /**
     * 首页获取当前用户的下的事务列表
     * 时间范围是固定的，但是事务类型 0 预警  1 告警  2 全部
     * 事务当前的流程 0开始 1下发 2反馈 3现场测试 4整改通知 5整改反馈 6完结 7 全部
     * <p>
     * 事务主表的数据存在两种状态 1 用户新建或者定时器新建的记录，只能根据部门索引去筛选 2 事件已经经过处理，upUser不为空，需要根据当前用户索引去获取
     */
    @Override
    public IndexPojo getTransactionData(Date startTime, Date endTime, Integer type, Integer progress) throws Exception {
        IndexPojo indexPojo=new IndexPojo();
        List<Supervise> supervises = new ArrayList<>();
        //获取当前用户部门,根据用户部门遍历出所有子部门
        Depts depts = userUtil.getCurrentDept();
        List<Depts> deptsList = userUtil.getDeptsByNode(depts.getDeptsIndex());
        //首先查出upUser为空的，当前用户权限部门下的所有事件
        List<String> deptsIndexs = new ArrayList<>();
        deptsIndexs.add(depts.getDeptsIndex());
        for (Depts i : deptsList) {
            deptsIndexs.add(i.getDeptsIndex());
        }
        if (!CollectionUtils.isEmpty(deptsIndexs)) {
            List<Supervise> temps = superviseMapper.getTransactionDataByDepts(deptsIndexs, startTime, endTime, type, progress);
            if (!CollectionUtils.isEmpty(temps)) {
                supervises.addAll(temps);
            }
        }
        //其次查出已经被当前用户处理过的事务，此时理论上，就不需要部门条件了，因为是从上线流程下来的
        String userIndex = TokenManager.getUserId();
        List<Supervise> temps = superviseMapper.getTransactionDataByUserIndex(userIndex, startTime, endTime, type, progress);
        if (!CollectionUtils.isEmpty(temps)) {
            supervises.addAll(temps);
        }
        //查询到所有数据后，计算下事务当前状态持续的天数，以及时间格式
        if(!CollectionUtils.isEmpty(supervises)){
            for (Supervise supervise:supervises) {
                    supervise.setCreateTimeStr(PubUtils.date2String(supervise.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                    if(null!=supervise.getModifyTime()){
                        supervise.setModifyTimeStr(PubUtils.date2String(supervise.getModifyTime(),"yyyy-MM-dd HH:mm:ss"));
                    }else{
                        supervise.setModifyTimeStr("");
                    }
                    //计算进行的时间，如果流程为0，则用创建时间，如果不是，则用修改时间，如果已完结 则显示 ‘/’
                    if(supervise.getProgress()==0){
                        supervise.setProceed(PubUtils.getDays(supervise.getCreateTime())+"");
                    }else if(supervise.getProgress()==6){
                        supervise.setProceed("/");
                    }else{
                        supervise.setProceed(PubUtils.getDays(supervise.getModifyTime())+"");
                    }
            }
        }
        indexPojo.setSuperviseList(supervises);


        List<Supervise> allSupervises = new ArrayList<>();
        if (!CollectionUtils.isEmpty(deptsIndexs)) {
            List<Supervise> tempsSupervise = superviseMapper.getTransactionDataByDepts(deptsIndexs, startTime, endTime, 2, 7);
            if (!CollectionUtils.isEmpty(tempsSupervise)) {
                allSupervises.addAll(tempsSupervise);
            }
        }
        //其次查出已经被当前用户处理过的事务，此时理论上，就不需要部门条件了，因为是从上线流程下来的
        List<Supervise> tempsSupervise = superviseMapper.getTransactionDataByUserIndex(userIndex, startTime, endTime, 2, 7);
        if (!CollectionUtils.isEmpty(tempsSupervise)) {
            allSupervises.addAll(tempsSupervise);
        }
        //循环遍历已经查询到的列表
        TransactionType transactionType =new TransactionType();
        TransactionProgress transactionProgress =new TransactionProgress();
        for (Supervise supervise:allSupervises) {
            if(supervise.getType()==0){
                transactionType.setEarlyWarn(transactionType.getEarlyWarn()+1);
            }else{
                transactionType.setAlarm(transactionType.getAlarm()+1);
            }
            transactionType.setTotal(transactionType.getTotal()+1);

            if(supervise.getProgress()==0){
                transactionProgress.setStart(transactionProgress.getStart()+1);
            }else if(supervise.getProgress()==1){
                transactionProgress.setAlarmTicket(transactionProgress.getAlarmTicket()+1);
            }else if(supervise.getProgress()==2){
                transactionProgress.setFeedBack(transactionProgress.getFeedBack()+1);
            }else if(supervise.getProgress()==3){
                transactionProgress.setTestReport(transactionProgress.getTestReport()+1);
            }else if(supervise.getProgress()==4){
                transactionProgress.setReviseNotice(transactionProgress.getReviseNotice()+1);
            }else if(supervise.getProgress()==5){
                transactionProgress.setReviseFeedBack(transactionProgress.getReviseFeedBack()+1);
            }else if(supervise.getProgress()==6){
                transactionProgress.setFinish(transactionProgress.getFinish()+1);
            }
            transactionProgress.setTotal(transactionProgress.getTotal()+1);
        }

        indexPojo.setTransactionType(transactionType);
        indexPojo.setTransactionProgress(transactionProgress);

        return indexPojo;
    }

    /**
     * 判断是存在当前的事务
     * @param supIndex 事务索引
     */
    @Override
    public Supervise isExist(String supIndex) {
        Supervise supervise = new Supervise();
        supervise.setSupIndex(supIndex);
        supervise=superviseMapper.selectOne(supervise);
        return supervise;
    }

    /**
     * 执行完预警、告警单下载，更新状态
     */
    @Override
    public void finishEarlyWarn(Supervise supervise) throws Exception {
        excuteUpdateSupervise(supervise);
        //获取出所有子表数据，更新对应的文件地址数据
        OverRunLog overRunLog = new OverRunLog();
        overRunLog.setSupIndex(supervise.getSupIndex());
        List<OverRunLog> overRunLogs=overRunLogMapper.select(overRunLog);
        String type="alarm";
        if(supervise.getType()==0){
            type="earlyWarn";
        }
        //遍历更新
        for(int i=0;i<overRunLogs.size();i++){
            OverRunLog temp = overRunLogs.get(i);
            Line line = new Line();
            line.setLineIndex(temp.getLineIndex().longValue());
            line= lineMapper.selectOne(line);
            temp.setAlarmTicket(type+"/"+temp.getName()+ ".docx");
            Example example =new Example(OverRunLog.class);
            example.createCriteria().andEqualTo("lineIndex",temp.getLineIndex()).andEqualTo("supIndex",temp.getSupIndex());
            overRunLogMapper.updateByExample(temp,example);
        }

    }

    /**
     * 执行完整改通知单下载，更新状态
     */
    @Override
    public void finishEarlyNotice(Supervise supervise) throws Exception {
        excuteUpdateSupervise(supervise);
        //获取出所有子表数据，更新对应的文件地址数据
        OverRunLog overRunLog = new OverRunLog();
        overRunLog.setSupIndex(supervise.getSupIndex());
        List<OverRunLog> overRunLogs=overRunLogMapper.select(overRunLog);
        //遍历更新
        for(int i=0;i<overRunLogs.size();i++){
            OverRunLog temp = overRunLogs.get(i);
            Line line = new Line();
            line.setLineIndex(temp.getLineIndex().longValue());
            line= lineMapper.selectOne(line);
            temp.setReviseNotice("/notice/"+temp.getName()+ ".docx");
            Example example =new Example(OverRunLog.class);
            example.createCriteria().andEqualTo("lineIndex",temp.getLineIndex()).andEqualTo("supIndex",temp.getSupIndex());
            overRunLogMapper.updateByExample(temp,example);
        }
    }

    /**
     * 用户点击开始执行事务
     */
    @Override
    public void startDealTransaction(String supIndex) {
        Supervise supervise = new Supervise();
        supervise.setSupIndex(supIndex);
        supervise=superviseMapper.selectOne(supervise);
        excuteUpdateSupervise(supervise);
    }

    private void excuteUpdateSupervise(Supervise supervise){
        Integer progress = supervise.getProgress();
        progress=progress+1;
        supervise.setProgress(progress);
        supervise.setModifyTime(new Date());
        supervise.setModifyUser(TokenManager.getUserId());
        supervise.setUpUser(TokenManager.getUserId());
        supervise.setNextUser(TokenManager.getUserId());
        superviseMapper.updateByPrimaryKey(supervise);
    }
}
