package com.yizhi.application.portal.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.course.constant.UtilConstants;
import com.yizhi.application.course.util.WebUpConvert;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.lecturer.application.enums.DeleteFlag;
import com.yizhi.site.application.feign.InformationManageFeignClients;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.vo.domain.InformationVo;
import com.yizhi.site.application.vo.domain.ProtalPlateVo;
import com.yizhi.site.application.vo.site.IdOneVO;
import com.yizhi.site.application.vo.site.InfomationParamReleaseVO;
import com.yizhi.site.application.vo.site.InfomationParamVO;
import com.yizhi.site.application.vo.site.ParamVO;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;


import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 资讯管理
 *
 * @author mei
 * @Date: 2018/3/17 20:30
 */

@Api(tags = "资讯管理")
@RestController
@RequestMapping("/manage/site/classify/info")
public class SiteInformationManageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SiteInformationManageController.class);

    @Autowired
    private InformationManageFeignClients informationManageFeignClients;
    @Autowired
    private WebUpConvert webUpConvert;
    @Value("${ACTIVE}")
    public String active;

    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private PortalManagePCFeignClients portalManagePCFeignClient;

    @Value("${pc.host.url}")
    String pcHostUrl;

    /**
     * 资讯列表
     *
     * @return
     */
    @ApiOperation(value = "查看资讯", notes = "查看资讯", response = InfomationParamVO.class)
    @PostMapping("/list")
    public Response<Page<InfomationParamVO>> list(@RequestBody InfomationParamVO vo) {
        try {
            vo.setSiteId(ContextHolder.get().getSiteId());
            return Response.ok(informationManageFeignClients.list(vo));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 资讯发布的列表
     *
     */
    @ApiOperation(value = "查看资讯发布列表", notes = "查看资讯发布列表", response = InfomationParamVO.class)
    @PostMapping("/release/list")
    public Response<Page<InfomationParamVO>> releaseList(@RequestBody InfomationParamReleaseVO vo) {
        try {
            RequestContext context = ContextHolder.get();
            vo.setCompanyCode(context.getCompanyCode());
            vo.setCompanyId(context.getCompanyId());
            vo.setSiteCode(context.getSiteCode());
            vo.setSiteId(context.getSiteId());
            vo.setAccountId(vo.getAccountId());
            vo.setAdmin(context.isAdmin());
            vo.setOrgId(context.getOrgId());
            vo.setOrgIds(context.getOrgIds());
            vo.setOrgName(context.getOrgName());
            return Response.ok(informationManageFeignClients.releaseList(vo));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "保存资料分类", notes = "保存资料分类")
    @PostMapping("/insert")
    public Response<Boolean> insert(@RequestBody InformationVo information) {
        try {
            Date date = new Date();
            RequestContext context = ContextHolder.get();
            information.setCreateById(context.getAccountId());
            information.setCreateByName(context.getAccountName());
            information.setCreateTime(date);
            information.setUpdateById(context.getAccountId());
            information.setUpdateByName(context.getAccountName());
            information.setUpdateTime(date);
            information.setSiteId(context.getSiteId());
            Long id = informationManageFeignClients.insert(information);
            if (id == null) {
                Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER.getCode());
            }
            information.setId(id);
            //异步处理pdf转图片
            ansyExecutor(information);
            return Response.ok(true);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     *  //异步处理pdf转图片
     * @param information
     */
    public void ansyExecutor(InformationVo information){
        if (information.getId() == null) {
            LOGGER.error("新闻id为空！！！");
            return;
        }
        taskExecutor.asynExecute(new AbstractTaskHandler() {
            @Override
            public void handle() {
                // 上传的pdf不拼接富文本
//                translatePdfToPhoto(information);
                InformationVo contentInformation  = new InformationVo();
                contentInformation.setId(information.getId());
                contentInformation.setContent(information.getContent());
                informationManageFeignClients.updateContent(contentInformation);
            }
        });

    }

    @ApiOperation(value = "修改资料分类", notes = "修改资料分类")
    @PostMapping("/update")
    public Response<Boolean> update(@RequestBody InformationVo information) {
        try {
            RequestContext context = ContextHolder.get();
            information.setUpdateById(context.getAccountId());
            information.setUpdateByName(context.getAccountName());
            information.setUpdateTime(new Date());
            Boolean update = informationManageFeignClients.update(information);
            if (update){
                //异步处理pdf转图片
                ansyExecutor(information);
            }
            return Response.ok(true);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("" + e);
            return Response.fail(ReturnCode.UPDATE_FAIL.getCode(),ReturnCode.UPDATE_FAIL.getMsg());
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除站点", notes = "删除站点")
    public Response<String> deleteById(@RequestBody IdOneVO vo) {
        if (vo == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        if (vo.getId() == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        try {
            return Response.ok(informationManageFeignClients.deleteById(vo));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail();
        }
    }

    @PostMapping("/releases")
    @ApiOperation(value = "资讯发布", notes = "资讯发布")
    public Response<Boolean> releases(@RequestBody ParamVO vo) {
        if (vo == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        if (vo.getIds() == null || vo.getIds().size() == 0) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        return Response.ok(informationManageFeignClients.releases(vo));
    }

    @PostMapping("/unreleases")
    @ApiOperation(value = "资讯取消发布", notes = "资讯取消发布")
    public Response<Boolean> unreleases(@RequestBody ParamVO vo) {
        if (vo == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        if (vo.getIds() == null || vo.getIds().size() == 0) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        //新增新闻下架，校验是否关联首页模块
        List<Long> ids = vo.getIds();
        for (Long infoId : ids) {
            ProtalPlateVo protalPlate = new ProtalPlateVo();
            protalPlate.setLinkContent(infoId);
            protalPlate.setState(DeleteFlag.YES.ordinal());
            ProtalPlateVo plate = portalManagePCFeignClient.getPlate(protalPlate);
            if (plate != null) {
                LOGGER.info("新闻下架失败;informationId={},新闻已经关联到首页配置模块；不能下架",infoId);
                return Response.fail(InternationalEnums.TRAININGPROJECTCONTROLLER2.getCode());
            }
        }
        boolean b = informationManageFeignClients.unreleases(vo);
        return Response.ok(b);
    }

    @GetMapping("/view")
    @ApiOperation(value = "资讯预览", notes = "资讯预览", response = InformationVo.class)
    public Response<InformationVo> releases(@RequestParam(name = "id") Long id) {
        InformationVo info = informationManageFeignClients.informationView(id);
        return Response.ok(info);
    }

    @PostMapping("/top")
    @ApiOperation(value = "置顶", notes = "置顶")
    public Response<Boolean> top(@RequestBody IdOneVO vo) {
        if (vo == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        if (vo.getId() == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        try {
            return Response.ok(informationManageFeignClients.top(vo));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail();
        }
    }

    /**
     * 将上传的pdf转换成图片拼接富文本
     *
     * @param information
     */
    private void translatePdfToPhoto(InformationVo information) {
        String pdfOssUrl = information.getPdfOssUrl();
        String pdfFileName = information.getPdfFileName();
        if (StringUtils.isEmpty(pdfOssUrl) || StringUtils.isEmpty(pdfFileName)) {
            return;
        }

        String imageDir = null;
        try {
            imageDir = webUpConvert.convert(pdfOssUrl, pdfFileName, 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 = pdfFileName.substring(0, pdfFileName.lastIndexOf(".")) + "/" + file.getName();
                OssUpload.upload(uploadFile, key);
                String  result = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+key;
                imageOssPathList.add(result);
            }
        }

        if (!CollectionUtils.isEmpty(imageOssPathList)) {
            String htmlBR = "<p><br></p>";
            String content = StringUtils.isEmpty(information.getContent()) ? htmlBR : information.getContent();
            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>");
                    }
                }
            }

            information.setContent(sb.toString());
        }
    }

}
