package com.cirs.biz.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.cirs.biz.domain.TVerificationTaskDetail;
import com.cirs.biz.domain.VerificationData;
import com.cirs.common.utils.DictUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cirs.common.annotation.Log;
import com.cirs.common.core.controller.BaseController;
import com.cirs.common.core.domain.AjaxResult;
import com.cirs.common.enums.BusinessType;
import com.cirs.biz.domain.TVerificationScoretaskDetail;
import com.cirs.biz.service.ITVerificationScoretaskDetailService;
import com.cirs.common.utils.poi.ExcelUtil;
import com.cirs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * 打分算法验证详情Controller
 * 
 * @author allen
 * @date 2023-12-10
 */
@RestController
@RequestMapping("/biz/scoretaskdetail")
public class TVerificationScoretaskDetailController extends BaseController
{
    @Autowired
    private ITVerificationScoretaskDetailService tVerificationScoretaskDetailService;

    private WebClient webClient = WebClient.builder()
//            .baseUrl("http://jsonplaceholder.typicode.com")
            .build();
    /**
     * 查询打分算法验证详情列表
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(TVerificationScoretaskDetail tVerificationScoretaskDetail)
    {
        startPage();
        List<TVerificationScoretaskDetail> list = tVerificationScoretaskDetailService.selectTVerificationScoretaskDetailList(tVerificationScoretaskDetail);
        return getDataTable(list);
    }

    /**
     * 导出打分算法验证详情列表
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:export')")
    @Log(title = "打分算法验证详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TVerificationScoretaskDetail tVerificationScoretaskDetail)
    {
        List<TVerificationScoretaskDetail> list = tVerificationScoretaskDetailService.selectTVerificationScoretaskDetailList(tVerificationScoretaskDetail);
        ExcelUtil<TVerificationScoretaskDetail> util = new ExcelUtil<TVerificationScoretaskDetail>(TVerificationScoretaskDetail.class);
        util.exportExcel(response, list, "打分算法验证详情数据");
    }

    /**
     * 获取打分算法验证详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tVerificationScoretaskDetailService.selectTVerificationScoretaskDetailById(id));
    }

    /**
     * 新增打分算法验证详情
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:add')")
    @Log(title = "打分算法验证详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TVerificationScoretaskDetail tVerificationScoretaskDetail)
    {
        return toAjax(tVerificationScoretaskDetailService.insertTVerificationScoretaskDetail(tVerificationScoretaskDetail));
    }

    /**
     * 修改打分算法验证详情
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:edit')")
    @Log(title = "打分算法验证详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TVerificationScoretaskDetail tVerificationScoretaskDetail)
    {
        return toAjax(tVerificationScoretaskDetailService.updateTVerificationScoretaskDetail(tVerificationScoretaskDetail));
    }

    /**
     * 删除打分算法验证详情
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:remove')")
    @Log(title = "打分算法验证详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tVerificationScoretaskDetailService.deleteTVerificationScoretaskDetailByIds(ids));
    }

    /**
     * 导入验证任务detail wangruilin
     */
    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TVerificationScoretaskDetail> util = new ExcelUtil<TVerificationScoretaskDetail>(TVerificationScoretaskDetail.class);
        List<TVerificationScoretaskDetail> taskDetailList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String fileName = file.getOriginalFilename();

        assert fileName != null;
        fileName =  fileName.substring(0, fileName.lastIndexOf("."));

        String message = tVerificationScoretaskDetailService.importTaskDetail(taskDetailList, updateSupport, operName,fileName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TVerificationScoretaskDetail> util = new ExcelUtil<TVerificationScoretaskDetail>(TVerificationScoretaskDetail.class);
        util.importTemplateExcel(response, "score任务详情数据");
    }



    @PreAuthorize("@ss.hasPermi('biz:scoretaskdetail:verification')")
    @GetMapping("/verification")
    public AjaxResult verification(Long taskid) {

        try {

            String model_path = DictUtils.getDictValue("biz_factoryScore_algorithm_config","model_path");
            String verification_uri = DictUtils.getDictValue("biz_factoryScore_algorithm_config","verification_uri");


            logger.info(taskid.toString());
//            System.out.println(taskid);


            Map<String, Object> objectMap=new HashMap<>();

            List<TVerificationScoretaskDetail> dataset = tVerificationScoretaskDetailService.getByscoretaskid(taskid);
            objectMap.put("dataSet", dataset);
            objectMap.put("modelPath", model_path);
            // 发送请求
            Mono<String> mono = webClient
                    .post() // POST 请求
                    .uri(verification_uri)  // 请求路径
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .syncBody(objectMap)
                    .retrieve() // 获取响应体
                    .bodyToMono(String.class); //响应数据类型转换

            AjaxResult res = new AjaxResult();
            String result = mono.block();//返回值有accuracyRate和recallRate属性

            res.put("data",result);
            res.put("msg","打分任务"+taskid+"验证算法调用成功");
            res.put("code",200);

//            System.out.println(result);
            logger.info(result);
            return res;
//            return success(returndata);

//            return success("任务"+taskid+"验证算法调用成功");
        } catch (Exception e) {

            return error("任务"+taskid+"验证算法调用失败");
        }
    }




    @PostMapping("/updateDetails")
    public AjaxResult updateDetails(@RequestBody List<TVerificationScoretaskDetail> dataset){
        try {
            for (TVerificationScoretaskDetail data : dataset) {

                tVerificationScoretaskDetailService.updateTVerificationScoretaskDetail(data);
            }



            return success();
        } catch (Exception e){
            return error("加载数据出错");
        }
    }

//    @PostMapping("/getUpdatedDetails")
//    public TableDataInfo getUpdatedDetails(@RequestBody List<Long> taskids){
////        try{
//            startPage();
//            return getDataTable(tVerificationScoretaskDetailService.selectTVerificationScoreaskDetailByTaskIds(taskids));
////        } catch (Exception e){
////            return null;
////        }
//
//    }

    @PostMapping("/getUpdatedDetails")
    public PageInfo<TVerificationScoretaskDetail> getUpdatedDetails(
            @RequestBody List<Long> taskids,
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<TVerificationScoretaskDetail> Page = new PageInfo<>(tVerificationScoretaskDetailService.selectTVerificationScoreaskDetailByTaskIds(taskids));
        return Page;
    }
}
