package com.qxgmat.help;

import com.qxgmat.data.constants.SessionKey;
import com.qxgmat.dto.response.UploadInfoDto;
import com.qxgmat.dto.SmsSessionDto;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.third.aliyuncs.Aliyun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

import static com.nuliji.tools.Tools.encodeBase64;
import static com.nuliji.tools.Tools.getHmacSha1;

/**
 * Created by GaoJie on 2017/11/3.
 */
@Service
public class UploadHelp {
    private static final Logger logger = LoggerFactory.getLogger(UploadHelp.class);
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static String format = "{\"expiration\":\"%s\",\"conditions\":[[\"content-length-range\",0,%d],[\"starts-with\",\"$key\",\"%s\"]]}";

    final public String UPLOAD_IMAGE = "nuliji-edu-all-files.oss-cn-beijing.aliyuncs.com";
    final public String UPLOAD_FILE = "nuliji-edu-all-image.oss-cn-beijing.aliyuncs.com";

    @Value("${third.aliyuncs.accessKeyId}")
    private String accessKeyId;

    @Value("${third.aliyuncs.accessKeySecret}")
    private String accessKeySecret;


    public UploadInfoDto authorize(String type, String module, int size){
        if(!type.equals(UPLOAD_FILE) && !type.equals(UPLOAD_IMAGE))
            throw new ParameterException("上传文件类型错误");
        UploadInfoDto dto = new UploadInfoDto();
        dto.setHost("https://"+type);
        dto.setOSSAccessKeyId(accessKeyId);
        dto.setSuccess_action_status("200");

        ZonedDateTime ldt = ZonedDateTime.now();
        dto.setKey(module + "/" + ldt.format(dtf) + "/" + UUID.randomUUID().toString());
        String policy = String.format(format,
                ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")),
                size,
                dto.getKey()
        );
        dto.setPolicy(encodeBase64(policy));
        dto.setSignature(encodeBase64(getHmacSha1(encodeBase64(policy), accessKeySecret)));
        logger.debug("{}", dto);
        return dto;
    }

    public boolean key(String mobile, String code, HttpSession session) {
        SmsSessionDto dto = (SmsSessionDto) session.getAttribute(SessionKey.SMS_KEY);
        if(dto == null){
            throw new ParameterException("手机验证码错误！");
        }
        session.removeAttribute(SessionKey.SMS_KEY);
        String originCode = dto.getCode();
        String originMobile = dto.getSendMobile();
        Date expireTime = dto.getExpireTime();
        if (originCode.equalsIgnoreCase(code) && originMobile.equalsIgnoreCase(mobile)) {
            if (new Date().getTime() > expireTime.getTime()) {
                throw new ParameterException("验证码已过期！");
            }
            return true;
        }
        return false;
    }
}
