package com.css.simulation.resource.server.adapter.controller.scene_library.general;

import api.common.pojo.common.ResponseBodyVO;
import api.common.pojo.constants.DictConstants;
import api.common.pojo.constants.LogConstants;
import api.common.pojo.param.scene.SceneGeneralTemplateParam;
import api.common.pojo.po.scene.SceneGeneralExamplePO;
import api.common.pojo.po.scene.SceneGeneralTemplatePO;
import api.common.pojo.po.system.SceneImportPO;
import api.common.pojo.vo.scene.SceneGeneralTemplateVO;
import api.common.util.ObjectUtil;
import api.common.util.StringUtil;
import api.common.util.TimeUtil;
import com.css.simulation.resource.server.app.service.*;
import com.css.simulation.resource.server.infra.util.PageUtil;
import com.css.simulation.resource.server.infra.feign.service.FileDownService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//泛化场景
@RestController
@RequestMapping("/SceneGeneralTemplate")
public class SceneGeneralController {

    @Resource
    private SceneGeneralTemplateService sceneGeneralTemplateService;
    @Resource
    private SceneGeneralExampleService exampleService;
    @Resource
    private FileDownService fileDownService;
    @Resource
    private SceneImportService sceneImportService;
    @Resource
    private LogService logService;
    @Resource
    private DictService dictService;

