package com.tzld.piaoquan.api.config;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.tzld.piaoquan.api.util.AliOssFileTool;
import com.tzld.piaoquan.api.util.PropertiesUtils;
import com.tzld.piaoquan.api.model.vo.PolicyDetailVO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author zhaoyuchun
 */
@Configuration
public class AliOssConfig {
	/** 图片服务域名 **/
	// public String picEndPoint;
	/** 对象存储域名 **/
	private static String ossEndPoint;
	/** 阿里云accesskeyId **/
	private static String accessKeyId;
	/** 过期时间，单位秒 **/
	private static long expiration;
	/** 阿里云accessKeySecret **/
	private static String accessKeySecret;
	/** 文件系统配置文件地址 **/
	public String configPath;
	private static Boolean needPress;
	private static String projectName;
	private static String videoEndPoint;
	private static String internalEndPoint;
	private static OSSClient ossClient;
	private static OSSClient priClient;
	private static OSSClient videoClient;
	private static OSSClient internalOssClient;

	private static String snapshotLocation;
	private static OSSClient ossReadOnlyClient;
	private static IAcsClient mAcsClient;

	private static DefaultAcsClient defaultAcsClient;
	public static final String PIPELINEID = "abe6a0b9b9334858913eb416974485d2";
	public static final String MTS_REGION = "cn-hangzhou";
	public static final String OSS_REGION = "oss-cn-hangzhou";
	private static PolicyDetailVO policyDetail;
	static {
		policyDetail = new PolicyDetailVO();
		policyDetail.setVersion("1");
		List<PolicyDetailVO.PolicyVO> statement = new ArrayList<PolicyDetailVO.PolicyVO>();
		PolicyDetailVO.PolicyVO policy = new PolicyDetailVO.PolicyVO();
		List<String> action = new ArrayList<String>();
		List<String> resource = new ArrayList<String>();
		action.add("oss:PutObject");
		action.add("oss:AbortMultipartUpload");
		action.add("oss:ListParts");
		action.add("oss:AbortMultipartUpload");
		action.add("oss:ListObjects");
		resource.add("*");
		policy.setEffect("Allow");
		policy.setAction(action);
		policy.setResource(resource);
		statement.add(policy);
		policyDetail.setStatement(statement);

	}


	public static OSSClient getVideoClient() {
		return videoClient;
	}

	public void setVideoClient(OSSClient videoClient) {
		AliOssConfig.videoClient = videoClient;
	}

