package com.cirs.biz.controller;

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

import com.cirs.common.utils.DictUtils;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.FactoryScore;
import com.cirs.biz.service.IFactoryScoreService;
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/score")
public class FactoryScoreController extends BaseController
{
    @Autowired
    private IFactoryScoreService factoryScoreService;

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

    /**
     * 查询厂家得分列表
     */
    @PreAuthorize("@ss.hasPermi('biz:score:list')")
    @GetMapping("/list")
    public TableDataInfo list(FactoryScore factoryScore)
    {
        startPage();
        List<FactoryScore> list = factoryScoreService.selectFactoryScoreList(factoryScore);
        return getDataTable(list);
    }

    /**
     * 导出厂家得分列表
     */
    @PreAuthorize("@ss.hasPermi('biz:score:export')")
    @Log(title = "厂家得分", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FactoryScore factoryScore)
    {
        List<FactoryScore> list = factoryScoreService.selectFactoryScoreList(factoryScore);
        ExcelUtil<FactoryScore> util = new ExcelUtil<FactoryScore>(FactoryScore.class);
        util.exportExcel(response, list, "厂家得分数据");
    }

    /**
     * 获取厂家得分详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:score:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(factoryScoreService.selectFactoryScoreById(id));
    }

    /**
     * 新增厂家得分
     */
    @PreAuthorize("@ss.hasPermi('biz:score:add')")
    @Log(title = "厂家得分", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FactoryScore factoryScore)
    {
        return toAjax(factoryScoreService.insertFactoryScore(factoryScore));
    }

    /**
     * 修改厂家得分
     */
    @PreAuthorize("@ss.hasPermi('biz:score:edit')")
    @Log(title = "厂家得分", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FactoryScore factoryScore)
    {
        return toAjax(factoryScoreService.updateFactoryScore(factoryScore));
    }

    /**
     * 删除厂家得分
     */
    @PreAuthorize("@ss.hasPermi('biz:score:remove')")
    @Log(title = "厂家得分", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(factoryScoreService.deleteFactoryScoreByIds(ids));
    }

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

        String operName = getUsername();
        String message = factoryScoreService.importTrain(scoreList, updateSupport, operName);
        return success(message);
    }

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

    @PreAuthorize("@ss.hasPermi('biz:score:train')")
    @GetMapping("/train")
    public AjaxResult train() {
        try {

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

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

            objectMap.put("dataSet", factoryScoreService.selectFactoryScoreList(new FactoryScore()));

            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:score:marking')")
    @PostMapping ("/marking")
    public AjaxResult recommend(@RequestBody FactoryScore args) {
        try {
            String model_path = DictUtils.getDictValue("biz_factoryScore_algorithm_config","model_path");
            String marking_uri = DictUtils.getDictValue("biz_factoryScore_algorithm_config","marking_uri");

            Map<String, Object> objectMap=new HashMap<>();
            objectMap.put("data", args);
            objectMap.put("modelPath", model_path);

            //接下来就传入算法
//            System.out.println(JSON.toJSONString(objectMap));
            // todo wangruilin uri 应该是一个全地址+端口，这个地址可以通过数据字典配置和获取
            Mono<String> mono = webClient
                    .post() // POST 请求
                    .uri(marking_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("msg","成功");
            result.put("data",res);
            result.put("code",200);
            return result;
        } catch (Exception e) {

            return error("打分失败！");
        }
    }


}
