package com.tourism.webadmin.app.website.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyOrderParam;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.validator.UpdateGroup;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.app.website.dto.TourismProjectTravelNotesWriteDetailPageDto;
import com.tourism.webadmin.app.website.dto.TourismProjectTravelNotesWriteToWebDto;
import com.tourism.webadmin.app.website.service.TourTravelNotesPublishService;
import com.tourism.webadmin.back.dto.TourTourismProjectTravelNotesWriteContentDto;
import com.tourism.webadmin.back.dto.TourismTravelNotesContentWriteDto;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.AuditState;
import com.tourism.webadmin.back.model.constant.UnmountState;
import com.tourism.webadmin.back.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tourism.common.huaweicloud.moderation.service.HuaweiCloudModerationService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("TourTravelNotesPublishService")
public class TourTravelNotesPublishServiceImpl implements TourTravelNotesPublishService {


    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;
    @Autowired
    private TourismTravelNotesContentWriteService tourismTravelNotesContentWriteService;
    @Autowired
    private TourTravelNotesMentionUserService tourTravelNotesMentionUserService;
    @Autowired
    private TourTravelNotesTopicRelationService tourTravelNotesTopicRelationService;
    @Autowired
    private HuaweiCloudModerationService huaweiCloudModerationService;
    @Autowired
    private TourTravelNotesImgService tourTravelNotesImgService;
    @Autowired
    private TourTourismProjectTravelNotesWriteContentService tourTourismProjectTravelNotesWriteContentService;
    @Autowired
    private TourTravelNotesTopicService tourTravelNotesTopicService;
    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Override
    @Transactional
    public void saveDraft(TourismProjectTravelNotesWriteToWebDto tourismProjectTravelNotesWriteDto) {

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite =
                tourismProjectTravelNotesWriteService.getById(tourismProjectTravelNotesWriteDto.getId());

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteSave =
                MyModelUtil.copyTo(tourismProjectTravelNotesWriteDto, TourismProjectTravelNotesWrite.class);

        //判断imgUrls是否为空，不为空的话，则把第一张图作为列表图
        if (CollectionUtils.isNotEmpty(tourismProjectTravelNotesWriteDto.getImgUrls())) {
            tourismProjectTravelNotesWriteSave.setTourismUrl(tourismProjectTravelNotesWriteDto.getImgUrls().get(0));
        }

        List<TourTravelNotesTopicRelation> tourTravelNotesTopicRelationList = new ArrayList<>();
        List<TourTravelNotesImg> tourTravelNotesImgList = new ArrayList<>();
        //需要新增的话题
        List<Map<String, String>> ls = tourismProjectTravelNotesWriteDto.getTopics().stream().filter(j -> ObjectUtil.isEmpty(j.get("id"))).collect(Collectors.toList());
        ArrayList<TourTravelNotesTopic> objects = new ArrayList<>();
        if(!ls.isEmpty()){
            for (Map<String, String> l : ls) {
                String s = l.get("name");
                TourTravelNotesTopic tourTravelNotesTopic = new TourTravelNotesTopic();
                tourTravelNotesTopic.setId(idGenerator.nextLongId());
                tourTravelNotesTopic.setName(s);
                tourTravelNotesTopic.setEnable(1);
                tourTravelNotesTopic.setHotValue(0);
                objects.add(tourTravelNotesTopic);
            }
            tourTravelNotesTopicService.saveNewBatch(objects);
        }

        List<String> topics = tourismProjectTravelNotesWriteDto.getTopics().stream().map(i->i.get("name")).collect(Collectors.toList());
        List<TourTravelNotesTopic> lls = new ArrayList<>();
        if(!topics.isEmpty()){
            lls=tourTravelNotesTopicService.lambdaQuery().in(TourTravelNotesTopic::getName, topics).list();
        }
        //判断是新增还是更新
        if (tourismProjectTravelNotesWrite == null) {
            //新增
            //草稿为下架状态
            tourismProjectTravelNotesWriteSave.setUnmountState(UnmountState.DELIST);
            TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteNew = tourismProjectTravelNotesWriteService.saveNew(tourismProjectTravelNotesWriteSave);

            //对游记提及的关联用户信息进行关联游记id
            tourismProjectTravelNotesWriteDto.getMentions().forEach(item -> {
                item.setTravelNotesId(tourismProjectTravelNotesWriteNew.getId());
            });

            //对游记中提及的话题进行关联游记id
            lls.forEach(j->{
                TourTravelNotesTopicRelation tourTravelNotesTopicRelationNew = new TourTravelNotesTopicRelation();
                tourTravelNotesTopicRelationNew.setTopicName(j.getName());
                tourTravelNotesTopicRelationNew.setTopicId(j.getId());
                tourTravelNotesTopicRelationNew.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
                tourTravelNotesTopicRelationList.add(tourTravelNotesTopicRelationNew);
            });

            if(!objects.isEmpty()){
                for (TourTravelNotesTopic object : objects) {
                    TourTravelNotesTopicRelation tourTravelNotesTopicRelation = new TourTravelNotesTopicRelation();
                    tourTravelNotesTopicRelation.setTopicName(object.getName());
                    tourTravelNotesTopicRelation.setTopicId(object.getId());
                    tourTravelNotesTopicRelation.setTravelNotesId(tourismProjectTravelNotesWriteNew.getId());
                    tourTravelNotesTopicRelationList.add(tourTravelNotesTopicRelation);
                }
            }

            //构建游记中的图片数据
            tourismProjectTravelNotesWriteDto.getImgUrls().forEach(y->{
                TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
                tourTravelNotesImg.setImgUrl(y);
                tourTravelNotesImg.setTravelNotesId(tourismProjectTravelNotesWriteNew.getId());
                tourTravelNotesImgList.add(tourTravelNotesImg);
            });
        } else {
            //修改
            //草稿为下架状态
            tourismProjectTravelNotesWriteSave.setUnmountState(UnmountState.DELIST);
            tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWriteSave);
            //对游记提及的关联用户信息进行关联游记id
            tourismProjectTravelNotesWriteDto.getMentions().forEach(item -> {
                item.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
            });
            TourTravelNotesMentionUser tourTravelNotesMentionUser = new TourTravelNotesMentionUser();
            tourTravelNotesMentionUser.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
            tourTravelNotesMentionUserService.removeBy(tourTravelNotesMentionUser);
            //移除原来关联的话题
            TourTravelNotesTopicRelation tourTravelNotesTopicRelation = new TourTravelNotesTopicRelation();
            tourTravelNotesTopicRelation.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
            tourTravelNotesTopicRelationService.removeBy(tourTravelNotesTopicRelation);

            //对游记中提及的话题进行关联游记id
            lls.forEach(j->{
                TourTravelNotesTopicRelation tourTravelNotesTopicRelationNew = new TourTravelNotesTopicRelation();
                tourTravelNotesTopicRelationNew.setTopicName(j.getName());
                tourTravelNotesTopicRelationNew.setTopicId(j.getId());
                tourTravelNotesTopicRelationNew.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
                tourTravelNotesTopicRelationList.add(tourTravelNotesTopicRelationNew);
            });

            //移除原来图片中的地址数据
            TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
            tourTravelNotesImg.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
            tourTravelNotesImgService.removeBy(tourTravelNotesImg);

            //构建现有的游记图片数据
            tourismProjectTravelNotesWriteDto.getImgUrls().forEach(y->{
                TourTravelNotesImg tourTravelNotesImgNew = new TourTravelNotesImg();
                tourTravelNotesImgNew.setImgUrl(y);
                tourTravelNotesImgNew.setTravelNotesId(tourismProjectTravelNotesWriteSave.getId());
                tourTravelNotesImgList.add(tourTravelNotesImgNew);
            });
        }
        //保存游记中提及的用户
        List<TourTravelNotesMentionUser> tourTravelNotesMentionUserList = MyModelUtil.copyCollectionTo(tourismProjectTravelNotesWriteDto.getMentions(), TourTravelNotesMentionUser.class);
        tourTravelNotesMentionUserService.saveBatch(tourTravelNotesMentionUserList);
        //保存游记中提及的话题
        tourTravelNotesTopicRelationService.saveNewBatch(tourTravelNotesTopicRelationList);
        //保存游记中的图片
        tourTravelNotesImgService.saveNewBatch(tourTravelNotesImgList);

