package com.cirs.biz.controller;

import com.cirs.biz.domain.VerificationData;
import com.cirs.common.utils.DictUtils;
import org.springframework.http.HttpMethod;


import java.io.File;
import java.sql.Timestamp;
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.JSONObject;
import com.cirs.biz.domain.TElectronComponent;
import com.cirs.biz.domain.TrainReturn;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration;
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.SysTrain;
import com.cirs.biz.service.ISysTrainService;
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.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * 训练集数据列Controller
 * 
 * @author allen
 * @date 2023-11-28
 */
@RestController
@RequestMapping("/biz/train")
public class SysTrainController extends BaseController
{

    @Autowired
    private ISysTrainService sysTrainService;

    // 创建 WebClient 对象
    private WebClient webClient = WebClient.builder()
//            .baseUrl("http://jsonplaceholder.typicode.com")
            .build();



    /**
     * 查询训练集数据列列表
     */
    @PreAuthorize("@ss.hasPermi('biz:train:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysTrain sysTrain)
    {
        startPage();
        List<SysTrain> list = sysTrainService.selectSysTrainList(sysTrain);
        return getDataTable(list);
    }

    /**
     * 导出训练集数据列列表
     */
    @PreAuthorize("@ss.hasPermi('biz:train:export')")
    @Log(title = "训练集数据列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTrain sysTrain)
    {
        List<SysTrain> list = sysTrainService.selectSysTrainList(sysTrain);
        ExcelUtil<SysTrain> util = new ExcelUtil<SysTrain>(SysTrain.class);
        util.exportExcel(response, list, "训练集数据列数据");
    }

    /**
     * 获取训练集数据列详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:train:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysTrainService.selectSysTrainById(id));
    }

    /**
     * 新增训练集数据列
     */
    @PreAuthorize("@ss.hasPermi('biz:train:add')")
    @Log(title = "训练集数据列", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysTrain sysTrain)
    {
        return toAjax(sysTrainService.insertSysTrain(sysTrain));
    }

    /**
     * 修改训练集数据列
     */
    @PreAuthorize("@ss.hasPermi('biz:train:edit')")
    @Log(title = "训练集数据列", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysTrain sysTrain)
    {
        return toAjax(sysTrainService.updateSysTrain(sysTrain));
    }

    /**
     * 删除训练集数据列
     */
    @PreAuthorize("@ss.hasPermi('biz:train:remove')")
    @Log(title = "训练集数据列", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysTrainService.deleteSysTrainByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('biz:train:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysTrain> util = new ExcelUtil<SysTrain>(SysTrain.class);
        List<SysTrain> trainList = util.importExcel(file.getInputStream());

        String operName = getUsername();
        String message = sysTrainService.importTrain(trainList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysTrain> util = new ExcelUtil<SysTrain>(SysTrain.class);
        util.importTemplateExcel(response, "训练集数据");
    }


    @GetMapping("/componentIds")
    public AjaxResult getComponentIds()
    {
        List<SysTrain> train_dataset = sysTrainService.alldata();
        int idx = 0;
        for(;idx < train_dataset.size(); idx++){
            SysTrain data = train_dataset.get(idx);

            if(data.getResult1Id()==null){//不改动元器件id时可行
                Long component_id1 = sysTrainService.getComponentId(data.getResult1());
                Long component_id2 = sysTrainService.getComponentId(data.getResult2());
                Long component_id3 = sysTrainService.getComponentId(data.getResult3());
                Long component_id4 = sysTrainService.getComponentId(data.getResult4());
                Long component_id5 = sysTrainService.getComponentId(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:train:train')")
    @GetMapping("/train")
    public AjaxResult train() {
        try {

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

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

            objectMap.put("dataSet", sysTrainService.getComponentids());

            objectMap.put("modelPath", model_path);
            // 发送请求
            // todo wangruilin uri 应该是一个全地址+端口，这个地址可以通过数据字典配置和获取
            Mono<String> mono = webClient
                    .post() // POST 请求
                    .uri(train_uri)  // 请求路径
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .syncBody(objectMap)
                    .retrieve() // 获取响应体
                    .bodyToMono(String.class); //响应数据类型转换


            mono.subscribe(result -> {
                logger.info(result);

            });
            //接下来就传入算法即可
//            System.out.println(JSON.toJSONString(objectMap));

            return success("训练成功");
        } catch (Exception e) {

            return error("训练失败");
        }
    }

    @PreAuthorize("@ss.hasPermi('biz:train:recommend')")
    @PostMapping ("/recommend")
    public AjaxResult recommend(@RequestBody TrainReturn recommend_args) {
        try {

            String recommend_uri = DictUtils.getDictValue("biz_algorithm_config","recommend_uri");

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

            Map<String, Object> objectMap=new HashMap<>();
            objectMap.put("useScene", recommend_args.getUseScene());
            objectMap.put("SearchCondition",recommend_args.getSearchCondition());
            objectMap.put("modelPath", model_path);
            objectMap.put("result1Id",recommend_args.getResult1Id());
            objectMap.put("result2Id",recommend_args.getResult2Id());
            objectMap.put("result3Id",recommend_args.getResult3Id());
            objectMap.put("result4Id",recommend_args.getResult4Id());
            objectMap.put("result5Id",recommend_args.getResult5Id());
            //接下来就传入算法
//            System.out.println(JSON.toJSONString(objectMap));
            // todo wangruilin uri 应该是一个全地址+端口，这个地址可以通过数据字典配置和获取
            Mono<String> mono = webClient
                    .post() // POST 请求
                    .uri(recommend_uri)  // 请求路径
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .syncBody(objectMap)
                    .retrieve() // 获取响应体
                    .bodyToMono(String.class); //响应数据类型转换

                String res = mono.block();
                // // todo wangruilin 改成logger
                logger.info(res);
            AjaxResult result = new AjaxResult();
            result.put("data",res);
            result.put("code",200);
            return result;
        } catch (Exception e) {

            return error("推荐元器件失败");
        }
    }

    @GetMapping("/getTraindataset")
    public TableDataInfo getTraindataset(){
        try{
            startPage();
            return getDataTable(sysTrainService.alldata());
        } catch (Exception e){
            return null;
        }
    }
}
