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.vo.ApiSeachCerticateVo;
import com.yizhi.certificate.application.vo.ApiUserCertificateVo;
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.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.*;
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.*;

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

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

    private static final Logger logger = LoggerFactory.getLogger(CertificateAppController.class);

    @Autowired
    CertificateAppClient certificateAppClient;

    @Autowired
    CertificateClient certificateClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    private OrganizationClient organizationClient;


    @ApiOperation(value = "查询学员端证书数量")
    @PostMapping("/getCount")
    public Response<Integer> getCertificateCount() {
        try {
            RequestContext requestContext = ContextHolder.get();
            Integer count = certificateAppClient.getCertificateCount(requestContext.getAccountId(), requestContext.getCompanyId(), requestContext.getSiteId());
            return Response.ok(count);
        } catch (Exception e) {
            return Response.fail(LogError.LOG_SEARCH_ERROR_COUNTCERTIFICATEMSG);
        }

    }


    @ApiOperation(value = "根据学生证表主键id 获取单个证书对象", notes = "获取证书，type=0长期有效 ,type=1固定周期有效，type=2固定失效日期有效", response = TrUserCertificateVo.class,
            extensions = {
                    @Extension(name = ReturnCode.API_SUB_FLAG, properties = {
                            @ExtensionProperty(name = LogError.CERTIFICATE_ANALYSIS_ERROR, value = LogError.CERTIFICATE_ANALYSIS_ERROR_MSG)
                    })
            }
    )
    @GetMapping("/get")
    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
    ) {
        try {
            RequestContext requestContext = ContextHolder.get();
            System.out.println(requestContext.getAccountId());
            TrUserCertificateVo trUserCertificate = certificateAppClient.getCertificate(id);
            if (trUserCertificate != null) {
                trUserCertificate.setCreateByName(requestContext.getSiteName());
                return Response.ok(getImage(trUserCertificate));
            } else {
                TrUserCertificateVo trUserCertificate1 = certificateAppClient.view(id, requestContext.getAccountId(), projectId);
                trUserCertificate1.setCreateByName(requestContext.getSiteName());
                if (null != trUserCertificate1) {
                    return Response.ok(getImage(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) {
            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, "https://cloud-wmy.oss-cn-shanghai.aliyuncs.com/wmy/1553587267000.zip", accountVO, orgNameList);
            }
            if (LogError.CERTIFICATE_ANALYSIS_ERROR.equals(result)) {
                logger.error("我的证书生成解析失败！");
                return trUserCertificate;
            } else {
                trUserCertificate.setUserImage(result);
                certificateAppClient.updateTrUserCertificate(trUserCertificate);
            }
        }
        return trUserCertificate;
    }


    @ApiOperation(value = "我的证书列表", notes = "app我的证书列表", response = TrUserCertificateVo.class,
            extensions = {
                    @Extension(name = ReturnCode.API_SUB_FLAG, properties = {
                            @ExtensionProperty(name = LogError.USER_CERTIFICATE_SEARCH_ERROR, value = LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG)
                    })
            }
    )
    @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 = certificateAppClient.list(apiSeachCerticateVo);
            if (page != null) {
                return Response.ok(page);
            }
            return Response.fail(LogError.USER_CERTIFICATE_SEARCH_ERROR, LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG);
        } catch (Exception e) {
            logger.error(LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG, e);
            return Response.fail(LogError.USER_CERTIFICATE_SEARCH_ERROR, LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG);

        }

    }


    @ApiOperation(value = "根据证书标题 certificate_title 模糊查询 我的证书列表", notes = "app我的证书列表", response = ApiUserCertificateVo.class,
            extensions = {
                    @Extension(name = ReturnCode.API_SUB_FLAG, properties = {
                            @ExtensionProperty(name = LogError.USER_CERTIFICATE_SEARCH_ERROR, value = LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG)
                    })
            }
    )
    @GetMapping("/searchList")
    public Response list(
            @ApiParam(value = "证书标题", required = false) @RequestParam(value = "certificate_title", required = false) String certificate_title,
            @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.setPageNo(pageNo);
            apiSeachCerticateVo.setPageSize(pageSize);
            RequestContext requestContext = ContextHolder.get();
            apiSeachCerticateVo.setAccountId(requestContext.getAccountId());
            apiSeachCerticateVo.setCompanyId(requestContext.getCompanyId());
            apiSeachCerticateVo.setSiteId(requestContext.getSiteId());

            Page<ApiUserCertificateVo> page = certificateAppClient.appSerachAppList(apiSeachCerticateVo);
            if (page != null) {
                return Response.ok(page);
            }
            return Response.fail(LogError.USER_CERTIFICATE_SEARCH_ERROR, LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG);
        } catch (Exception e) {
            logger.error(LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG, e);
            return Response.fail(LogError.USER_CERTIFICATE_SEARCH_ERROR, LogError.USER_CERTIFICATE_SEARCH_ERROR_MSG);
        }
    }
}
