package com.jianshui.web.controller.breaker;

import cn.hutool.core.io.FileUtil;
import com.jianshui.breaker.jianshuiy.domain.dto.JianShuiLicenseDTO;
import com.jianshui.common.config.JianshuiConfig;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.utils.file.FileUploadUtils;
import com.jianshui.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

import static com.jianshui.breaker.jianshuiy.Breaker.buildLicense;

/**
 * @Description
 * @Author 巩权林
 * @Date 2022/10/8 09:55
 **/
@RestController
@RequestMapping("/breaker")
public class BreakerController {

    @Autowired
    private ServerConfig serverConfig;

    @PostMapping("/jianShuiLicense")
    public AjaxResult jianShuiLicense(HttpServletResponse response, @RequestBody JianShuiLicenseDTO jianShuiLicenseDTO) throws IOException {
        String license = buildLicense(jianShuiLicenseDTO.getSellerName(), jianShuiLicenseDTO.getSellerTaxno(), new Date(), jianShuiLicenseDTO.getEndDate(), jianShuiLicenseDTO.getMachineNo());
        String filename = "BZ" + jianShuiLicenseDTO.getSellerTaxno() + ".Render";
        String uploadPath = JianshuiConfig.getUploadPath();
        String filePath = uploadPath + "/" + filename;
        FileUtil.writeBytes(license.getBytes("GBK"), filePath);
        String uri = FileUploadUtils.getPathFileName(uploadPath, filename);
        String url = serverConfig.getUrl() + uri;
        return AjaxResult.success("success", url);
        // ServletOutputStream out = response.getOutputStream();
        // byte[] licenseBytes = license.getBytes("GBK");
        // InputStream inputStream = new ByteArrayInputStream(licenseBytes);
        // try {
        //     int bytes = 0;
        //     byte[] buffer = new byte[1024];
        //     while ((bytes = inputStream.read(buffer)) != -1) {
        //         out.write(buffer, 0, bytes);
        //     }
        // } finally {
        //     out.close();
        //     inputStream.close();
        // }

    }
}
