package com.zd.forward.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.Result;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.Assert;
import com.zd.common.redis.service.RedisService;
import com.zd.common.swagger.config.Knife4jConfiguration;
import com.zd.forward.config.AlgorithmYml;
import com.zd.forward.domain.VideoRequestData;
import com.zd.forward.serivce.*;
import com.zd.system.api.domain.Algorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;


/**
 * 签到验证
 */
@Api(tags = {"签到验证:算法转发服务"})
@ApiSupport(author = Knife4jConfiguration.Author.ZP)
@RestController
@RequestMapping("/signIn/check")
public class SignInCheckController {

    Logger logger = LoggerFactory.getLogger(SignInCheckController.class);

    @Autowired
    CheckService checkService;

    @Autowired
    VideoCheckResultValidImpl videoCheckResultValid;

    @Autowired
    RedisService redisService;

    @Autowired
    SendSginAccessLogService sendSginAccessLogService;

    @Autowired
    AlgorithmYml algorithmYml;

    @Resource
    private FireImageService fireImageService;

    /**
     * 进入项验证
     *
     * @param id   进出记录ID
     * @param code 字典sub_check_in类型下的的值
     * @param file 带验证图片
     */
    @ApiOperation(value = "进入项验证")
    @PostMapping("/{code}/{id}")
    public R checkIn(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
        return checkService.checkAndCommit(code, file, id);
    }

    /**
     * 进入项验证:合并
     *
     * @param id   进出记录ID
     * @param file 带验证图片
     */
    @ApiOperation(value = "进入项验证：合并,codes格式:1,2,3")
    @PostMapping("/checkInAll")
    public R checkInAll(@ApiParam("进出记录ID") @RequestParam("id") Long id,
                        @ApiParam("图片文件") @RequestParam("file") MultipartFile file,
                        @ApiParam("实验室ID") @RequestParam("subId") Long subId) {
        return checkService.checkAndCommit(id, file, subId);
    }


    /**
     * 进入项验证:mock方法
     *
     * @param code 字典sub_check_in类型下的的值
     * @param file 带验证图片
     */
    @ApiOperation(value = "进入项验证:mock方法")
    @PostMapping("/mock/{code}/{id}")
    public R checkInMock(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
        return checkService.mockTest(code, file, id);
    }


    @ApiOperation(value = "进入项验证（测试）：必须登录权限后面加！！")
    @PostMapping("/test1")
    public R test1() {
        checkService.send("1", 100L, true, "");
        return R.ok();
    }


    @ApiOperation(value = "视频回调，code 来自字典：检查项")
    @PostMapping("/callback")
    public R callBack(@ApiParam("验证类型编码") @RequestBody VideoRequestData videoRequestData) {
        Map<Integer, AlgorithmYml.VideoCheckValid> videoAidMap = algorithmYml.getVideoAidMap();
        AlgorithmYml.VideoCheckValid algorithmCheck = Optional.ofNullable(videoAidMap.get(videoRequestData.getAid()))
                .orElseThrow(() -> new ServiceException("未配置的算法类型"));
        Assert.isTrue(videoRequestData.getStatus() == 1, "算法服务检测失败！。");
        redisService.setCacheObject("VIDEO_CID:" + videoRequestData.getCid(), Long.valueOf(videoRequestData.getCid()));
        Long subId = redisService.getCacheObject("VIDEO_CID:" + videoRequestData.getCid());
        if (subId == null) {
            logger.info("未找到CID对应的实验室");
            return R.fail("未找到CID对应的实验室");
        }
        checkService.checkVideo(algorithmCheck, videoRequestData, subId);
        return R.ok();
    }

    @ApiOperation(value = "警报回调")
    @PostMapping("/alarmCallBack")
    public Result fireCallBack(@RequestBody VideoRequestData videoRequestData) {
        Integer aid = videoRequestData.getAid();
        if (aid!=null){
            if (aid.equals(9610)){
                logger.info("=====================>测试回调了。。。{}",videoRequestData.getAlgo_name());
                checkService.sendAlarm(videoRequestData);
            }else if (aid.equals(9690)){
                checkService.playMp3();
            }
        }
        return Result.ok();
    }

    @ApiOperation(value = "语音播报")
    @PostMapping("/playMp3")
    public Result playMp3() {
        checkService.playMp3();
        return Result.ok();
    }

    @ApiOperation(value = "测试算法保存")
    @PostMapping("/algorithm/test/save")
    public R saveAlgorithmTest(@RequestBody JSONObject aa) {
        Algorithm algorithm = new Algorithm();
        algorithm.setAlgorithmResult(aa.toJSONString());
        sendSginAccessLogService.saveAlgorithmResult(algorithm);
        return R.ok(aa);
    }

    /**
     * 火焰算法验证
     * @param file 带验证图片
     */
    @ApiOperation(value = "进入项验证：合并,codes格式:1,2,3")
    @PostMapping("/checkFire")
    public R checkFire(@ApiParam("图片文件") @RequestParam("file") MultipartFile file) {
        return R.ok(fireImageService.catchImage(file));
    }
}
