package com.m2pool.manage.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.constant.HttpStatus;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.core.web.page.TableDataInfo;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.manage.constant.CountryConstant;
import com.m2pool.manage.dto.ManageCatalogueDocumentDto;
import com.m2pool.manage.dto.ManageCatalogueDto;
import com.m2pool.manage.dto.ManageDocumentDto;
import com.m2pool.manage.entity.ManageDocuments;
import com.m2pool.manage.mapper.ManageDocumentsMapper;
import com.m2pool.manage.service.ManageDocumentsService;
import com.m2pool.manage.utils.TranslateUtils;
import com.m2pool.manage.vo.ManageBaseVo;
import com.m2pool.manage.vo.ManageCatalogueVo;
import com.m2pool.manage.vo.ManageDocumentVo;
import com.m2pool.manage.vo.ManageSearchDocumentVo;
import com.mongodb.client.result.DeleteResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * @Description 文档信息 服务器类
 */
@Service
public class ManageDocumentsServiceImpl extends ServiceImpl<ManageDocumentsMapper, ManageDocuments> implements ManageDocumentsService {


    @Resource
    private ManageDocumentsMapper manageDocumentsMapper;


    @Resource(name = "docMongoTemplate")
    private MongoTemplate mongoTemplate;

    @Override
    public TableDataInfo<ManageDocumentDto> getListDataByPage(ManageSearchDocumentVo manageSearchDocumentVo) {
        PageHelper.startPage(manageSearchDocumentVo.getPageNum(), manageSearchDocumentVo.getPageSize());
        List<ManageDocumentDto> listDataByPage;
        if (CountryConstant.EN.equals(manageSearchDocumentVo.getLang())){
            listDataByPage = manageDocumentsMapper.getListDataEnByPage(manageSearchDocumentVo.getKeyword(),manageSearchDocumentVo.getType());
        }else{
            listDataByPage = manageDocumentsMapper.getListDataByPage(manageSearchDocumentVo.getKeyword(),manageSearchDocumentVo.getType());
        }
        return getDataTable(listDataByPage);
    }

    private TableDataInfo<ManageDocumentDto> getDataTable(List<ManageDocumentDto>  list)
    {
        TableDataInfo<ManageDocumentDto> rspData = new TableDataInfo<ManageDocumentDto>();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        PageInfo<ManageDocumentDto> pageInfo = new PageInfo<ManageDocumentDto>(list);
        rspData.setTotal(pageInfo.getTotal());
        rspData.setTotalPage(pageInfo.getPages());
        PageHelper.clearPage();
        return rspData;
    }
    @Override
    public R<ManageDocumentDto> findDataById(ManageBaseVo manageBaseVo) {
        ManageDocuments documents = this.getById(manageBaseVo.getId());
        ManageDocumentDto build = ManageDocumentDto.builder()
                .id(documents.getId())
                .title(documents.getTitle())
                .subTitle(documents.getSubTitle())
                .content(documents.getContent())
                .createUser(documents.getCreateUser())
                .updateUser(documents.getUpdateUser())
                .updateTime(documents.getUpdateTime())
                .createTime(documents.getCreateTime())
                .build();
        if (CountryConstant.EN.equals(manageBaseVo.getLang())){
            build.setTitle(documents.getTitleEn());
            build.setSubTitle(documents.getSubTitleEn());
            build.setContent(documents.getContentEn());
        }
        return R.success(build);
    }