        //判断内容是否为空
        if (tourismProjectTravelNotesWriteDto.getTourTourismProjectTravelNotesWriteContentDto() != null) {
            TourTourismProjectTravelNotesWriteContentDto tourTourismProjectTravelNotesWriteContentDto = 
                    tourismProjectTravelNotesWriteDto.getTourTourismProjectTravelNotesWriteContentDto();
            TourTourismProjectTravelNotesWriteContent tourTourismProjectTravelNotesWriteContent =
                    MyModelUtil.copyTo(tourTourismProjectTravelNotesWriteContentDto, TourTourismProjectTravelNotesWriteContent.class);
                tourTourismProjectTravelNotesWriteContent.setAssociationId(tourismProjectTravelNotesWriteSave.getId());
            tourTourismProjectTravelNotesWriteContent.setId(null);
            tourismTravelNotesContentWriteService.removeByAssociationId(tourismProjectTravelNotesWriteSave.getId());
            //查询关联数据的id,根据id进行更新数据表的数据
            tourTourismProjectTravelNotesWriteContentService.saveNew(tourTourismProjectTravelNotesWriteContent);
        }


    }

    @Override
    @Transactional
    public void removeByDraftId(String writeId){
        //删除游记主表
        tourismProjectTravelNotesWriteService.remove(Long.valueOf(writeId));
        //删除游记内容表
        tourismTravelNotesContentWriteService.removeByAssociationId(Long.valueOf(writeId));
        //删除游记中提及的用户关系表
        TourTravelNotesMentionUser tourTravelNotesMentionUser = new TourTravelNotesMentionUser();
        tourTravelNotesMentionUser.setTravelNotesId(Long.valueOf(writeId));
        tourTravelNotesMentionUserService.removeBy(tourTravelNotesMentionUser);
        //删除游记中提及的话题关系表
        TourTravelNotesTopicRelation tourTravelNotesTopicRelation = new TourTravelNotesTopicRelation();
        tourTravelNotesTopicRelation.setTravelNotesId(Long.valueOf(writeId));
        tourTravelNotesTopicRelationService.removeBy(tourTravelNotesTopicRelation);
        //删除游记中的图片信息
        TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
        tourTravelNotesImg.setTravelNotesId(Long.valueOf(writeId));
        tourTravelNotesImgService.removeBy(tourTravelNotesImg);
    }

    @Override
    public List<TourismProjectTravelNotesWrite> getDraftList(TourismProjectTravelNotesWriteDetailPageDto pageDto){

        Long userId = TokenData.takeFromRequest().getUserId();
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = new TourismProjectTravelNotesWrite();
        tourismProjectTravelNotesWrite.setCreateUserId(userId);
        tourismProjectTravelNotesWrite.setState(pageDto.getType());
        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProjectTravelNotesWrite.class);
        if(pageDto.getPageSize() != null && pageDto.getPageNum() != null){
            PageMethod.startPage(pageDto.getPageNum(), pageDto.getPageSize(), true);
        }
        //查询已发布状态的状态，则需要state为3并且上下架状态为上架
        if(pageDto.getType() == 3){
            tourismProjectTravelNotesWrite.setUnmountState(UnmountState.LISTING);
        }
        List<TourismProjectTravelNotesWrite> tourismProjectTravelNotesWriteList =
                tourismProjectTravelNotesWriteService.getTourismProjectTravelNotesWriteList(tourismProjectTravelNotesWrite, orderBy);

        return tourismProjectTravelNotesWriteList;
    }

    @Override
    @Transactional
    public ResponseResult<Void> publishDraft(TourismProjectTravelNotesWriteToWebDto tourismProjectTravelNotesWriteDto){
        String errorMessage = MyCommonUtil.getModelValidationError(tourismProjectTravelNotesWriteDto, UpdateGroup.class);
        if (errorMessage != null) {
            return ResponseResult.success(null);
        }
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite =
                BeanUtil.toBean(tourismProjectTravelNotesWriteDto, TourismProjectTravelNotesWrite.class);

        //校验该游记是否为审核中和已发布状态
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteVerify =
                tourismProjectTravelNotesWriteService.getById(tourismProjectTravelNotesWriteDto.getId());

        if(tourismProjectTravelNotesWriteVerify != null){
            if(tourismProjectTravelNotesWriteVerify.getState().equals(AuditState.UNAUDITSTATE)) {
                return ResponseResult.error(ErrorCodeEnum.INVALID_STATUS_ARGUMENT, "该游记状态为:正在审核中,请撤销后进行操作");
            }else if(tourismProjectTravelNotesWriteVerify.getState() .equals(AuditState.SUCCEEDAUDIT)){
                return ResponseResult.error(ErrorCodeEnum.INVALID_STATUS_ARGUMENT, "该游记状态为:已发布成功,请下架后进行操作");
            }
        }

        //判断imgUrls是否为空，不为空的话，则把第一张图作为列表图
        if (CollectionUtils.isNotEmpty(tourismProjectTravelNotesWriteDto.getImgUrls())) {
            tourismProjectTravelNotesWrite.setTourismUrl(tourismProjectTravelNotesWriteDto.getImgUrls().get(0));
        }

        // 图片审核
        List<String> imageList = tourismProjectTravelNotesWriteDto.getImgUrls();
//        if(tourismProjectTravelNotesWrite.getTravelNotesBanner()!=null){
//            imageList.add(tourismProjectTravelNotesWrite.getTravelNotesBanner());
//        }
        Boolean imageResult = huaweiCloudModerationService.runImageModeration(imageList);
        // 文案审核
        List<String> titleList = new ArrayList<>();

        //提取出从表内容
        TourTourismProjectTravelNotesWriteContentDto tourTourismProjectTravelNotesWriteContentDto =
                tourismProjectTravelNotesWriteDto.getTourTourismProjectTravelNotesWriteContentDto();
        if(tourTourismProjectTravelNotesWriteContentDto != null && StringUtils.isNotBlank(tourTourismProjectTravelNotesWriteContentDto.getContent())) {
            titleList.add(tourTourismProjectTravelNotesWriteContentDto.getContent());
            Boolean textResult = huaweiCloudModerationService.runTextModeration(titleList);
            String auditReson = "";
            if (imageResult && textResult) {
                tourismProjectTravelNotesWrite.setAutoAuditStatus(1);
                auditReson = "图文审核通过";
            } else {
                tourismProjectTravelNotesWrite.setAutoAuditStatus(2);
                if (!imageResult) {
                    auditReson = "图片审核未通过：可能设计暴恐、色情、违禁、辱骂等内容;";
                }
                if (!textResult) {
                    auditReson += "文案审核未通过：可能设计暴恐、色情、违禁、辱骂等内容;";
                }
            }
            tourismProjectTravelNotesWrite.setAutoRejectReason(auditReson);
        }

        tourismProjectTravelNotesWrite.setState(AuditState.UNAUDITSTATE);
        List<TourTravelNotesTopicRelation> tourTravelNotesTopicRelationList = new ArrayList<>();
        List<TourTravelNotesImg> tourTravelNotesImgList = new ArrayList<>();

        List<TourTravelNotesTopic> list = new ArrayList<>();
        //对dto的id进行判断，如果数据表中查不到该id，则为新增;否则为修改
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite1 =
                tourismProjectTravelNotesWriteService.getById(tourismProjectTravelNotesWriteDto.getId());


        if(tourismProjectTravelNotesWrite1 == null) {
            //新增
            tourismProjectTravelNotesWriteService.saveNew(tourismProjectTravelNotesWrite);
        }else{//草稿
            if(!tourismProjectTravelNotesWrite1.getCreateUserId().equals(TokenData.takeFromRequest().getUserId())){
                return ResponseResult.error(ErrorCodeEnum.DATA_SAVE_FAILED);
            }
            tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWrite);
        }

        //新增的话题
        tourismProjectTravelNotesWriteDto.getTopics().forEach(j->{
            String id = j.get("id");
            String name = j.get("name");
            if(ObjectUtil.isEmpty(id)){
                TourTravelNotesTopic tourTravelNotesTopic = new TourTravelNotesTopic();
                tourTravelNotesTopic.setId(idGenerator.nextLongId());
                tourTravelNotesTopic.setName(name);
                tourTravelNotesTopic.setEnable(1);
                tourTravelNotesTopic.setHotValue(0);
                list.add(tourTravelNotesTopic);
            }
        });
        //新增话题
        tourTravelNotesTopicService.saveNewBatch(list);

        //删除游记中提及的用户关系表
        TourTravelNotesMentionUser tourTravelNotesMentionUser = new TourTravelNotesMentionUser();
        tourTravelNotesMentionUser.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        tourTravelNotesMentionUserService.removeBy(tourTravelNotesMentionUser);

        //对游记提及的关联用户信息进行关联游记id
        tourismProjectTravelNotesWriteDto.getMentions().forEach(item -> {
            item.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        });
        //保存游记中提及的用户
        List<TourTravelNotesMentionUser> tourTravelNotesMentionUserList = MyModelUtil.copyCollectionTo(tourismProjectTravelNotesWriteDto.getMentions(), TourTravelNotesMentionUser.class);
        tourTravelNotesMentionUserService.saveBatch(tourTravelNotesMentionUserList);

        //删除游记中提及的话题关系表
        TourTravelNotesTopicRelation tourTravelNotesTopicRelation = new TourTravelNotesTopicRelation();
        tourTravelNotesTopicRelation.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        tourTravelNotesTopicRelationService.removeBy(tourTravelNotesTopicRelation);

        List<String> topics = tourismProjectTravelNotesWriteDto.getTopics().stream().map(i->i.get("name")).collect(Collectors.toList());
        List<TourTravelNotesTopic> ls = new ArrayList<>();
        if(!topics.isEmpty()){
            ls = tourTravelNotesTopicService.lambdaQuery().in(TourTravelNotesTopic::getName, topics).list();
        }

        //对游记中提及的话题进行关联游记id
        ls.forEach(j->{
            TourTravelNotesTopicRelation tourTravelNotesTopic = new TourTravelNotesTopicRelation();
            tourTravelNotesTopic.setTopicName(j.getName());
            tourTravelNotesTopic.setTopicId(j.getId());
            tourTravelNotesTopic.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
            tourTravelNotesTopicRelationList.add(tourTravelNotesTopic);
        });
        //保存游记中提及的话题
        tourTravelNotesTopicRelationService.saveNewBatch(tourTravelNotesTopicRelationList);


        //移除原来图片中的地址数据
        TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
        tourTravelNotesImg.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        tourTravelNotesImgService.removeBy(tourTravelNotesImg);

        //构建游记中的图片数据
        tourismProjectTravelNotesWriteDto.getImgUrls().forEach(y->{
            TourTravelNotesImg image = new TourTravelNotesImg();
            image.setImgUrl(y);
            image.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
            tourTravelNotesImgList.add(image);
        });
        //保存游记中的图片
        tourTravelNotesImgService.saveNewBatch(tourTravelNotesImgList);

        //删除游记中的内容
        tourismTravelNotesContentWriteService.removeByAssociationId(tourismProjectTravelNotesWriteDto.getId());

        //新增内容
        TourTourismProjectTravelNotesWriteContent tourTourismProjectTravelNotesWriteContent =
                MyModelUtil.copyTo(tourismProjectTravelNotesWriteDto.getTourTourismProjectTravelNotesWriteContentDto(), TourTourismProjectTravelNotesWriteContent.class);
        tourTourismProjectTravelNotesWriteContent.setAssociationId(tourismProjectTravelNotesWrite.getId());
        tourTourismProjectTravelNotesWriteContent.setId(null);
        tourTourismProjectTravelNotesWriteContentService.saveNew(tourTourismProjectTravelNotesWriteContent);

        return ResponseResult.success();
    }
}
