package com.ruoyi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.domain.ModelTestTask;
import com.ruoyi.mapper.ModelTestTaskMapper;
import com.ruoyi.service.StrategyModelTestTask;
import com.ruoyi.service.TestUseCaseService;
import com.ruoyi.web.response.ModelTestResponse;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional
public class StrategyModelTestTaskPending implements StrategyModelTestTask, InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private StrategyModelTestTaskContext strategyModelTestTaskContext;

    @Autowired
    private ModelTestTaskMapper modelTestTaskMapper;

    @Autowired
    private StrategyModelTestTaskNew strategyModelTestTaskNew;

    @Autowired
    private TestUseCaseService testUseCaseService;

    private static String url = "https://10.12.48.78:8090/DescribeProjectTestResult";

    @Override
    public ModelTestResponse doView(ModelTestTask modelTestTask) {
        ModelTestResponse response = strategyModelTestTaskNew.getTestScheme(modelTestTask);
        return response;
    }

    @Override
    public void doStartTest(ModelTestTask modelTestTask) {
        throw new ServiceException("不能开始一个进行中的任务", HttpStatus.ERROR);
    }

    @Override
    public void doConfirmTest(ModelTestTask modelTestTask) {
        // 查看当前任务-用例完成情况
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", modelTestTask.getTestSchemeId());
        map.put("verbose", "BASIC");
        JSONObject jsonObject = testUseCaseService.callThirdPartyInterface(url, map);
        Integer sumCount = (Integer) jsonObject.get("case_count");
        AtomicReference<Integer> currentCount = new AtomicReference<>(0);
        AtomicReference<Integer> failedCount = new AtomicReference<>(0);
        List<CaseStatistics> caseStatisticsList = jsonObject.getList("case_statistics", CaseStatistics.class);
        if (CollUtil.isNotEmpty(caseStatisticsList)) {
         caseStatisticsList.forEach(obj -> {
             if (CaseStatistics.CASE_STATUS_FAILED.equals(obj.status) || CaseStatistics.CASE_STATUS_PASSED.equals(obj.status)) {
                 currentCount.updateAndGet(v -> v + obj.getCount());
             }
             if (CaseStatistics.CASE_STATUS_FAILED.equals(obj.status)) {
                 failedCount.updateAndGet(v -> v + obj.getCount());
             }
         });
        }
        // 进行中的任务, 点击返回后, 判断当前用例完成程度, 用例都完成后状态改为待签字
        if (sumCount.equals(currentCount.get())) {
            modelTestTaskMapper.update(new ModelTestTask(),
                    new LambdaUpdateWrapper<ModelTestTask>()
                            .set(ModelTestTask::getTaskEndTime, new Date())
                            .set(ModelTestTask::getTaskStatus, ModelTestTask.TASK_STATUS_SIGNED)
                            .set(failedCount.get() > 0, ModelTestTask::getTaskResult, ModelTestTask.TASK_STATUS_REJECT)
                            .set(failedCount.get().equals(0), ModelTestTask::getTaskResult, ModelTestTask.TASK_STATUS_PASS)
                            .eq(ModelTestTask::getId, modelTestTask.getId()));
        }
    }

    @Override
    public void doSubmitTest(ModelTestTask modelTestTask, List<String> imagesUrl) {
        throw new ServiceException("不能提交一个进行中的任务", HttpStatus.ERROR);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        strategyModelTestTaskContext.putResource(ModelTestTask.TASK_STATUS_PENDING, applicationContext.getBean(this.getClass()));
    }

    /**
     * 接参DTO
     */
    @Data
    public class CaseStatistics {

        /**
         * 通过
         */
        private static final String CASE_STATUS_PASSED = "PASSED";

        /**
         * 失败
         */
        private static final String CASE_STATUS_FAILED = "FAILED";

        /**
         * 数量
         */
        private Integer count;

        /**
         * 状态
         */
        private String status;

    }
}