    @Override
    public R<String> addDocument(ManageDocumentVo manageDocumentVo) {
        String fromCountry = CountryConstant.ZH;
        String toCountry = CountryConstant.EN;
        ManageDocuments build;
        if (manageDocumentVo.getTitle().isEmpty()){
            return R.fail("标题不能为空");
        }
        if (manageDocumentVo.getType() ==  null){
            return R.fail("文档类型不能为空");
        }
        if (manageDocumentVo.getTitleUrl() != null && manageDocumentVo.getTitleUrl().length() >= 256){
            return R.fail("标题图片长度不能大于255");
        }

        if (manageDocumentVo.getContent().length() >= 50000){
            return R.fail("内容长度大于50000,请确定传递的html格式是否正确");
        }

        //中文转英文
        build =  ManageDocuments.builder()
                .title(manageDocumentVo.getTitle())
                .subTitle(manageDocumentVo.getSubTitle())
                .content(manageDocumentVo.getContent())
                .type(manageDocumentVo.getType())
                .contentEn(TranslateUtils.translateHtml(manageDocumentVo.getContent(), fromCountry, toCountry))
                .titleEn(TranslateUtils.tencentTextTranslate(manageDocumentVo.getTitle(), fromCountry, toCountry))
                .subTitleEn(TranslateUtils.tencentTextTranslate(manageDocumentVo.getSubTitle(),fromCountry, toCountry))
                .childType(manageDocumentVo.getChildType())
                .articleUrl(manageDocumentVo.getArticleUrl())
                .titleUrl(manageDocumentVo.getTitleUrl())
                .createUser(SecurityUtils.getUsername())
                .updateUser(SecurityUtils.getUsername())
                .coin(manageDocumentVo.getCoin())
                .build();
        int insert = manageDocumentsMapper.insert(build);
        //存入mongodb 方便以后如果mysql查询限制时切换
        mongoTemplate.save(build, "documents");
        if (insert > 0){
            return R.success("添加文章成功");
        }
        return R.fail("添加文章失败");
    }

    @Override
    public R<String> deleteDocument(ManageBaseVo manageBaseVo) {
        //int i = manageDocumentsMapper.updateById(ManageDocuments.builder().id(manageBaseVo.getId()).del(true).build());
        int delete = manageDocumentsMapper.deleteById(manageBaseVo.getId());
        DeleteResult remove = mongoTemplate.remove(new Query(Criteria.where("id").is(manageBaseVo.getId())), "documents");
        if (delete > 0){
            return R.success("删除文章成功");
        }
        return R.fail("删除文章失败");
    }

    @Override
    public R<String> updateDocument(ManageDocumentVo manageDocumentVo) {

        String fromCountry = CountryConstant.ZH;
        String toCountry = CountryConstant.EN;
        ManageDocuments build;
        if (manageDocumentVo.getTitleUrl() != null && manageDocumentVo.getTitleUrl().length() >= 256){
            return R.fail("标题图片地址字符数不能大于255");
        }
        Update update = new Update();

        String content = StringUtils.isEmpty(manageDocumentVo.getContent()) ? "" :   TranslateUtils.translateHtml(manageDocumentVo.getContent(), fromCountry, toCountry);
        String title = StringUtils.isEmpty(manageDocumentVo.getTitle()) ? "" :  TranslateUtils.tencentTextTranslate(manageDocumentVo.getTitle(), fromCountry, toCountry);
        String subTitle = StringUtils.isEmpty(manageDocumentVo.getSubTitle()) ? "" :  TranslateUtils.tencentTextTranslate(manageDocumentVo.getSubTitle(), fromCountry, toCountry);
        //中文转英文
        build =  ManageDocuments.builder()
                .id(manageDocumentVo.getId())
                .title(manageDocumentVo.getTitle())
                .subTitle(manageDocumentVo.getSubTitle())
                .content(manageDocumentVo.getContent())
                .contentEn(content)
                .titleEn(title)
                .subTitleEn(subTitle)
                .articleUrl(manageDocumentVo.getArticleUrl())
                .titleUrl(manageDocumentVo.getTitleUrl())
                .childType(manageDocumentVo.getChildType())
                .createUser(SecurityUtils.getUsername())
                .updateUser(SecurityUtils.getUsername())
                .type(manageDocumentVo.getType())
                .coin(manageDocumentVo.getCoin())
                .build();
        // 中文转英文
        update.set("title", manageDocumentVo.getTitle())
                .set("subTitle", manageDocumentVo.getSubTitle())
                .set("content", manageDocumentVo.getContent())
                .set("articleUrl", manageDocumentVo.getArticleUrl())
                .set("titleUrl", manageDocumentVo.getTitleUrl())
                .set("contentEn", content)
                .set("titleEn", title)
                .set("subTitleEn", subTitle)
                .set("childType", manageDocumentVo.getChildType())
                .set("createUser", SecurityUtils.getUsername())
                .set("updateUser", SecurityUtils.getUsername())
                .set("type", manageDocumentVo.getType());

        Query query = new Query(Criteria.where("id").is(manageDocumentVo.getId()));

        mongoTemplate.updateFirst(query, update, "documents");
        int insert = manageDocumentsMapper.updateById(build);
        if (insert > 0){
            return R.success("修改文章成功");
        }
        return R.fail("修改文章失败");
    }