	public static String cdnDomain;
	public static String imgDomain;
	public static String videoDomain;
	public static String uploadDomain;
	public static String lvvideoDomain;
	public static String pubBucket;
	public static String priBucket;
	public static String priEndPoint;
	public static HashMap<String, String> bucketes = new HashMap<String, String>();
	private static Logger logger = Logger.getLogger(AliOssFileTool.class);
	public static String SUFFIX = "https://";
	private String tmpStr;
	@PostConstruct
	public void init() throws Exception {
		logger.info("初始化oss参数");
		try {
			setOssEndPoint(ossEndPoint);
			setProjectName(projectName);
			setExpiration(Long.valueOf(expiration));
			setVideoEndPoint(videoEndPoint);
			setAccessKeyId(accessKeyId);
			setAccessKeySecret(accessKeySecret);
			setCdnDomain(cdnDomain);
			setImgDomain(imgDomain);
			setVideoDomain(videoDomain);
			setUploadDomain(uploadDomain);
			setInternalEndPoint(internalEndPoint);
			setPubBucket(pubBucket);
			try{
				String[] buckets = pubBucket.split(",");
				for (String bucket : buckets) {
					String[] bucketParms = bucket.split(":");
					String bucketKey = bucketParms[0];
					String bucketName = bucketParms[1];
					AliOssConfig.bucketes.put(bucketKey, bucketName);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			setPriBucket(priBucket);
			String[] buckets = priBucket.split(",");
			for (String bucket : buckets) {
				String[] bucketParms = bucket.split(":");
				String bucketKey = bucketParms[0];
				String bucketName = bucketParms[1];
				AliOssConfig.bucketes.put(bucketKey, bucketName);
			}
			setNeedPress(needPress);
			setLvvideoDomain(lvvideoDomain);
			setpriEndPoint(priEndPoint);
			setSnapshotLocation("");

			setOssClient(new OSSClient(SUFFIX + ossEndPoint, accessKeyId, accessKeySecret));
			setInternalOssClient(new OSSClient(SUFFIX + internalEndPoint, accessKeyId, accessKeySecret));
			setPriClient(new OSSClient(SUFFIX + priEndPoint, accessKeyId, accessKeySecret));
			setVideoClient(new OSSClient(SUFFIX + videoEndPoint, accessKeyId, accessKeySecret));
			DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			setDefaultAcsClient(new DefaultAcsClient(profile));
		} catch (Exception e) {
			logger.error("配置文件读取失败");
			throw e;
		}

	}
	@Value("${oss.growth.priEndPoint}")
	public void setpriEndPoint(String priEndPoint) {
		AliOssConfig.priEndPoint = priEndPoint;
	}

	public static OSSClient getOssReadOnlyClient() {
		if (AliOssConfig.ossReadOnlyClient == null) {
			ClientConfiguration conf = new ClientConfiguration();
			// 设置OSSClient允许打开的最大HTTP连接数，默认为1024个。
			conf.setMaxConnections(500);
			// 设置Socket层传输数据的超时时间，默认为50000毫秒。
			conf.setSocketTimeout(40000);
			// 设置建立连接的超时时间，默认为50000毫秒。
			conf.setConnectionTimeout(10000);
			// 设置从连接池中获取连接的超时时间（单位：毫秒），默认不超时。
			conf.setConnectionRequestTimeout(1000);
			// 设置连接空闲超时时间。超时则关闭连接，默认为60000毫秒。
			conf.setIdleConnectionTime(10000);
			// 设置失败请求重试次数，默认为3次。
			conf.setMaxErrorRetry(5);
			AliOssConfig.ossReadOnlyClient = new OSSClient(SUFFIX + getOssEndPoint(), 
					PropertiesUtils.getReadOnlyAccessKeyId(),
					PropertiesUtils.getReadOnlyAccessKeySecret(),
					conf );
		}
		return AliOssConfig.ossReadOnlyClient;
	}
	@Value("${oss.growth.internal.endPoint}")
	public void setInternalEndPoint(String internalEndPoint) {
		AliOssConfig.internalEndPoint = internalEndPoint;
	}

	public static String getInternalEndPoint() {
		return internalEndPoint;
	}
	public static String getBucket(String key) {
		String bucket = AliOssConfig.bucketes.get(key);
		if (StringUtils.isEmpty(bucket)) {
			logger.error(String.format("bucket key[%s]不存在", key));
		}
		return bucket;
	}

	public static String getSnapshotLocation() {
		return snapshotLocation;
	}

	public void setSnapshotLocation(String snapshotLocation ) {
		AliOssConfig.snapshotLocation = snapshotLocation;
	}
	
	public static String getProjectName() {
		return projectName;
	}

	@Value("${oss.growth.projectName}")
	public void setProjectName(String projectName) {
		AliOssConfig.projectName = projectName;
	}


	public static OSSClient getOssClient() {
		return ossClient;
	}

	public void setOssClient(OSSClient ossClient) {
		AliOssConfig.ossClient = ossClient;
	}

	public static OSSClient getInternalOssClient() {
		return internalOssClient;
	}

	public void setInternalOssClient(OSSClient internalOssClient) {
		AliOssConfig.internalOssClient = internalOssClient;
	}

	public static String getOssEndPoint() {
		return ossEndPoint;
	}

	@Value("${oss.growth.ossEndPoint}")
	public void setOssEndPoint(String ossEndPoint) {
		AliOssConfig.ossEndPoint = ossEndPoint;
	}

	public static String getAccessKeyId() {
		return accessKeyId;
	}
	@Value("${oss.growth.accessKey}")
	public void setAccessKeyId(String accessKeyId) {
		AliOssConfig.accessKeyId = accessKeyId;
	}



	public static String getAccessKeySecret() {
		return accessKeySecret;
	}
	@Value("${oss.growth.secretKey}")
	public void setAccessKeySecret(String accessKeySecret) {
		AliOssConfig.accessKeySecret = accessKeySecret;
	}

	public String getConfigPath() {
		return configPath;
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

	public static String getCdnDomain() {
		return cdnDomain;
	}
	@Value("${oss.growth.cdnDomain}")
	public void setCdnDomain(String cdnDomain) {
		AliOssConfig.cdnDomain = cdnDomain;
	}

	public static String getImgDomain() {
		return imgDomain;
	}

	@Value("${oss.growth.imgDomain}")
	public void setImgDomain(String imgDomain) {
		AliOssConfig.imgDomain = imgDomain;
	}
	@Value("${oss.growth.pubBucket}")
	public void setPubBucket(String pubBucket) {
		AliOssConfig.pubBucket = pubBucket;
	}
	@Value("${oss.growth.priBucket}")
	public void setPriBucket(String priBucket) {
		AliOssConfig.priBucket = priBucket;
	}

	public static HashMap<String, String> getBucketes() {
		return bucketes;
	}

	public void setBucketes(HashMap<String, String> bucketes) {
		AliOssConfig.bucketes = bucketes;
	}


	public static Boolean getNeedPress() {
		return needPress;
	}
	@Value("${oss.growth.needPress}")
	public void setNeedPress(Boolean needPress) {
		AliOssConfig.needPress = needPress;
	}

	public static String getVideoDomain() {
		return videoDomain;
	}
	@Value("${oss.growth.videoDomain}")
	public void setVideoDomain(String videoDomain) {
		AliOssConfig.videoDomain = videoDomain;
	}

	public static String getVideoEndPoint() {
		return videoEndPoint;
	}
	@Value("${oss.growth.videoEndPoint}")
	public void setVideoEndPoint(String videoEndPoint) {
		AliOssConfig.videoEndPoint = videoEndPoint;
	}


	public static long getExpiration() {
		return expiration;
	}
	@Value("${oss.growth.expiration}")
	public void setExpiration(long expiration) {
		AliOssConfig.expiration = expiration;
	}

	public static String getUploadDomain() {
		return uploadDomain;
	}
	@Value("${cdn.upload.domain}")
	public void setUploadDomain(String uploadDomain) {
		AliOssConfig.uploadDomain = uploadDomain;
	}

	public static PolicyDetailVO getPolicyDetail() {
		return policyDetail;
	}

	public void setPolicyDetail(PolicyDetailVO policyDetail) {
		AliOssConfig.policyDetail = policyDetail;
	}

	public static OSSClient getPriClient() {
		return priClient;
	}

	public void setPriClient(OSSClient priClient) {
		AliOssConfig.priClient = priClient;
	}

	public static DefaultAcsClient getDefaultAcsClient() {
		return defaultAcsClient;
	}

	public void setDefaultAcsClient(DefaultAcsClient defaultAcsClient) {
		AliOssConfig.defaultAcsClient = defaultAcsClient;
	}

	public static String getLvvideoDomain() {
		return lvvideoDomain;
	}
	@Value("${oss.growth.lvvideoDomain}")
	public void setLvvideoDomain(String lvvideoDomain) {
		AliOssConfig.lvvideoDomain = lvvideoDomain;
	}
	
	public static OSSClient getShangHaiInternalOssClient() {
		return new OSSClient(SUFFIX + "oss-cn-shanghai.aliyuncs.com", accessKeyId, accessKeySecret);
	} 
	
	public static IAcsClient getIAcsClient() {
		if (AliOssConfig.mAcsClient == null) {
			DefaultProfile profile = DefaultProfile.getProfile(getMpsRegionId(), // 地域ID
					getAccessKeyId(), // RAM账号的AccessKey ID
					getAccessKeySecret()); // RAM账号Access Key Secret
			mAcsClient = new DefaultAcsClient(profile);
		}
		return AliOssConfig.mAcsClient;
	}
	public static String getMpsRegionId() {
		return PropertiesUtils.getValue("oss.longvideo.transcode.mpsRegionId");
	}
}
