package com.reyun.saas.mob.async;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.reyun.saas.common.framework.component.AwsS3Component;
import com.reyun.saas.mob.user.dao.AppMapper;
import com.reyun.saas.mob.user.domain.App;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;

@Component
@Slf4j
public class AsyncTask {

    @Resource
    private AppMapper appMapper;
    @Value("${user.dir}")
    private String tempFilePath;
    @Autowired
    private AwsS3Component awsS3Component;

    @Async
    public void getAppIcon(App app){
        File file = null;
        FileInputStream fileInputStream = null;
        String iconNetUrl = null;
        try {
            if(app.getOs().equals("iOS")){
                String body = Jsoup.connect("http://itunes.apple.com/lookup?bundleId="+app.getBid())
                        .header("Accept-Language", "zh-Hans-CN")
                        .header("User-Agent", "AppStore/2.0 iOS/10.0.2 model/iPhone7,2 hwp/t7000 build/14A456 (6; dt:106)")
                        .header("X-Apple-Connection-Type", "WiFi")
                        .header("X-Apple-Store-Front", "143465-19,29")
                        .timeout(14000)
                        .get().body().text();

                if(JSONUtil.isJson(body)){
                    JSONObject jsonObject = JSONUtil.parseObj(body);
                    Integer resultCount = jsonObject.getInt("resultCount");
                    if(resultCount!=null && resultCount>0){
                        iconNetUrl = jsonObject.getByPath("results[0].artworkUrl60",String.class);
                    }
                }
            }else{
                String body = Jsoup.connect("https://sj.qq.com/myapp/searchAjax.htm?kw="+app.getBid()+"&pns=&sid=")
                        .header("content-type","application/*+xml")
                        .ignoreContentType(true)
                        .timeout(14000)
                        .get().body().text();
                if(JSONUtil.isJson(body)){
                    JSONObject jsonObject = JSONUtil.parseObj(body);
                    JSONObject objJson = jsonObject.getJSONObject("obj");
                    if(objJson!=null){
                        JSONArray items = objJson.getJSONArray("items");
                        if(!CollectionUtil.isEmpty(items)){
                            for (int i = 0; i < items.size(); i++) {
                                JSONObject itemJson = items.getJSONObject(i);
                                String pkgName = itemJson.getStr("pkgName");
                                if(app.getBid().equals(pkgName)){
                                    iconNetUrl = itemJson.getByPath("appDetail.iconUrl",String.class);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if(!StringUtils.isEmpty(iconNetUrl)){
                file = HttpUtil.downloadFileFromUrl(iconNetUrl, getTempFilePath() + app.getRootParent()+File.separator+app.getAppkey()+".png");
                fileInputStream = IoUtil.toStream(file);
                String objKey = "icon/"+app.getRootParent()+"/"+app.getAppkey()+".png";
                awsS3Component.upload(objKey,fileInputStream);

                App appIcon = new App();
                appIcon.setId(app.getId());
                appIcon.setIconUrl(objKey);
                appMapper.updateByPrimaryKeySelective(appIcon);

            }
        }catch (Exception e){
            log.error("获取app图标失败:{},异常信息:{}",app.toString(),e);
        }finally {
            FileUtil.del(file);
            IoUtil.close(fileInputStream);
        }
    }

    public String getTempFilePath(){
        String path = new File(tempFilePath)+File.separator+"mob-dna-temp-file"+File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }
}