package cn.com.ctop.toutiao.modules.tool.controller;

import cn.com.ctop.common.module.utils.ParseInstallPackageUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/ctop/queryTool")
public class ParseInstallPackageController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/parseInstallPackage")
    public Result<Map<String,String>> installPackageParse(@RequestParam String installUrl,
                                                          @RequestParam String appType) {
        Result<Map<String, String>> result = new Result<>();
        //在此不需要判断安装包类型拼接后缀
        String installPath="C:\\Users\\Arc\\Desktop\\install"+System.currentTimeMillis();
        //String installPath="/data/webpackage/install"+System.currentTimeMillis();
        byte[] bytes = restTemplate.postForObject(installUrl, null, byte[].class);
        if (null == bytes || bytes.length == 0) {
            result.error500("请输入正确的下载链接");
        } else {
            File file = new File(installPath);
            OutputStream outputStream = null;
            try {
                    outputStream = new FileOutputStream(file, true);
                    outputStream.write(bytes);
                    outputStream.flush();
            } catch (IOException e) {
                log.error("下载安装包失败>>>ParseInstallPackageController"+e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
            Map<String, String> packageInfo=new HashMap<>();
            if("APP_ANDROID".equals(appType)){
                packageInfo=ParseInstallPackageUtil.parseAPK(installPath);
            }else if("APP_IOS".equals(appType)){
                packageInfo=ParseInstallPackageUtil.parseIpa(installPath);
            }
            if(packageInfo.isEmpty()){
                result.error500("请选择正确的安装包类型");
            }else {
                result.setSuccess(true);
                result.setResult(packageInfo);
            }
        }
        return result;
    }
}