    @Override
    public R<ManageDocumentDto> findDataInfo(ManageBaseVo manageBaseVo) {
        LambdaQueryWrapper<ManageDocuments> wrapper = new LambdaQueryWrapper<ManageDocuments>();
        if (manageBaseVo.getId() != null) {
            wrapper.eq(ManageDocuments::getId, manageBaseVo.getId());
        }
        if (manageBaseVo.getChildType() != null){
            wrapper.eq(ManageDocuments::getChildType, manageBaseVo.getChildType());
        }

        List<ManageDocuments> manageDocuments = manageDocumentsMapper.selectList(wrapper);
        if (manageDocuments.isEmpty()){
            return R.fail("未找到该文章");
        }
        ManageDocuments documents = manageDocuments.get(0);

        ManageDocumentDto build = null;
        if(documents != null){
            build = ManageDocumentDto.builder()
                    .id(documents.getId())
                    .title(documents.getTitle())
                    .subTitle(documents.getSubTitle())
                    .content(documents.getContent())
                    .articleUrl(documents.getArticleUrl())
                    .titleUrl(documents.getTitleUrl())
                    .createUser(documents.getCreateUser())
                    .updateUser(documents.getUpdateUser())
                    .updateTime(documents.getUpdateTime())
                    .createTime(documents.getCreateTime())
                    .childType(documents.getChildType())
                    .type(documents.getType())
                    .coin(documents.getCoin())
                    .build();
            if (CountryConstant.EN.equals(manageBaseVo.getLang())){
                build.setTitle(documents.getTitleEn());
                build.setSubTitle(documents.getSubTitleEn());
                build.setContent(documents.getContentEn());
            }

        }
        return R.success(build);
    }

    @Override
    public TableDataInfo<ManageCatalogueDocumentDto> findCatalogueDocumentList(ManageCatalogueVo manageCatalogueVo) {
        if (manageCatalogueVo.getChildType() == null){
            manageCatalogueVo.setChildType(0);
        }
        PageHelper.startPage(manageCatalogueVo.getPageNum(), manageCatalogueVo.getPageSize());
        List<ManageCatalogueDocumentDto> catalogueDocumentList = manageDocumentsMapper.findCatalogueDocumentList(manageCatalogueVo.getType(),manageCatalogueVo.getLang(),manageCatalogueVo.getChildType());
        return getDataManageCatalogueDocument(catalogueDocumentList);
    }

    private TableDataInfo<ManageCatalogueDocumentDto> getDataManageCatalogueDocument(List<ManageCatalogueDocumentDto>  list)
    {
        TableDataInfo<ManageCatalogueDocumentDto> rspData = new TableDataInfo<ManageCatalogueDocumentDto>();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        PageInfo<ManageCatalogueDocumentDto> pageInfo = new PageInfo<ManageCatalogueDocumentDto>(list);
        rspData.setTotal(pageInfo.getTotal());
        rspData.setTotalPage(pageInfo.getPages());
        PageHelper.clearPage();
        return rspData;
    }

    @Override
    public TableDataInfo<ManageDocumentDto> searchDocument(ManageSearchDocumentVo manageSearchDocumentVo) {
        PageHelper.startPage(manageSearchDocumentVo.getPageNum(), manageSearchDocumentVo.getPageSize());
        List<ManageDocumentDto> listDataByPage;
        if (CountryConstant.EN.equals(manageSearchDocumentVo.getLang())){
            listDataByPage = manageDocumentsMapper.getListDataEnByPage(manageSearchDocumentVo.getKeyword(), manageSearchDocumentVo.getType());
        }else{
            listDataByPage = manageDocumentsMapper.getListDataByPage(manageSearchDocumentVo.getKeyword(), manageSearchDocumentVo.getType());
        }

        return getDataTable(listDataByPage);
    }

    @Override
    public R<List<ManageCatalogueDto>> findCatalogueList(ManageCatalogueVo manageCatalogueVo) {
        List<ManageCatalogueDto> catalogueList = manageDocumentsMapper.findCatalogueList(manageCatalogueVo.getLang());
        return R.success(catalogueList);
    }
}
