package cn.estsh.i3plus.ext.mes.pcn.apiservice.controller.base;

import cn.estsh.i3plus.ext.mes.pcn.apiservice.model.MesPictureModel;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.MesConfigService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.MesProduceSnExtService;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import jodd.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;

@RestController
@RequestMapping("/white")
@Api(tags = "白名单")
@Slf4j
public class MesWhiteController {

    @Autowired
    private MesProduceSnExtService mesProduceSnExtService;

    @Autowired
    private MesConfigService mesConfigService;

    @GetMapping("/mesPartSap/{productSn}/{organizeCode}")
    public ResultBean getPartNo(@PathVariable String productSn,@PathVariable String organizeCode){

        String partNo;
        try {
            partNo = mesProduceSnExtService.queryPartNoByProduceSn(productSn, organizeCode);
        } catch (Exception e) {
           return ResultBean.fail("查询失败").setErrorMsg(e.getMessage());
        }
        return ResultBean.success("查询成功").setResultObject(partNo);

    }

    @PostMapping("/picture")
    public ResultBean savePicture(@RequestBody MesPictureModel model){
        log.info("castle-保存图片开始 model={}", JSONObject.toJSONString(model));
        String localUrl = mesConfigService.getCfgValue(model.getOrganizeCode(), "LOCAL_PICTURE_ABS_URL");
        String fileName = localUrl+model.getFileName();
        File file = new File(fileName);
        byte[] decode = Base64.decode(model.getFile());
        OutputStream outputStream;
        try {
            outputStream = Files.newOutputStream(file.toPath());
            outputStream.write(decode);
            outputStream.close();
        } catch (IOException e) {
            log.error("保存图片出错:{}",e.getMessage());
            log.error("入参为:{}", model);
        }
       if (!StringUtils.isBlank(model.getRemoteUserName()) && !StringUtils.isBlank(model.getRemoteNginxUrl()) ){
           // 构建scp命令
           log.info("castle-保存图片开始-scp命令");
           String scpCommand = String.format("scp  %s %s@%s:%s" ,fileName, model.getRemoteUserName(), model.getRemoteNginxUrl(), localUrl);
           log.info("castle-保存图片开始-scp命令开始={}",scpCommand);

           try {
               Runtime.getRuntime().exec(scpCommand);
               log.info("castle-保存图片开始-scp命令结束={}",scpCommand);

           } catch (Exception e) {
               log.error("调用scp命令失败,请手动同步图片:{}",fileName);
           }
       }

        return ResultBean.success("查询成功");

    }

}
