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.cirs.biz.domain.*;
import com.cirs.biz.service.ITElectronComponentService;
import com.cirs.common.utils.DictUtils;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.boot.json.GsonJsonParser;
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.service.ITVerificationTaskDetailService;
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-11-03
 */
@RestController
@RequestMapping("/biz/detail")
public class TVerificationTaskDetailController extends BaseController
{
    @Autowired
    private ITVerificationTaskDetailService tVerificationTaskDetailService;

    @Autowired
    private ITElectronComponentService tElectronComponentService;//之前写在元器件接口不太方便

    private WebClient webClient = WebClient.builder()
//            .baseUrl("http://jsonplaceholder.typicode.com")
            .build();
    /**
     * 查询验证任务详情列表
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:list')")
    @GetMapping("/list")
    public TableDataInfo list(TVerificationTaskDetail tVerificationTaskDetail)
    {
        startPage();
        List<TVerificationTaskDetail> list = tVerificationTaskDetailService.selectTVerificationTaskDetailList(tVerificationTaskDetail);
        return getDataTable(list);
    }

    /**
     * 导出验证任务详情列表
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:export')")
    @Log(title = "验证任务详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody List<Long> taskids)
    {
        List<TVerificationTaskDetail> list = tVerificationTaskDetailService.selectTVerificationTaskDetailByTaskIds(taskids);
        ExcelUtil<TVerificationTaskDetail> util = new ExcelUtil<TVerificationTaskDetail>(TVerificationTaskDetail.class);
        util.exportExcel(response, list, "验证任务详情数据");
    }

    /**
     * 获取验证任务详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tVerificationTaskDetailService.selectTVerificationTaskDetailById(id));
    }

    /**
     * 新增验证任务详情
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:add')")
    @Log(title = "验证任务详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TVerificationTaskDetail tVerificationTaskDetail)
    {
        return toAjax(tVerificationTaskDetailService.insertTVerificationTaskDetail(tVerificationTaskDetail));
    }

    /**
     * 修改验证任务详情
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:edit')")
    @Log(title = "验证任务详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TVerificationTaskDetail tVerificationTaskDetail)
    {
        return toAjax(tVerificationTaskDetailService.updateTVerificationTaskDetail(tVerificationTaskDetail));
    }

    /**
     * 删除验证任务详情
     */
    @PreAuthorize("@ss.hasPermi('biz:detail:remove')")
    @Log(title = "验证任务详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tVerificationTaskDetailService.deleteTVerificationTaskDetailByIds(ids));
    }

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

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

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

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

//    @GetMapping("/componentIds/{taskid}")
    public AjaxResult getComponentIds(Long taskid)
    {

        List<TVerificationTaskDetail> dataset = tVerificationTaskDetailService.alldata(taskid);

        int idx = 0;
        for(;idx < dataset.size(); idx++){
            TVerificationTaskDetail data = dataset.get(idx);
//            System.out.println(data.getResult1());
            if(data.getResult1Id()==null){//不改动元器件id时可行
                Long component_id1 = tVerificationTaskDetailService.setComponentId(data.getResult1());
//                System.out.println(component_id1);
                Long component_id2 = tVerificationTaskDetailService.setComponentId(data.getResult2());
                Long component_id3 = tVerificationTaskDetailService.setComponentId(data.getResult3());
                Long component_id4 = tVerificationTaskDetailService.setComponentId(data.getResult4());
                Long component_id5 = tVerificationTaskDetailService.setComponentId(data.getResult5());
                data.setResult1Id(component_id1);
                data.setResult2Id(component_id2);
                data.setResult3Id(component_id3);
                data.setResult4Id(component_id4);
                data.setResult5Id(component_id5);
                edit(data);//更新数据库
            }

        }

        return success();
    }

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

        try {

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


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

            getComponentIds(taskid);
            Map<String, Object> objectMap=new HashMap<>();
            List<VerificationData> dataset = tVerificationTaskDetailService.getComponentids(taskid);//id就是taskdetail的id，由此更新相应的taskdetail
//            for(int i=0;i<dataset.size();i++){
//                dataset.get(i).setId((long)(i+1));
//            }

            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属性
//
//            GsonJsonParser jsonParser = new GsonJsonParser();
//
//            System.out.println(jsonParser.parseMap(result).get("dataSet").toString());

            // 这里后端GsonJsonParser解析json语句报错Handler dispatch failed;，所以返回到前端解析
            res.put("data",result);
            res.put("msg","任务"+taskid+"验证算法调用成功");
            res.put("code",200);
            // todo System.out.println System.out.println应该使用logger框架替换
//            System.out.println(result);
            logger.info(result);
            return res;

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

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


    public String getDetailById(Long id) {
        if(id==null) return null;
        return tElectronComponentService.getDetailById(id);
    }

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

                TVerificationTaskDetail detail = tVerificationTaskDetailService.selectTVerificationTaskDetailById(verificationData.getId());

                detail.setCalculate1Id(verificationData.getCalculate1Id());
                detail.setCalculate2Id(verificationData.getCalculate2Id());
                detail.setCalculate3Id(verificationData.getCalculate3Id());
                detail.setCalculate4Id(verificationData.getCalculate4Id());
                detail.setCalculate5Id(verificationData.getCalculate5Id());

                detail.setCalculate1(getDetailById(detail.getCalculate1Id()));
                detail.setCalculate2(getDetailById(detail.getCalculate2Id()));
                detail.setCalculate3(getDetailById(detail.getCalculate3Id()));
                detail.setCalculate4(getDetailById(detail.getCalculate4Id()));
                detail.setCalculate5(getDetailById(detail.getCalculate5Id()));

                detail.setTested(1);

                tVerificationTaskDetailService.updateTVerificationTaskDetail(detail);
            }

//            List<TVerificationTaskDetail> detaildataset = tVerificationTaskDetailService.selectTVerificationTaskDetailByTaskIds(taskids);

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

//    @PostMapping("/getUpdatedDetails")
//    public TableDataInfo getUpdatedDetails(@RequestBody List<Long> taskids){
//        try{
//            startPage();
//            return getDataTable(tVerificationTaskDetailService.selectTVerificationTaskDetailByTaskIds(taskids));
//        } catch (Exception e){
//            return null;
//        }
//
//    }
    @PostMapping("/getUpdatedDetails")
    public PageInfo<TVerificationTaskDetail> getUpdatedDetails(
            @RequestBody List<Long> taskids,
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<TVerificationTaskDetail> Page = new PageInfo<>(tVerificationTaskDetailService.selectTVerificationTaskDetailByTaskIds(taskids));
        return Page;
    }
}
