package com.xjrsoft.module.system.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.config.LicenseConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tzx
 * @Date: 2023/6/29 17:26
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/license")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/license", tags = "授权")
@AllArgsConstructor
public class LicenseController {

    private final LicenseConfig licenseConfig;

    @PostMapping("/create")
    @ApiOperation(value = "生成licence")
    @XjrLog(value = "生成licence")
    public R create() throws IOException {

        final String CREATE_URL = "http://82.157.162.230:8080/api/license/create";

        final String DOWNLOAD_URL = "http://82.157.162.230:8080/api/license/download";

        HttpRequest post = HttpUtil.createPost(CREATE_URL);
        Map<String, Object> param = new HashMap<>();

        File tempFile = FileUtil.file(getOutputDir() + StringPool.SLASH + "license.properties");

//        File tempFile = File.createTempFile(Objects.requireNonNull(StringUtils.substringBeforeLast(file.getOriginalFilename(), StringPool.COMMA)),
//                StringUtils.substringAfterLast(file.getOriginalFilename(), StringPool.COMMA));

//        FileUtil.writeBytes(file.getBytes(), tempFile);


        String stringBuilder = "companyName = " + licenseConfig.getCompanyName() + "\n" +
                "contactNumber = " + licenseConfig.getContactNumber() + "\n" +
                "loginMax = " + StrUtil.toString(licenseConfig.getLoginMax()) + "\n" +
                "startTime = " + licenseConfig.getStartTime() + "\n" +
                "endTime = " + licenseConfig.getEndTime() + "\n";

        FileUtil.writeString(stringBuilder, tempFile, StandardCharsets.UTF_8);


        param.put("file[0]", tempFile);
        param.put("name", licenseConfig.getCompanyName());
        param.put("contactNumber", licenseConfig.getContactNumber());
        param.put("datetime",licenseConfig.getStartTime()+ StringPool.COMMA +licenseConfig.getEndTime());

        post.contentType("multipart/form-data; boundary=----WebKitFormBoundarygs5FBJFB7SBEhWbX");
        post.form(param);
        HttpResponse response = post.execute();
        String body = response.body();
        JSONObject json = JSONUtil.parseObj(body);
        HttpRequest get = HttpUtil.createGet(DOWNLOAD_URL + "?file=" + json.get("data"));
        HttpResponse execute = get.execute();

        File licenseFile = FileUtil.file(getOutputDir() + StringPool.SLASH + "License.shield");

        FileUtil.writeBytes(execute.bodyBytes(), licenseFile);

        boolean _newFile = licenseFile.createNewFile();

        boolean _delete = tempFile.delete();

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment", "11111");
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return R.ok(_newFile && _delete);
    }

    /**
     * 获取生成目录 默认生成到src/main/java/com/xjrsoft/module
     *
     * @return
     */
    private String getOutputDir() {
        return System.getProperty("user.dir") + StringPool.SLASH + "src" + StringPool.SLASH + "main" + StringPool.SLASH + "resources";
    }


//    @PostMapping("/test")
//    @ApiOperation(value = "生成licence")
//    @XjrLog(value = "生成licence")
//    public ResponseEntity test(@RequestParam MultipartFile file) throws IOException {
//        HttpRequest post = HttpUtil.createPost("http://82.157.162.230:8080/api/license/create");
//        Map<String, Object> param = new HashMap<>();
//        File tempFile = File.createTempFile(Objects.requireNonNull(StringUtils.substringBeforeLast(file.getOriginalFilename(), StringPool.COMMA)),
//                StringUtils.substringAfterLast(file.getOriginalFilename(), StringPool.COMMA));
//        FileUtil.writeBytes(file.getBytes(), tempFile);
//        param.put("file[0]", tempFile);
//        param.put("name", "11111");
//        param.put("contactNumber", "1111");
//        param.put("datetime", "2023-06-29 17:55:29,2024-06-29 17:55:29");
//
//        post.contentType("multipart/form-data; boundary=----WebKitFormBoundarygs5FBJFB7SBEhWbX");
//        post.form(param);
//        HttpResponse response = post.execute();
//        String body = response.body();
//        JSONObject json = JSONUtil.parseObj(body);
//        HttpRequest get = HttpUtil.createGet("http://82.157.162.230:8080/api/license/download?file=" + json.get("data"));
//        HttpResponse execute = get.execute();
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment", "11111");
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//
//        return new ResponseEntity<byte[]>(execute.bodyBytes(), headers, HttpStatus.OK);
//    }
}
