package com.friday.custody.service.AmbersService.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.IjsxiRobotMqDao;
import com.friday.custody.dao.RpamessageDao;
import com.friday.custody.entity.IjsxiRobotMqEntity;
import com.friday.custody.entity.RpamessageEntity;
import com.friday.custody.service.AmbersService.IjsxiRobotMqService;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;


@Slf4j
@Service("ijsxiRobotMqService")
public class IjsxiRobotMqServiceImpl extends ServiceImpl<IjsxiRobotMqDao, IjsxiRobotMqEntity> implements IjsxiRobotMqService {
    private String adminId = "";
    @Autowired
    private IjsxiRobotMqDao robotMqDao;
    @Autowired
    private RpamessageDao rpamessageDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<IjsxiRobotMqEntity> page = this.page(
                new Query<IjsxiRobotMqEntity>().getPage(params),
                new QueryWrapper<IjsxiRobotMqEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public IjsxiRobotMqEntity selectInfoByAdmin(String admin) {
        IjsxiRobotMqEntity robotMqEntity = robotMqDao.selectInfoByAdmin(admin);
        return robotMqEntity;
    }

    @Override
    public IjsxiRobotMqEntity selectInfoByAdminNull() {
        IjsxiRobotMqEntity robotMqEntity = robotMqDao.selectInfoByAdminNull();
        return robotMqEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRobotMq(IjsxiRobotMqEntity robotMqEntity) {
        robotMqDao.insertMq(robotMqEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R getRPAResult(String type, String userId, String product, String admin, String code, String message) {
        log.info("code==="+code);
        String result = "0".equals(code)?"运行成功":"运行失败";
        // 记入日志
        RpamessageEntity rpamessageEntity = RpamessageEntity.builder()
                .id(UUID.randomUUID().toString().replace("-",""))
                .pulldate(new Date())
                .pullstatus(result)
                .procode(product)
                .usetype(type)
                .errormesg(message)
                .createdtime(new Date())
                .modifiedtime(new Date())
                .build();
        String creater = adminId;
        try {
            IjsxiRobotMqEntity runingRobotMqInfoByAdmin = null;
            if (StringUtils.isNotEmpty(admin)){
                runingRobotMqInfoByAdmin = robotMqDao.selectInfoByAdmin(admin);
            } else {
                runingRobotMqInfoByAdmin = robotMqDao.selectInfoByAdminNull();
            }
            if (null != runingRobotMqInfoByAdmin){
                creater = runingRobotMqInfoByAdmin.getUserId();
            }
        }catch (Exception e){
            log.info("===获取失败===");
        }

        try {
            rpamessageEntity.setCreater(creater);
            log.info("日志入库参数:"+ JSON.toJSONString(rpamessageEntity));
            //日志入库
            rpamessageDao.insert(rpamessageEntity);

            // 更改 机器人运行队列状态
            log.info("===更改机器人运行队列状态========{},{},{}",result,message,userId);

            // 如果是 密码错误，则把这一批次的任务都改为 运行失败密码错误
            if ("运行失败".equals(result) && StringUtils.isNotEmpty(message) && message.indexOf("登录失败") > -1){
                robotMqDao.updateRobitStatusAndResultWithLoginError(result,message,userId);
            }
            if ("运行失败".equals(result) && StringUtils.isNotEmpty(message) && message.indexOf("Ambers网页未加载") > -1){
                robotMqDao.updateRobitStatus("未启动",userId);
            } else {
                robotMqDao.updateRobitStatusAndResult(result,message,userId);
            }
        } catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return R.ok("已记录日志");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R queryPrepareRobot() {
        IjsxiRobotMqEntity robotMqEntity = robotMqDao.getPrepareRobotMqInfo();
        if (!Objects.isNull(robotMqEntity)){
            updateRobotStatus("启动中",robotMqEntity.getId());
        }
        return R.ok("获取未运行的任务列表").put("data",robotMqEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReadStatus(String status, String id) {
        robotMqDao.updateReadStatus(status,id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRobotStatus(String status, String id) {
        robotMqDao.updateRobotStatus(status,id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRuningRobotTimeOut() {
        robotMqDao.updateRunningRobotTimeOut();
    }

}