    //查询列表
    @PostMapping("/querySceneGeneralTemplateList")
    public ResponseBodyVO<PageInfo<SceneGeneralTemplatePO>> querySceneGeneralTemplateList(@RequestBody SceneGeneralTemplateParam po) {
        PageUtil.setPageInfo(po);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, new PageInfo<>(sceneGeneralTemplateService.querySceneGeneralTemplateList(po)));
    }

    //查模板详情
    @PostMapping("/querySceneGeneralTemplateById")
    public ResponseBodyVO<SceneGeneralTemplateVO> querySceneGeneralTemplateById(@RequestBody SceneGeneralTemplateParam param) {
        if (param != null && ObjectUtil.isNotNull(param.getId())) {
            SceneGeneralTemplateVO po = sceneGeneralTemplateService.querySceneGeneralTemplateById(param.getId());
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, po);
        }
        return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "参数id不能为空，请检查");

    }

    //新增泛化模板 带任务的
    @PostMapping("/saveSceneGeneralTemplateNew")
    public ResponseBodyVO<String> saveSceneGeneralTemplateNew(@RequestParam("file") MultipartFile multipartFile, @RequestBody SceneImportPO sceneImportPO) {
        File file;
        String originalFilename = multipartFile.getOriginalFilename();
        if (StringUtil.isEmpty(originalFilename)) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE);
        }
        if (!originalFilename.contains(".xls") && !originalFilename.contains(".xlsx")) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "文件格式错误，请检查模板.");
        }
        //版本号
        String version = TimeUtil.getToStringDate(new Date(), 5);
        SceneImportPO sceneImportPO1 = sceneImportService.saveTask(sceneImportPO);
        try {
            // Integer nowTime = TimeUtil.getRq(new Date(), 0);
            String fileName = "泛化场景/" + version + "/" + originalFilename;
            fileDownService.upload(multipartFile, fileName);
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "模板解析失败，请检查模板.");

        }
        sceneImportPO1.setStatus(DictConstants.SCENE_IMPORT_STATUS_2);
        sceneImportService.updateStatus(sceneImportPO1);
        sceneImportPO = sceneGeneralTemplateService.saveSceneGeneralTemplateNew(file, version, sceneImportPO);
        sceneImportService.updateStatus(sceneImportPO);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);

    }

    //新增泛化模板
    @PostMapping("/saveSceneGeneralTemplate")
    public ResponseBodyVO<String> saveSceneGeneralTemplate(@RequestParam("file") MultipartFile multipartFile) {
        File file;
        String originalFilename = multipartFile.getOriginalFilename();
        if (!originalFilename.contains(".xls") && !originalFilename.contains(".xlsx")) {
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "文件格式错误，请检查模板.");

        }
        //版本号
        String version = TimeUtil.getToStringDate(new Date(), 5);
        try {
            // Integer nowTime = TimeUtil.getRq(new Date(), 0);
            String fileName = "泛化场景/" + version + "/" + originalFilename;
            fileDownService.upload(multipartFile, fileName);
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "模板解析失败，请检查模板.");

        }

        sceneGeneralTemplateService.saveSceneGeneralTemplate(file, version);

        return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);

    }


    //删除泛化模板
    @PostMapping("/deleteSceneGeneralTemplateById")
    public ResponseBodyVO<String> deleteSceneGeneralTemplateById(@RequestBody SceneGeneralTemplatePO po) {
        sceneGeneralTemplateService.deleteSceneGeneralTemplateById(po);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);

    }

    //批量删除泛化模板
    @PostMapping("/deleteSceneGeneralTemplateByIds")
    public ResponseBodyVO<String> deleteSceneGeneralTemplateByIds(@RequestBody SceneGeneralTemplateParam params) {
        List<String> fhNameList = params.getFhNameList();
        SceneGeneralTemplatePO po = new SceneGeneralTemplatePO();
        for (String fhName : fhNameList) {
            po.setSceneId(fhName);
            sceneGeneralTemplateService.deleteSceneGeneralTemplateById(po);
        }
        return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);
    }

    //查看泛化实例详情页面

    @PostMapping("/queryGeneralTemplateByFh")
    public ResponseBodyVO queryGeneralTemplateByFh(@RequestBody SceneGeneralExamplePO param) {
        if (param != null && ObjectUtil.isNotNull(param.getId())) {
            return exampleService.querySceneGeneralExampleById(param.getId());
        }
        return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "参数id不能为空，请检查");
    }


    /**
     * 调用外部接口生成泛化数据
     */
    @PostMapping("/saveSceneGeneralExample")
    public ResponseBodyVO<Map<String, String>> saveSceneGeneralExample(@RequestBody SceneGeneralTemplateVO vo) {
        return exampleService.saveSceneGeneralExample(vo);
    }

    //查询模块名称
    @PostMapping("/queryType")
    public ResponseBodyVO queryType() {
        return exampleService.queryType();
    }


   /* //测试
    @PostMapping("/test1")
    public ResponseBodyVO test1(@RequestBody SceneGeneralTemplatePO po) throws IllegalAccessException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        Map map = beanToMap(po);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(6 * 10 * 1000)
                .setConnectTimeout(6 * 10 * 1000)
                .setConnectionRequestTimeout(6 * 10 * 1000)
                .setRedirectsEnabled(false)
                .setExpectContinueEnabled(false)
                .build();

        String post = HttpUtil.post(HttpUtil.getHttpClient(), requestConfig, "http://47.94.105.148:5000/test_1.0", null, map);
        JsonNode params = JsonUtil.readTree(post).get("params");
        // 实例化 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
        String newjson = objectMapper.writeValueAsString(params);
        List<SceneGeneralDataPO> list = JsonUtil.jsonToList(newjson, SceneGeneralDataPO.class);
        return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "参数不能为空，请检查");
    }
*/

    /**
     * 对象转Map
     */
    public static Map beanToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
        return map;
    }


    //新增泛化模板  现在
    @PostMapping("/saveSceneGeneralTemplateAll")
    public ResponseBodyVO<String> saveSceneGeneralTemplateAll(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {

        SceneImportPO sceneImportPO = new SceneImportPO();
        //获取文件类型
        String taskName = request.getParameter("taskName");
        sceneImportPO.setName(taskName);
        sceneImportPO.setSceneType("4");
        sceneImportPO = sceneImportService.saveTask(sceneImportPO);
        //记录日志
        Map<String, String> mapType = dictService.getDictMapByType(DictConstants.SCENE_TYPE);
        String type = mapType.get(DictConstants.SCENE_GENERAL);
        String content = "创建" + type + "上传任务:" + sceneImportPO.getName() + "(ID:" + sceneImportPO.getId() + ")";
        logService.logSceneUpload(LogConstants.SYS_LOG_SCENE_TASK_INSERT, content);


        sceneImportPO.setStatus(DictConstants.SCENE_IMPORT_STATUS_2);

        File file = null;
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename.indexOf(".xls") == -1 && originalFilename.indexOf(".xlsx") == -1) {
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "文件格式错误，请检查模板.");

        }
        //版本号
        String version = TimeUtil.getToStringDate(new Date(), 5);
        try {
            ResponseBodyVO<String> respon;
            // Integer nowTime = TimeUtil.getRq(new Date(), 0);
            String fileName = "泛化场景/" + version + "/" + originalFilename;
            respon = fileDownService.upload(multipartFile, fileName);

            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
            sceneImportPO.setDataDirectory(fileName);
            sceneImportService.update(sceneImportPO);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "模板解析失败，请检查模板.");

        }

        sceneImportPO = sceneGeneralTemplateService.saveSceneGeneralTemplateNew(file, version, sceneImportPO);
        sceneImportService.updateInfo(sceneImportPO);
        return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);

    }

    //分享·
    @PostMapping("/instShareSceneGeneralTemplate")
    public ResponseBodyVO<String> instShareSceneGeneralTemplate(@RequestBody SceneGeneralTemplatePO po) {
        sceneGeneralTemplateService.instShareSceneGeneralTemplate(po);
        return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);

    }


}
