package com.yizhi.application.Certificate.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.yizhi.application.Certificate.constant.LogError;
import com.yizhi.certificate.application.feign.CertificateAppClient;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.feign.CertificatePcClient;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.certificate.application.vo.domain.TrUserCertificateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.domain.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.yizhi.application.Certificate.util.MyCertificateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

/**
 * 证书下载
 *
 * @author Administrator
 */

@Api(tags = "( PC端 ) 学员端证书接口", description = "certificateApp Controller")
@Controller
@RequestMapping("/api/pc/certificatePc")
public class CertificatePcDownController {

    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAInZlfTwk5fCDJ";
    private static String accessKeySecret = "UavtbFb2vUvRxiwUMLvUEelXTQtHCB";
    private static String bucketName = "fulan-test";

    private static final Logger LOGGER = LoggerFactory.getLogger(CertificatePcController.class);

    @Autowired
    private CertificatePcClient certificatePcClient;

    @Autowired
    CertificateClient certificateClient;

    @Autowired
    CertificateAppClient certificateAppClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    private OrganizationClient organizationClient;

    @GetMapping("/download")
    public void getCertificate(
            @ApiParam(value = "证书主键id", required = true) @RequestParam("id") Long id,
            @ApiParam(value = "项目主键id", required = false) @RequestParam(name = "projectId", required = false) Long projectId,
            @ApiParam(value = "活动类型", required = false) @RequestParam(name = "type", required = false, defaultValue = "0") Integer type,
            HttpServletResponse response
    ) {
        try {
            RequestContext requestContext = ContextHolder.get();
            TrUserCertificateVo trUserCertificate = certificatePcClient.getCertificate(id);
            if (trUserCertificate != null) {
                trUserCertificate.setCreateByName(requestContext.getSiteName());
                getImage(trUserCertificate);
                String userImage = trUserCertificate.getUserImage();
                boolean isOk = download(response, userImage);
                if (!isOk) {
                    String error = JSON.toJSONString(Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG));
                    writeError(response, error);
                }
            } else {
                TrUserCertificateVo trUserCertificate1 = certificatePcClient.view(id, requestContext.getAccountId(), projectId, type);
                trUserCertificate1.setCreateByName(requestContext.getSiteName());
                if (null != trUserCertificate1) {
                    getImage(trUserCertificate);
                    String userImage = trUserCertificate1.getUserImage();
                    boolean isOk = download(response, userImage);
                    if (!isOk) {
                        String error = JSON.toJSONString(Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG));
                        writeError(response, error);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = JSON.toJSONString(Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG));
            writeError(response, error);
        }
    }

    private TrUserCertificateVo getImage(TrUserCertificateVo trUserCertificate) {

        AccountVO accountVO = null;
        List<String> orgNameList = null;

        try {
            accountVO = accountClient.findById(trUserCertificate.getAccountId());

            trUserCertificate.setAccountName(accountVO.getName());
            trUserCertificate.setUserName(accountVO.getFullName());
            trUserCertificate.setCompanyName(accountVO.getCompanyName());
            certificateAppClient.updateTrUserCertificate(trUserCertificate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result;
        if (StringUtils.isEmpty(trUserCertificate.getUserImage())) {
            CertificateVo certificate = certificateClient.getCertificate(trUserCertificate.getCertificateId());
            //获取全部门集合
            orgNameList = organizationClient.getChiefOrgNames(accountVO.getOrgId(), accountVO.getCompanyId());
            if (null == orgNameList) {
                orgNameList = new ArrayList<>();
            }
            Boolean vailTemplate = null != certificate && !StringUtils.isEmpty(certificate.getTemplate());
            if (vailTemplate) {
                result = MyCertificateUtil.generatingCertificateImage(trUserCertificate, certificate.getTemplate(), accountVO, orgNameList);
            } else {
                result = MyCertificateUtil.generatingCertificateImage(trUserCertificate, "http://fulan-test.oss-cn-hangzhou.aliyuncs.com/cert.zip", accountVO, orgNameList);
            }
            if (LogError.CERTIFICATE_ANALYSIS_ERROR.equals(result)) {
                LOGGER.error("我的证书生成解析失败！");
                return trUserCertificate;
            } else {
                trUserCertificate.setUserImage(result);
                certificateAppClient.updateTrUserCertificate(trUserCertificate);
            }
        }
        return trUserCertificate;
    }

    private boolean download(HttpServletResponse response, String filePath) {
        BufferedInputStream is = null;
        BufferedOutputStream os = null;

        try {
            int len = filePath.lastIndexOf("/");
            String fileName = filePath.substring(len + 1);

            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSObject object = client.getObject(new GetObjectRequest(bucketName, fileName));
            ObjectMetadata objectMeta = object.getObjectMetadata();
            String contentType = "application/" + objectMeta.getContentType();
            String contentLength = String.valueOf(objectMeta.getContentLength());
            String contentDisposition = "attachment;filename=\"" + fileName + "\"";

            response.setContentType(contentType);
            response.setHeader("Content-Length", contentLength);
            response.setHeader("Content-disposition", contentDisposition);

            is = new BufferedInputStream(object.getObjectContent());
            os = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int bytesRead;
            while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
                os.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e1) {
            }
        }
        return true;
    }

    private void writeError(HttpServletResponse response, String error) {
        String contentType = "text/html;charset=utf-8";
        response.setContentType(contentType);

        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(error);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e1) {
            }
        }
    }
}
