package com.yizhi.application.document;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.course.constant.UtilConstants;
import com.yizhi.application.course.util.OssUpload;
import com.yizhi.application.course.util.WebUpConvert;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.documents.application.feign.DocumentClient;
import com.yizhi.documents.application.vo.documents.DocumentParamVo;
import com.yizhi.documents.application.vo.documents.ModelVo;
import com.yizhi.documents.application.vo.documents.ParamsVo;
import com.yizhi.documents.application.vo.documents.UploadVo;
import com.yizhi.documents.application.vo.domain.DocumentVo;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hutao
 * @since 2019-06-11
 */
@Api(tags = "资料库管理端接口", description = "资料库管理端接口")
@RestController
@RequestMapping("/manage/document")
public class WebDocumentComtroller {


    @Resource
    private DocumentClient documentClient;
    @Resource
    private WebUpConvert webUpConvert;
    @Value("${ACTIVE}")
    public String active;
    private static final Logger LOGGER = LoggerFactory.getLogger(WebDocumentComtroller.class);

    @PostMapping("/upload")
    @ApiOperation(value = "资料上传", notes = "资料上传", response = String.class)
    public Response<String> upload(@ApiParam("uploadVo 里面参数除id,均必传") @RequestBody UploadVo uploadVo) {
        if (uploadVo == null) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER1.getCode());
        }
        if (StringUtils.isEmpty(uploadVo.getName().trim()) || StringUtils.isEmpty(uploadVo.getUrl().trim())) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER1.getCode());
        }
        if (documentClient.upload(uploadVo)) {
            return Response.ok("上传资料成功！");
        }
        return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER2.getCode());
    }

    @PostMapping("/delete")
    @ApiOperation(value = "资料删除", notes = "资料删除", response = String.class)
    public Response<String> delete(@ApiParam("modelVo: id、needDelete必传") @RequestBody ModelVo modelVo) {
        if (modelVo == null) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        if (null == modelVo.getId()) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        ParamsVo paramsVo = documentClient.delete(modelVo.getId(), modelVo.getNeedDelete());
        if (paramsVo.getSuccess()) {
            return Response.ok("删除成功！");
        } else {
            return Response.ok(paramsVo.getErrorMsg());
        }
    }

    @PostMapping("/query/onCondition")
    @ApiOperation(value = "按条件查询资料", notes = "按条件查询资料", response = DocumentVo.class)
    public Response<Page<DocumentVo>> query(@ApiParam("documentParamVo") @RequestBody DocumentParamVo documentParamVo) {
        return Response.ok(documentClient.query(documentParamVo));
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改资料", notes = "修改资料", response = String.class)
    public Response update(@ApiParam("uploadVo") @RequestBody UploadVo uploadVo) {
        if (uploadVo == null) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        if (null == uploadVo.getId()) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        if (StringUtils.isEmpty(uploadVo.getName()) && StringUtils.isEmpty(uploadVo.getUrl())) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER1.getCode());
        }
        if (uploadVo.getSuffixName().equalsIgnoreCase("pdf")) {
            String imageDir = null;
            try {
                imageDir = webUpConvert.convert(uploadVo.getUrl(), uploadVo.getFileName(), UtilConstants.DOC_PATH, 200, 0, UtilConstants.OPENOFFICE_PATH);
            } catch (IOException e) {
                LOGGER.error("将上传的pdf转换成图片拼接富文本，错误：", e);
            }

            File dir = new File(imageDir);
            File[] files = dir.listFiles();

            String uploadFile;
            String key;
            List<String> imageOssPathList = new ArrayList<>(files.length);

            if (files.length > 0) {
                for (File file : files) {
                    uploadFile = file.getAbsolutePath();
                    key = uploadVo.getFileName().substring(0, uploadVo.getFileName().lastIndexOf(".")) + "/" + file.getName();
                    String result = OssUpload.upload(uploadFile, key, active);
                    imageOssPathList.add(result);
                }
            }

            if (!CollectionUtils.isEmpty(imageOssPathList)) {
                String htmlBR = "<p><br></p>";
                String content = htmlBR;
                StringBuilder sb = new StringBuilder(content);

                for (int i = 1; i <= imageOssPathList.size(); i++) {
                    for (String image : imageOssPathList) {
                        String index = image.substring(image.lastIndexOf("/") + 1, image.lastIndexOf("."));
                        if (index.equals(String.valueOf(i))) {
                            sb.append("<p><img src=\" " + image + " \" /></p>");
                            sb.append("<p><br></p>");
                        }
                    }
                }

                uploadVo.setPdfUrl(sb.toString());
            }
		}
        ParamsVo paramsVo = documentClient.update(uploadVo);
        if (paramsVo.getSuccess()) {
            return Response.ok("修改成功！");
        } else {
            return Response.fail(paramsVo.getErrorMsg());
        }
    }

    /**
     * @param modelVo 里面的id必传
     * @return
     */
    @GetMapping("/query/byId")
    @ApiOperation(value = "通过id查询资料", notes = "通过id查询资料", response = DocumentVo.class)
    public Response<DocumentVo> queryById(@ApiParam("modelVo id必传") @RequestBody ModelVo modelVo) {
        if (null == modelVo) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        if (null == modelVo.getId()) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER3.getCode());
        }
        return Response.ok(documentClient.queryById(modelVo.getId()));
    }

    /**
     * @param relationId   与模块类型有关  关联id
     * @param relationType 关联模块类型：1、课程；2、培训项目
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/query/ByRelationId")
    @ApiOperation(value = "通过关联关系查询", notes = "通过关联关系查询", response = DocumentVo.class)
    public Response<Page<DocumentVo>> queryByIds(@ApiParam("关联模块id必传") @RequestParam("relationId") Long relationId,
                                                 @ApiParam("关联模块类型必传") @RequestParam("relationType") Integer relationType,
                                                 @ApiParam("pageNo") @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                 @ApiParam("pageSize") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return Response.ok(documentClient.queryByIds(relationId, relationType, pageNo, pageSize));
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载资料", notes = "下载资料", response = DocumentVo.class)
    public Response<String> download(@ApiParam("资料id必传") @RequestParam("id") Long id,
                                     @ApiParam("终端类型：1、PC；2、weixin；3、app；4、manage") @RequestParam("termialType") Integer termialType) {

        if (termialType < 1 && termialType > 4) {
            return Response.fail(InternationalEnums.DOCUMENTCOMTROLLER4.getCode());
        }
        ParamsVo paramsVo = documentClient.download(id, termialType);
        if (paramsVo.getSuccess()) {
            return Response.ok(paramsVo.getSuccessData());
        } else {
            return Response.fail(paramsVo.getErrorMsg());
        }
    }

    @PostMapping("/export/onCondition")
    @ApiOperation(value = "按条件导出资料列表", notes = "按条件导出资料", response = DocumentVo.class)
    public Response<Page<DocumentVo>> export(@ApiParam("documentParamVo") @RequestBody DocumentParamVo documentParamVo) {
        Long taskId = System.currentTimeMillis();
        String taskName =   "资料库列表导出" + "_" + taskId.toString();
        String serialNo = "DOCUMENT-EXPORT-" + taskId.toString();
        documentParamVo.setTaskId(taskId);
        documentParamVo.setTaskName(taskName);
        documentParamVo.setSerialNo(serialNo);
        try{
            documentClient.export(documentParamVo);

        } catch(Exception e){
            LOGGER.error("", e);
            e.getStackTrace();
        }
        return Response.ok("导出成功," + " " + "任务名称:" + taskName);
    }


}

