package com.yizhi.application.Certificate.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.Certificate.constant.LogError;
import com.yizhi.application.Certificate.util.MyCertificateUtil;
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.ApiSeachCerticateVo;
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 com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


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

    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("/list")
    public Response list(
            @ApiParam(value = "证书标题", required = false) @RequestParam(value = "certificate_title", required = false) String certificate_title,
            @ApiParam(value = "证书类型:1为有效，0为失效", required = true) @RequestParam(value = "validityType", required = true, defaultValue = "1") String validityType,
            @ApiParam(value = "要跳转的页数", required = true) @RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数,默认:10", required = true) @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize
    ) {
        try {
            ApiSeachCerticateVo apiSeachCerticateVo = new ApiSeachCerticateVo();
            apiSeachCerticateVo.setTitle(certificate_title);
            apiSeachCerticateVo.setValidityType(validityType);
            apiSeachCerticateVo.setPageNo(pageNo);
            apiSeachCerticateVo.setPageSize(pageSize);

            RequestContext requestContext = ContextHolder.get();
            apiSeachCerticateVo.setAccountId(requestContext.getAccountId());
            apiSeachCerticateVo.setCompanyId(requestContext.getCompanyId());
            apiSeachCerticateVo.setSiteId(requestContext.getSiteId());
            Page<TrUserCertificateVo> page = certificatePcClient.list(apiSeachCerticateVo);

            HashMap<String, Integer> pageMap = new HashMap<String, Integer>();
            pageMap.put("pageNo", page.getCurrent());
            pageMap.put("pageSize", page.getSize());
            pageMap.put("pageTotal", page.getPages());
            if (page != null) {
                return Response.ok(page, pageMap);
            }
            return Response.fail(Constants.MSG_BIZ_FAIL);
        } catch (Exception e) {
            LOGGER.error(LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG, e);
            return Response.fail(Constants.MSG_BIZ_FAIL);

        }

    }

//    @GetMapping("/imageView")
//    public Response<TrUserCertificatePcVo> viewImage(
//            @ApiParam(value = "传入证书id ", required = true) @RequestParam(value = "id") Long id){
//        try{
//            RequestContext context = ContextHolder.get();
//            TrUserCertificatePcVo view = certificatePcClient.view(id, context.getAccountId());
//            return Response.ok(view);
//        }catch (Exception e){
//            return Response.fail(Constants.MSG_BIZ_FAIL);
//        }
//    }


    @GetMapping("/imageView")
    public Response<TrUserCertificateVo> 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, defaultValue = "0") @RequestParam(value = "type", required = false, defaultValue = "0") Integer type
    ) {
        try {
            RequestContext requestContext = ContextHolder.get();
            TrUserCertificateVo trUserCertificate = certificatePcClient.getCertificate(id);
            if (trUserCertificate != null) {
                trUserCertificate.setCreateByName(requestContext.getSiteName());


                trUserCertificate = getImage(trUserCertificate);
                //是否过期放在type字段0未过期 1已过期
                if (trUserCertificate.getType() != 0) {
                    if (System.currentTimeMillis() >= trUserCertificate.getEndTime().getTime()) {
                        trUserCertificate.setType(1);
                    } else {
                        trUserCertificate.setType(0);
                    }
                }
                return Response.ok(trUserCertificate);
            } else {
                TrUserCertificateVo trUserCertificate1 = certificatePcClient.view(id, requestContext.getAccountId(), projectId, type);
                trUserCertificate1.setCreateByName(requestContext.getSiteName());
                trUserCertificate1 = getImage(trUserCertificate1);

                if (null != trUserCertificate1) {
                    //是否过期放在type字段0未过期 1已过期
                    if (trUserCertificate1.getType() != 0) {
                        if (System.currentTimeMillis() >= trUserCertificate1.getEndTime().getTime()) {
                            trUserCertificate1.setType(1);
                        } else {
                            trUserCertificate1.setType(0);
                        }
                    }
                    return Response.ok(trUserCertificate1);
                }
            }
            return Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG);
        }
    }

    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();
        }

        boolean isGet = false;
        if (!StringUtils.isEmpty(trUserCertificate.getUserImage())){
            URL url = null;
            try {
                url = new URL(trUserCertificate.getUserImage());
                HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
                int fileLength=urlcon.getContentLength();
                if (fileLength == 0){
                    isGet = true;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                isGet = true;
            } catch (IOException e) {
                e.printStackTrace();
                isGet = true;

            }
        }else {
            isGet = true;
        }
        String result;
        if (isGet && !StringUtils.isEmpty(trUserCertificate.getCertificateCode())) {
            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;
    }

}
