package com.friday.custody.controller;

import com.friday.custody.service.AmbersService.AmService;
import com.friday.custody.service.AmbersService.IjsxiRobotMqService;
import com.friday.custody.aop.AccessLimit;
import com.friday.custody.dao.ChanpinquanjingDao;
import com.friday.custody.entity.IjsxiRobotMqEntity;
import com.friday.custody.utils.R;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/custody/ambers")
@Slf4j
@EnableScheduling
public class AmbersController {
    private String adminId="2c9280a26706a73a016706a93ccf002b";

    @Autowired
    private AmService amService;
    @Autowired
    private IjsxiRobotMqService robotMqService;
    @Autowired
    private ChanpinquanjingDao chanpinquanjingDao;
    /**
     * 资讯数据查询
     */
    @PostMapping("/queryZXFundIdAndName")
    @AccessLimit
    public R queryPublicData(@RequestParam(value = "adminId", required = false) String adminId) {
        if(scheduleTask){
            R r = amService.queryFundIdAndName(adminId);
            return r;
        }
        return R.ok();
    }


    /***
     * 功能描述: 上传产品全景数据
     *
     * @Param: [data]
     * @Return: com.authine.cloudpivot.web.api.view.ResponseResult
     * @Author: K0051721
     * @Date: 2022/09/22 15:40
     */
    @PostMapping("/pullProductPanoramaData")
    @ApiOperation(value = "上传产品全景数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data",value = "数据", required = false, paramType = "query"),
            @ApiImplicitParam(name = "admin",value = "租户", required = false, paramType = "query"),
    })
    public R pullProductPanoramaData(String data, String admin) {
        String id = null;
        log.info("data===={},admin==={}",data,admin);

        if (StringUtils.isEmpty(data)||"{}".equals(data)){
            return R.error("传入数据为空！！！");
        }
        String creater = adminId;
        try {
            IjsxiRobotMqEntity robotMqEntity = null;
            if (StringUtils.isNotEmpty(admin)){
                robotMqEntity = robotMqService.selectInfoByAdmin(admin);
            } else {
                robotMqEntity = robotMqService.selectInfoByAdminNull();
            }

            if (null != robotMqEntity){
                creater = robotMqEntity.getUserId();
            }
            R r = amService.saveAmbersData(data, admin, creater);
            return r;
        }catch (Exception e){
            log.info("===获取失败===");
        }
        return R.error("获取失败");
    }

    /***
     * 功能描述: 上传产品全景附件
     *
     * @Param: [file, companyExt, productId, attmfield]
     * @Return: com.authine.cloudpivot.web.api.view.ResponseResult
     * @Author: K0051721
     * @Date: 2022/4/27 15:39
     */
    @PostMapping("/pullProductPanoramaAttm")
    @ApiOperation(value = "上传产品全景附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath",value = "文件路径", required = false, paramType = "query"),
            @ApiImplicitParam(name = "fileName",value = "文件名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "admin",value = "租户", required = false, paramType = "query"),
            @ApiImplicitParam(name = "productId",value = "基金编码", required = false, paramType = "query"),
            @ApiImplicitParam(name = "attmfield",value = "附件", required = false, paramType = "query"),
    })
    public R pullProductPanoramaAttm(String filePath, String fileName, String admin, String productId, String attmfield) {
        log.info("filePath===={},admin==={},productId=={},attmfield==={},fileName=={}", filePath, admin, productId, attmfield, fileName);
        if (StringUtils.isBlank(filePath) || StringUtils.isBlank(fileName) || StringUtils.isBlank(productId)) {
            return R.error("无文件上传");
        }
        R r = amService.upLoadFile(filePath,fileName,admin,productId,attmfield);
        return R.ok("下载产品全景附件成功");
    }

    /**
     * 新建 队列数据
     * @param type
     * @param userId
     * @param productCode
     * @param admin
     * @param userName
     * @param passWord
     * @param redirectUrl
     * @return
     */
    @GetMapping("/sendProductRequest")
    public R sendProductRequest(String type, String userId, String productCode, String admin, String userName, String passWord, String redirectUrl, Boolean ifAttm, String batch){
        log.info("admin={}.productCode={}=====加入队列",admin,productCode);

        if (null==ifAttm){
            ifAttm = false;
        }
        IjsxiRobotMqEntity robotMqEntity = IjsxiRobotMqEntity.builder()
                .id(UUID.randomUUID().toString().replace("-",""))
                .admin(admin)
                .type(type)
                .creater(userId)
                .userId(userId)
                .productCode(productCode)
                .userName(userName)
                .passWord(passWord)
                .redirectUrl(redirectUrl)
                .robitStatus("未启动")
                .ifAttm(ifAttm?1:0)
                .batch(batch)
                .build();
        robotMqService.addRobotMq(robotMqEntity);
        return R.ok("加入队列");
    }

    /***
     * 功能描述: rpa启动返回
     *
     * @Param: [type, userId, product, admin, code, message]
     * @Return: com.authine.cloudpivot.web.api.view.ResponseResult
     * @Author: zhengyj
     * @Date: 2022/5/11 15:49
     */
    @GetMapping("/returnProductResult")
    @ApiOperation(value = "rpa启动返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type",value = "类型", required = false, paramType = "query"),
            @ApiImplicitParam(name = "userId",value = "用户id", required = false, paramType = "query"),
            @ApiImplicitParam(name = "admin",value = "租户", required = false, paramType = "query"),
            @ApiImplicitParam(name = "product",value = "基金编码", required = false, paramType = "query"),
            @ApiImplicitParam(name = "code",value = "返回码", required = false, paramType = "query"),
            @ApiImplicitParam(name = "message",value = "返回信息", required = false, paramType = "query"),
    })
    public R returnProductResult(String type, String userId, String product, String admin, String code, String message) {
        log.info("type===={},userId==={},product=={},admin==={},code=={},message=={}",type,userId,product,admin,code,message);
        R r = robotMqService.getRPAResult(type,userId,product,admin,code,message);
        return R.ok("已记录日志");
    }

    /**
     * 获取未运行的机器人队列
     * @return
     */
    @ApiOperation(value = "获取未运行的机器人队列")
    @GetMapping("/getPrepareRobot")
    @Transactional(rollbackFor = Exception.class)
    public R getPrepareRobot() {
        try {
            R r = robotMqService.queryPrepareRobot();
            Object data = r.get("data");
            if(Objects.isNull(data)){
                return R.ok("无未运行队列");
            }
            return r;
        } catch (Exception e){
            log.info("无未运行队列");
        }
        return R.ok();
    }

    //@Value("${taskConfig.scheduleTask}")
    private Boolean scheduleTask = true;
    @Scheduled(cron = "0 0/10 * * * ?")
    public void doRobitTask() {
        if (scheduleTask) {
            robotMqService.updateRuningRobotTimeOut();
        }
    }

    /**
     * 机器人消息已读状态
     * @param id
     * @return
     */
    @GetMapping("/updateRobotResult")
    public R updateRobotResult(String id) {
        robotMqService.updateReadStatus("已读",id);
        return R.ok("ok");
    }

    /**
     * 机器人消息 运行中 状态
     * @param id
     * @return
     */
    @GetMapping("/updateRobotStatusRunning")
    public R updateRobotStatusRunning(String id) {
        robotMqService.updateRobotStatus("启动中",id);
        return R.ok("ok");
    }


}
