package com.yizhi.application.certificate.controller;

import com.yizhi.application.certificate.constant.CertificateConstant;
import com.yizhi.application.certificate.constant.LogError;
import com.yizhi.application.certificate.constant.UtilConstants;
import com.yizhi.application.certificate.util.CertificateZipAnalysis;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.certificate.application.feign.CertificateClassifyClient;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.*;
import com.yizhi.certificate.application.vo.domain.CertificateClassifyVo;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.certificate.application.vo.domain.TrCertificateTemplateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.event.EventWrapper;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Api(tags = "证书接口", description = "certificate Controller")
@RestController
@RequestMapping("/manage/certificate")
public class CertificateController {

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

    @Autowired
    CertificateClient certificateClient;

    @Autowired
    CertificateZipAnalysis certificateZipAnalysis;

    @Autowired
    TpPlanActivityClient tpPlanActivityClient;

    @Autowired
    private CertificateClassifyClient certificateClassifyClient;

    @ApiOperation(value = "根据证书名称模糊    查询证书列表（分页）   company_id 项目id 为0的证书", response = PageCertificateVo.class)
    @GetMapping("/getlist")
    public Response getCertificatePage(
            @ApiParam(value = "证书标题", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(value = "要跳转的页数", required = false) @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数,默认:10", required = false) @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        RequestContext requestContext = ContextHolder.get();
        ApiSeachCerticateVo apiSeachCerticateVo = new ApiSeachCerticateVo();
        apiSeachCerticateVo.setTitle(title);
        apiSeachCerticateVo.setPageNo(pageNo);
        apiSeachCerticateVo.setPageSize(pageSize);

        apiSeachCerticateVo.setCompanyId(requestContext.getCompanyId());
        apiSeachCerticateVo.setSiteId(requestContext.getSiteId());
        if (!requestContext.isAdmin()) {
            apiSeachCerticateVo.setOrgId(requestContext.getOrgIds());
        }
        return Response.ok(certificateClient.getList(apiSeachCerticateVo));
    }

    @ApiOperation(value = "自定义证书解析", notes = "自定义证书解析", response = TrCertificateTemplateVo.class, extensions = {
            @Extension(name = ReturnCode.API_SUB_FLAG, properties = {
                    @ExtensionProperty(name = LogError.CERTIFICATE_ANALYSIS_ERROR, value = LogError.CERTIFICATE_ANALYSIS_ERROR_MSG)})})
    @GetMapping("/analysis")
    public Response<TrCertificateTemplateVO> analysisCertificate(
            @ApiParam("阿里云oss文件url") @RequestParam("url") String url,
            @ApiParam("文件名带后缀 例:XXX.zip") @RequestParam("fileName") String fileName) {

        try {
            // 证书自定义包解析
            logger.info("原文件名：" + fileName);
            fileName = fileName.replaceAll(" ", "");
            logger.info("文件名：" + fileName);
            String result = certificateZipAnalysis.parse(url, UtilConstants.CERTIFICATE_SAVE_PATH, fileName);

            if (LogError.CERTIFICATE_ANALYSIS_ERROR.equals(result)) {
                return Response.fail();
            } else {
                RequestContext requestContext = ContextHolder.get();
                TrCertificateTemplateVo trCertificateTemplate = new TrCertificateTemplateVo();
                trCertificateTemplate.setCreateById(requestContext.getAccountId());
                trCertificateTemplate.setCreateByName(requestContext.getAccountName());
                trCertificateTemplate.setCreateTime(new Date());
                trCertificateTemplate.setTemplateImage(result);
                trCertificateTemplate.setTemplateName(fileName);
                trCertificateTemplate.setTemplateUrl(url);
                trCertificateTemplate.setType(1);
                trCertificateTemplate = certificateClient.saveTemplate(trCertificateTemplate);
                return Response.ok(trCertificateTemplate);
            }
        } catch (Exception e) {
            logger.error(LogError.CERTIFICATE_ANALYSIS_ERROR_MSG, e);
            return Response.fail(LogError.CERTIFICATE_ANALYSIS_ERROR, LogError.CERTIFICATE_ANALYSIS_ERROR_MSG);
        }
    }

    @ApiOperation(value = "证书报表")
    @GetMapping("/statistics")
    public Response<String> statistics(@ApiParam("查询的开始时间") @RequestParam("startTime") String startTime,
                                       @ApiParam("查询的结束时间") @RequestParam("endTime") String endTime,
                                       @ApiParam("证书主键id") @RequestParam("id") Long id) {

        return Response.ok();
    }

    @ApiOperation(value = "证书报表导出")
    @GetMapping("/export")
    public Response<String> export(@ApiParam("查询的开始时间") @RequestParam("startTime") String startTime,
                                   @ApiParam("查询的结束时间") @RequestParam("endTime") String endTime,
                                   @ApiParam("证书主键id") @RequestParam("id") Long id) {

        return Response.ok();
    }

    @ApiOperation(value = "根据证书对象修改证书")
    @PostMapping("/update")
    public Response<String> updateCertificate(
            @RequestBody CertificateVo certificate
    ) {

        CertificateVo updateCertificate = certificateClient.getCertificate(certificate.getId());

        updateCertificate.setTitle(certificate.getTitle());
        updateCertificate.setLogourl(certificate.getLogourl());
        updateCertificate.setIssuer(certificate.getIssuer());
        updateCertificate.setType(certificate.getType());
        updateCertificate.setCircleCount(certificate.getCircleCount());
        updateCertificate.setCircleUnit(certificate.getCircleUnit());
        updateCertificate.setEndTime(certificate.getEndTime());
        updateCertificate.setTemplateId(certificate.getTemplateId());
        updateCertificate.setTemplateImage(certificate.getTemplateImage());
        updateCertificate.setTags(certificate.getTags());

        // 获取请求上下文信息
        RequestContext requestContext = ContextHolder.get();
        // 用于获取当前用户的信息
        updateCertificate.setUpdateById(requestContext.getAccountId());
        updateCertificate.setUpdateByName(requestContext.getAccountName());
        updateCertificate.setUpdateTime(new Date());
        try {
            if (certificateClient.updateCertificate(certificate) != null) {
                return Response.ok(certificate);
            }
        } catch (Exception e) {
            return Response.fail(LogError.LOG_UPDATECERTIFICATE_ERROR_SUBCODE,
                    LogError.LOG_UPDATECERTIFICATE_ERROR_SUBMSG);
        }
        return Response.ok();
    }

    @ApiOperation(value = "获得证书列表", response = CertificateListVO.class)
    @GetMapping("/list")
    public Response getCertificateList(
            @ApiParam(value = "证书名称或者标签", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(value = "证书状态 不传全部 0:下架 1:上架 2:草稿", required = false) @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "分类id", required = false) @RequestParam(value = "classifyId", required = false) Long classifyId,
            @ApiParam(name = "currentTime", value = "当前时间") @RequestParam(value = "currentTime", required = false) String currentTime,
            @ApiParam(value = "要跳转的页数", required = false) @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数,默认:10", required = false) @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        RequestContext requestContext = ContextHolder.get();

        return Response.ok(certificateClient.searchCertificateList(title, status, classifyId, currentTime, requestContext.getCompanyId(),
                requestContext.getSiteId(), requestContext.getOrgIds(), pageNo, pageSize));

    }

    @ApiOperation(value = "获得证书模板列表", response = TrCertificateTemplateVo.class)
    @GetMapping("/template")
    public Response<List<TrCertificateTemplateVo>> getTemplateList() {
        List<TrCertificateTemplateVo> list = null;
        try {
            list = certificateClient.getTemplateList();
        } catch (Exception e) {
            return Response.fail(LogError.LOG_SEARCH_ERROR_SELECTTEMPLATE_SUBCODE,
                    LogError.LOG_SEARCH_ERROR_SELECTTEMPLATE_SUBMSG);
        }
        // 如果没有证书模板
        if (list.size() == 0) {
            return Response.fail(LogError.LOG_SEARCH_ERROR_SELECTTEMPLATE_SUBCODE,
                    LogError.LOG_SEARCH_ERROR_SELECTTEMPLATE_SUBMSG);
        }
        return Response.ok(list);
    }

    @ApiOperation(value = "添加证书")
    @PostMapping("/save")
    public Response<String> saveCertificate(
            @RequestBody CertificateVo certificate
    ) {
        // 获取请求上下文信息
        RequestContext requestContext = ContextHolder.get();
        // 用于获取当前用户的信息
        certificate.setCreateById(requestContext.getAccountId());
        certificate.setCompanyId(requestContext.getCompanyId());
        certificate.setSiteId(requestContext.getSiteId());
        certificate.setOrgId(requestContext.getOrgId());
        certificate.setCreateById(requestContext.getAccountId());
        certificate.setCreateByName(requestContext.getAccountName());
        try {
            if (certificateClient.saveCertificate(certificate) != null) {
                return Response.ok(certificate);
            }
        } catch (Exception e) {
            return Response.fail(LogError.LOG_ADDCERTIFICATE_ERROR_SUBCODE, LogError.LOG_ADDCERTIFICATE_ERROR_SUBMSG);
        }
        return Response.ok(certificate);
    }

    @ApiOperation(value = "根据证书id，选择是否启用，修改证书状态")
    @PostMapping("/enable")
    public Response<String> enableCertificate(
            @RequestBody CertificateVo certificate
//			@ApiParam(name = "id", value = "证书id") @RequestParam(name = "id") Long id
    ) {

        try {

//            if (certificate.getStatus() == 0) {
//                List<Long> ids = new ArrayList<Long>();
//                ids.add(certificate.getId());
//                Set<String> tpNames = tpPlanActivityClient.checkBizIsExistInTpNames(ids);
//                String tpName = "";
//                boolean isUp = false;
//                if (!CollectionUtils.isEmpty(tpNames)) {
//                    for (String s : tpNames) {
//                        tpName = s;
//                    }
//                    isUp = true;
//                }
//                if (isUp) {
//                    return Response.fail("10000", "已经关联到培训项目，培训项目名称:" + tpName + ",不可以下架。");
//                }
//            }

            if (certificateClient.enableCertificate(certificate)) {
                return Response.ok("启用成功！");
            }else {
                return Response.fail("4001", InternationalEnums.CERTIFICATECONTROLLER1.getCode());
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("", e);
            return Response.fail(LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG);
        }
    }

    @ApiOperation(value = "根据证书id,查询单个证书信息，返回证书对象", response = CertificateVo.class)
    @GetMapping("/get")
    public Response<CertificateListVO> getCertificate(
            @ApiParam(name = "id", value = "证书id", required = true) @RequestParam(name = "id") Long id) {

        try {
            CertificateListVO certificateListVO = certificateClient.getCertificate(id);

            if (certificateListVO != null) {
                if (2 != certificateListVO.getType()) {
                    certificateListVO.setEndTime(null);
                }
                return Response.ok(certificateListVO);
            } else {
                return Response.fail(LogError.LOG_SEARCH_ERROR, LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG);
            }

        } catch (Exception e) {
            return Response.fail(LogError.LOG_SEARCH_ERROR, LogError.LOG_SEARCH_ERROR_ENABLECERTIFICATEMSG);
        }

    }

    @ApiOperation(value = "根据证书id,复制单个证书信息，数据库新增一条数据，证书信息完全一致但名称修改为“***证书【复制件】：证书状态为“下架”")
    @PostMapping("/copy")
    public Response<String> copyCertificate(
            @RequestBody CertificateVo certificate
    ) {
        try {
            // 调用添加方法
            if (certificateClient.copyCertificate(certificate) != null) {
                return Response.ok();
            } else {
                return Response.fail(LogError.LOG_SEARCH_ERROR, LogError.LOG_SEARCH_ERROR_COPYCERTIFICATEMSG);
            }
        } catch (Exception e) {
            return Response.fail(LogError.LOG_SEARCH_ERROR, LogError.LOG_SEARCH_ERROR_COPYCERTIFICATEMSG);
        }

    }

    /*@Autowired
    AmqpTemplate amqpTemplate;*/

    @ApiOperation(value = "测试消息")
    @GetMapping("/message")
    public Response<String> message() {
        Map<String, Object> map = new HashMap<>();
        map.put("certificateId", 1014733018797334528l);
        map.put("accountId", 000l);
        map.put("projectId", 000l);
        map.put("projectName", "123");
       // amqpTemplate.convertAndSend("myCertificate", new EventWrapper<Map<String, Object>>(0l, map));
        return Response.ok();
    }

    @ApiOperation(value = "新建分类", notes = "新建分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "level", value = "1:一级分类, 2:二级分类, 3:三级分类", paramType = "body", required = true),
            @ApiImplicitParam(name = "name", value = "名称", paramType = "body", required = true),
            @ApiImplicitParam(name = "parentId", value = "父级id", paramType = "body", required = false),
            @ApiImplicitParam(name = "description", value = "分类描述", paramType = "body", required = false)})
    @PostMapping("/classify/insert")
    public Response<Object> classifyInsert(@RequestBody CertificateClassifyVo certificateClassify) {

        try {
            Integer result = certificateClassifyClient.insertClassify(certificateClassify);
            if (result.equals(CertificateConstant.INSERT_CLASSIFY_SUCCESS)) {
                return Response.ok();
            } else if (result.equals(CertificateConstant.INSERT_CLASSIFY_IDENTICAL_NAME)) {
                return Response.fail(InternationalEnums.CERTIFICATECONTROLLER2.getCode());
            } else {
                logger.error("############插入数据过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }
        } catch (Exception e) {
            logger.error("############证书服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "修改分类", notes = "修改分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类id", paramType = "body", required = true),
            @ApiImplicitParam(name = "name", value = "名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "description", value = "分类描述", paramType = "body", required = false)})
    @PostMapping("/classify/update")
    public Response<Object> updateClassify(@RequestBody CertificateClassifyVo certificateClassify) {

        try {
            boolean result = certificateClassifyClient.updateClassify(certificateClassify);
            if (result){
                return Response.ok();
            }else {
                return Response.fail(InternationalEnums.CERTIFICATECONTROLLER2.getCode());
            }
        } catch (Exception e) {
            logger.error("############证书服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "删除分类")
    @GetMapping("/classify/delete")
    public Response<CertificateClassifyVo> deleteClassify(@ApiParam(name = "id", value = "分类id", required = true)
                                                        @RequestParam(name = "id") Long id) {

        try {
            Integer result = certificateClassifyClient.deleteClassify(id);
            if (result == 1) {
                return Response.ok();
            } else if (result == 2) {
                return Response.fail(InternationalEnums.CERTIFICATECONTROLLER3.getCode());
            }
            return Response.fail(Constants.MSG_BIZ_FAIL);
        } catch (Exception e) {
            logger.error("############证书服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "获取分类列表", response = CertificateClassifyListVO.class)
    @GetMapping("/classify/list")
    public Response<CertificateClassifyListVO> getClassifyList() {

        try {
            return Response.ok(certificateClassifyClient.getClassifyList());

        } catch (Exception e) {
            logger.error("############证书服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "证书清单导出")
    @GetMapping("/list/export")
    public Response certificateListExport(
            @ApiParam(value = "证书名称或者标签", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(value = "证书状态 不传全部 1:已关联 2:未关联 3:草稿", required = false) @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "分类id", required = false) @RequestParam(value = "classifyId", required = false) Long classifyId,
            @ApiParam(name = "currentTime", value = "当前时间") @RequestParam(value = "currentTime", required = false) String currentTime) {


        String serialNo = certificateClient.searchCertificateListExport(title, status, classifyId, currentTime);

        return Response.ok("导出成功," + " " + "编号:" + serialNo);

    }

    @ApiOperation(value = "查看关联活动")
    @GetMapping("/getRelationActivities")
    public Response<CertificateClassifyVo> getRelationActivities(@ApiParam(name = "certificateId", value = "证书id", required = true)
                                                        @RequestParam(name = "certificateId") Long certificateId) {

        try {
            return Response.ok(certificateClient.getRelationActivities(certificateId));
        } catch (Exception e) {
            logger.error("############证书服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }
}
