package com.tourism.webadmin.back.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.tourism.common.core.base.dao.BaseDaoMapper;
import com.tourism.common.core.base.service.BaseService;
import com.tourism.common.core.constant.GlobalDeletedFlag;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.back.dao.TourismProjectTravelNotesWriteMapper;
import com.tourism.webadmin.back.model.TourTourismTravelNotesContent;
import com.tourism.webadmin.back.model.TourismProjectTravelNotesWrite;
import com.tourism.webadmin.back.model.TourismTravelNotesContentWrite;
import com.tourism.webadmin.back.model.constant.AuditState;
import com.tourism.webadmin.back.service.TourismProjectTravelNotesWriteService;
import com.tourism.webadmin.back.service.TourismTravelNotesContentWriteService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 发布游记数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
@Service("tourismProjectTravelNotesWriteService")
public class TourismProjectTravelNotesWriteServiceImpl extends BaseService<TourismProjectTravelNotesWrite, Long> implements TourismProjectTravelNotesWriteService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourismProjectTravelNotesWriteMapper tourismProjectTravelNotesWriteMapper;
    @Autowired
    private TourismTravelNotesContentWriteService tourismTravelNotesContentWriteService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TourismProjectTravelNotesWrite> mapper() {
        return tourismProjectTravelNotesWriteMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourismProjectTravelNotesWrite saveNew(TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite) {
        tourismProjectTravelNotesWriteMapper.insert(this.buildDefaultValue(tourismProjectTravelNotesWrite));
        return tourismProjectTravelNotesWrite;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TourismProjectTravelNotesWrite> tourismProjectTravelNotesWriteList) {
        if (CollUtil.isNotEmpty(tourismProjectTravelNotesWriteList)) {
            tourismProjectTravelNotesWriteList.forEach(this::buildDefaultValue);
            tourismProjectTravelNotesWriteMapper.insertList(tourismProjectTravelNotesWriteList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourismProjectTravelNotesWrite saveNewWithRelation(TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite, JSONObject relationData) {
        this.saveNew(tourismProjectTravelNotesWrite);
        this.saveOrUpdateOneToOneRelationData(tourismProjectTravelNotesWrite, relationData);
        return tourismProjectTravelNotesWrite;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite, TourismProjectTravelNotesWrite originalTourismProjectTravelNotesWrite) {
        MyModelUtil.fillCommonsForUpdate(tourismProjectTravelNotesWrite, originalTourismProjectTravelNotesWrite);
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TourismProjectTravelNotesWrite> uw = this.createUpdateQueryForNullValue(tourismProjectTravelNotesWrite, tourismProjectTravelNotesWrite.getId());
        return tourismProjectTravelNotesWriteMapper.update(tourismProjectTravelNotesWrite, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateWithRelation(
            TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite, TourismProjectTravelNotesWrite originalTourismProjectTravelNotesWrite, JSONObject relationData) {
        // tourismProjectTravelNotesWrite 为空的时候，无需修改主表数据。
        if (tourismProjectTravelNotesWrite != null && !this.update(tourismProjectTravelNotesWrite, originalTourismProjectTravelNotesWrite)) {
            return false;
        }
        this.saveOrUpdateOneToOneRelationData(originalTourismProjectTravelNotesWrite, relationData);
        return true;
    }

    private void saveOrUpdateOneToOneRelationData(TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite, JSONObject relationData) {
        // 对于一对一新增或更新，如果主键值为空就新增，否则就更新，同时更新updateTime和updateUserId。
        TourismTravelNotesContentWrite tourismTravelNotesContentWrite = relationData.getObject("tourismTravelNotesContentWrite", TourismTravelNotesContentWrite.class);
        if (tourismTravelNotesContentWrite != null) {
            tourismTravelNotesContentWrite.setAssociationId(tourismProjectTravelNotesWrite.getId());
            tourismTravelNotesContentWriteService.saveNewOrUpdate(tourismTravelNotesContentWrite,
                    tourismTravelNotesContentWriteService::saveNew, tourismTravelNotesContentWriteService::update);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (tourismProjectTravelNotesWriteMapper.deleteById(id) == 0) {
            return false;
        }
        tourismTravelNotesContentWriteService.removeByAssociationId(id);
        return true;
    }

    @Override
    public List<TourismProjectTravelNotesWrite> getTourismProjectTravelNotesWriteList(TourismProjectTravelNotesWrite filter, String orderBy) {
        return tourismProjectTravelNotesWriteMapper.getTourismProjectTravelNotesWriteList(filter, orderBy);
    }

    @Override
    public List<TourismProjectTravelNotesWrite> getTourismProjectTravelNotesWriteListWithRelation(TourismProjectTravelNotesWrite filter, String orderBy) {
        List<TourismProjectTravelNotesWrite> resultList = tourismProjectTravelNotesWriteMapper.getTourismProjectTravelNotesWriteList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public List<TourismTravelNotesContentWrite> parseHTML(TourTourismTravelNotesContent entity) {
        List<TourismTravelNotesContentWrite> notes = new ArrayList<>();
        Document doc = Jsoup.parse(entity.getContent());

        // 获取所有的<p>标签
        Elements paragraphs = doc.select("p");

        for (Element p : paragraphs) {
            TourismTravelNotesContentWrite content = new TourismTravelNotesContentWrite();

            content.setAssociationId(Long.parseLong(entity.getAssociationId()));
            content.setCreateUserId(entity.getCreateUserId());
            content.setCreateTime(entity.getCreateTime());
            content.setUpdateTime(entity.getUpdateTime());
            content.setUpdateUserId(entity.getUpdateUserId());
            content.setDataState(entity.getDataState());

            // 提取文本内容
            String textContent = p.text();
            if (!textContent.trim().isEmpty()) {
                content.setType("sectionContent");
                content.setContent(textContent);
            }

            // 提取图片URL
            Element img = p.selectFirst("img");
            if (img != null) {
                content.setType("image");
                String imageUrl = img.attr("src");
                content.setContent(imageUrl);
            }
            notes.add(content);
        }

        return notes;
    }

    @Override
    public Integer audit(TourismProjectTravelNotesWrite enrity) {
        return tourismProjectTravelNotesWriteMapper.auditTravelNote(enrity);
    }

    @Override
    public List<Long> getMyTravelNoteIds(Long userId) {
        // 根据当前登录用户获取当前用户发布的游记ids
        return tourismProjectTravelNotesWriteMapper.getTravelNoteIds(userId);
    }

    private TourismProjectTravelNotesWrite buildDefaultValue(TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite) {
        if (tourismProjectTravelNotesWrite.getId() == null) {
            tourismProjectTravelNotesWrite.setId(idGenerator.nextLongId());
        }
        MyModelUtil.fillCommonsForInsert(tourismProjectTravelNotesWrite);
        tourismProjectTravelNotesWrite.setDataState(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(tourismProjectTravelNotesWrite, "reason", "");
        MyModelUtil.setDefaultValue(tourismProjectTravelNotesWrite, "travelNotesBanner", "");
        MyModelUtil.setDefaultValue(tourismProjectTravelNotesWrite, "tourismTavelNotesUrl", "");
        MyModelUtil.setDefaultValue(tourismProjectTravelNotesWrite, "state", AuditState.DRAFT);
        return tourismProjectTravelNotesWrite;
    }
}
