package com.mobvista.apptag.controller;

import com.google.gson.JsonObject;
import com.mobvista.apptag.entity.TreeTag;
import com.mobvista.apptag.mapper.TreeTagDao;
import com.mobvista.apptag.service.TreeTagService;
import com.mobvista.apptag.utils.GsonUtil;
import com.mobvista.apptag.utils.PageUtil;
import com.mobvista.apptag.utils.PropertyUtil;
import com.mobvista.apptag.utils.Query;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangjf
 */
@Controller
@RequestMapping("/tree_tag")
public class TreeTagController {

    @Autowired
    private TreeTagService treeTagService;

    @Autowired
    private TreeTagDao treeTagDao;

    @Autowired
    ServletContext context;

    public static final Logger logger = LoggerFactory.getLogger(TreeTagController.class);

    @PostMapping("/list")
    @ResponseBody
    public PageUtil list(@RequestBody Query query) {
        List<TreeTag> tags = treeTagService.list(query);
        int total = treeTagService.count(query);
        PageUtil pageUtil = new PageUtil(tags, total);
        return pageUtil;
    }

    @GetMapping("")
    String list() {
        return "tree_tag/list";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile multipartFile) {

        String rootPath = PropertyUtil.getProperty("app_tag.path");

        if (multipartFile.isEmpty()) {
            return "上传失败，请选择文件!";
        }
        String fileName = multipartFile.getOriginalFilename();
        File dest = new File(rootPath + "/" + fileName);
        if (dest.exists()) {
            dest.delete();
        }
        try {
            multipartFile.transferTo(dest);
            logger.info("上传成功");
            treeTagDao.delete();
            if (treeTagService.writeToMysql(dest)) {
                String execId = execAZ();
                return "上传成功,execId == >> " + execId;
            }
        } catch (IOException | URISyntaxException e) {
            logger.error(e.toString(), e);
        }
        return "上传失败！";
    }

    public static String execAZ() throws URISyntaxException {

        CloseableHttpClient client = HttpClients.createDefault();
        List<BasicNameValuePair> formparams = new ArrayList<>();

        String AZ_URL = PropertyUtil.getProperty("azkaban.server.http");
        final String serverUrl = AZ_URL + "azkaban/execute";
        URIBuilder uri = new URIBuilder();
        try {
            uri = new URIBuilder(serverUrl).addParameter("projectName", "dmp_on_k8s")
                    .addParameter("flowName", "app_tree_tag");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).build();

        final HttpGet httpGet = new HttpGet(uri.build());

        String execId = "";
        CloseableHttpResponse response;
        try {
            response = client.execute(httpGet);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            JsonObject jsonObject = GsonUtil.String2JsonObject(result.toString());
            if (jsonObject.get("code").getAsInt() == 200) {
                execId = jsonObject.get("execId").getAsString();
            }
        } catch (IOException e) {
            logger.info("Execute Failed!!!");
        } finally {
            httpGet.abort();
        }

        return execId;
    }
}