package com.zhiqiyun.open.mvc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiqiyun.open.annotation.Permission;
import com.zhiqiyun.open.core.models.sentiment.SentimentSpiderEvent;
import com.zhiqiyun.open.core.models.sentiment.SentimentSpiderResult;
import com.zhiqiyun.open.core.models.sentiment.SentimentSpiderSiteRule;
import com.zhiqiyun.open.core.models.user.OauthInfo;
import com.zhiqiyun.open.core.service.*;
import com.zhiqiyun.open.mvc.Result;
import com.zhiqiyun.open.mvc.params.sentiment.*;
import com.zhiqiyun.open.utils.DateUtil;
import com.zhiqiyun.open.utils.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sentiment/spider")
public class SentimentSpiderController {

    @Autowired
    private SentimentSpiderEventService sentimentSpiderEventService;

    @Autowired
    private SentimentSpiderRuleService sentimentSpiderRuleService;

    @Autowired
    private SentimentSpiderResultService sentimentSpiderResultService;

    @Autowired
    private OauthService oauthService;

    @Autowired
    private SequenceService sequenceService;

    @Permission(value = "sentiment.spider.rule.find", tags = "查询采集网站规则")
    @PostMapping("/rule/findPage")
    public Result findRulePage(@RequestBody QuerySpiderSiteRuleParam param) {
        QueryWrapper<SentimentSpiderSiteRule> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSiteName())) {
            wrapper.like("site_name", param.getSiteName());
        }

        Page<SentimentSpiderSiteRule> page = param.getPage();
        page.addOrder(OrderItem.desc("id"));

        Page<SentimentSpiderSiteRule> resultData = this.sentimentSpiderRuleService.page(page, wrapper);

        return Result.instance(Result.Code.SUCCESS).setData(resultData);
    }

    @ResponseBody
    @Permission(tags = "通过关键词查询采集网站规则", writeLog = false)
    @PostMapping("/rule/findSelectByKeyword")
    public Result findSelectRuleByKeyword(String keyword) {
        QueryWrapper<SentimentSpiderSiteRule> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("site_name", keyword);
            queryWrapper.or();
            queryWrapper.like("id", keyword);
        }
        queryWrapper.last("limit 10");
        queryWrapper.orderByDesc("id");

        List<SentimentSpiderSiteRule> listData = this.sentimentSpiderRuleService.list(queryWrapper);
        return Result.instance(Result.Code.SUCCESS).setData(listData);
    }

    @ResponseBody
    @Permission(tags = "通过关键词查询事件规则", writeLog = false)
    @PostMapping("/event/findSelectByKeyword")
    public Result findSelectEventByKeyword(String keyword) {
        QueryWrapper<SentimentSpiderEvent> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("event_title", keyword);
            queryWrapper.or();
            queryWrapper.like("keywords", keyword);
            queryWrapper.or();
            queryWrapper.like("id", keyword);
        }
        queryWrapper.last("limit 10");
        queryWrapper.orderByDesc("id");

        List<SentimentSpiderEvent> listData = this.sentimentSpiderEventService.list(queryWrapper);
        return Result.instance(Result.Code.SUCCESS).setData(listData);
    }

    @Permission(value = "sentiment.spider.rule.add", tags = "添加采集网站规则")
    @PostMapping("/rule/save")
    public Result saveRule(@Valid @RequestBody SaveSpiderSiteRuleParam param) {

        SentimentSpiderSiteRule entity = new SentimentSpiderSiteRule();
        BeanUtils.copyProperties(param, entity);

        OauthInfo oauthInfo = this.oauthService.getAuth(ServletContext.getAccessToken());

        entity.setCreatedTime(DateUtil.current());
        entity.setCreatedBy(oauthInfo.getId());

        entity.setUpdatedTime(DateUtil.current());
        entity.setUpdatedBy(oauthInfo.getId());
        entity.setId(this.sequenceService.nextId());

        this.sentimentSpiderRuleService.save(entity);

        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.rule.edit", tags = "修改采集网站规则")
    @PostMapping("/rule/updateById")
    public Result updateRuleById(Long id, @Valid @RequestBody SaveSpiderSiteRuleParam param) {
        SentimentSpiderSiteRule entity = new SentimentSpiderSiteRule();
        BeanUtils.copyProperties(param, entity);

        OauthInfo oauthInfo = this.oauthService.getAuth(ServletContext.getAccessToken());

        entity.setUpdatedBy(oauthInfo.getId());
        entity.setUpdatedTime(DateUtil.current());
        entity.setId(id);

        this.sentimentSpiderRuleService.updateById(entity);

        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.rule.delete", tags = "采集网站规则删除")
    @PostMapping("/rule/deleteByIds")
    public Result deleteRuleByIds(@RequestBody List<Long> ids) {
        this.sentimentSpiderRuleService.removeByIds(ids);
        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.event.find", tags = "查询舆情事件")
    @PostMapping("/event/findPage")
    public Result findEventPage(@RequestBody QuerySpiderEventParam param) {
        QueryWrapper<SentimentSpiderEvent> wrapper = new QueryWrapper<>();
        if (param.getSiteRuleId() != null) {
            wrapper.eq("site_rule_id", param.getSiteRuleId());
        }
        if (StringUtils.isNotBlank(param.getEventTitle())) {
            wrapper.like("event_title", param.getEventTitle());
        }
        if (StringUtils.isNotBlank(param.getKeywords())) {
            wrapper.like("keywords", param.getKeywords());
        }

        Page<SentimentSpiderEvent> page = param.getPage();
        page.addOrder(OrderItem.desc("id"));

        Page<SentimentSpiderEvent> resultData = this.sentimentSpiderEventService.page(page, wrapper);
        for (SentimentSpiderEvent event : resultData.getRecords()) {
            SentimentSpiderSiteRule rule = this.sentimentSpiderRuleService.getById(event.getSiteRuleId());
            event.setRule(rule);
            event.setStatus(this.sentimentSpiderEventService.getStatus(event.getId()));
        }

        return Result.instance(Result.Code.SUCCESS).setData(resultData);
    }

    @Permission(value = "sentiment.spider.event.add", tags = "添加舆情事件")
    @PostMapping("/event/save")
    public Result saveEvent(@Valid @RequestBody SaveSpiderEventParam param) throws Exception {

        SentimentSpiderEvent entity = new SentimentSpiderEvent();
        BeanUtils.copyProperties(param, entity);

        OauthInfo oauthInfo = this.oauthService.getAuth(ServletContext.getAccessToken());

        entity.setCreatedTime(DateUtil.current());
        entity.setCreatedBy(oauthInfo.getId());

        entity.setUpdatedTime(DateUtil.current());
        entity.setUpdatedBy(oauthInfo.getId());
        entity.setId(this.sequenceService.nextId());

        this.sentimentSpiderEventService.save(entity);

        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.event.edit", tags = "修改舆情事件")
    @PostMapping("/event/updateById")
    public Result updateEventById(Long id, @Valid @RequestBody SaveSpiderEventParam param) {
        SentimentSpiderEvent entity = new SentimentSpiderEvent();
        BeanUtils.copyProperties(param, entity);

        OauthInfo oauthInfo = this.oauthService.getAuth(ServletContext.getAccessToken());

        entity.setUpdatedBy(oauthInfo.getId());
        entity.setUpdatedTime(DateUtil.current());
        entity.setId(id);

        this.sentimentSpiderEventService.updateById(entity);

        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.event.delete", tags = "删除舆情事件")
    @PostMapping("/event/deleteByIds")
    public Result deleteEventByIds(@RequestBody List<Long> ids) {
        this.sentimentSpiderEventService.removeByIds(ids);
        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }


    @Permission(value = "sentiment.spider.event.start", tags = "启动舆情事件监控")
    @PostMapping("/event/startSpider")
    public Result startSpider(@RequestBody List<Long> ids) {
        List<SentimentSpiderEvent> listData = this.sentimentSpiderEventService.listByIds(ids);
        for (SentimentSpiderEvent event : listData) {
            SentimentSpiderSiteRule rule = this.sentimentSpiderRuleService.getById(event.getSiteRuleId());
            event.setRule(rule);
            this.sentimentSpiderEventService.start(event);
        }
        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }

    @Permission(value = "sentiment.spider.event.stop", tags = "停止舆情事件监控")
    @PostMapping("/event/stopSpider")
    public Result stopSpider(@RequestBody List<Long> ids) {
        List<SentimentSpiderEvent> listData = this.sentimentSpiderEventService.listByIds(ids);
        for (SentimentSpiderEvent event : listData) {
            this.sentimentSpiderEventService.stop(event);
        }
        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }


    @Permission(value = "sentiment.spider.event.find", tags = "查询采集结果")
    @PostMapping("/result/findPage")
    public Result findResultPage(@RequestBody QuerySpiderResultParam param) {
        QueryWrapper<SentimentSpiderResult> wrapper = new QueryWrapper<>();
        if (param.getEventId() != null) {
            wrapper.eq("event_id", param.getEventId());
        }
        if (param.getSiteRuleId() != null) {
            wrapper.eq("site_rule_id", param.getSiteRuleId());
        }
        if (StringUtils.isNotBlank(param.getTitle())) {
            wrapper.like("title", param.getTitle());
        }

        wrapper.select("id", "event_id", "site_rule_id", "url", "title", "keywords", "description", "fragments", "spider_time", "update_time");

        Page<SentimentSpiderResult> page = param.getPage();
        page.addOrder(OrderItem.desc("update_time"));

        Page<SentimentSpiderResult> resultData = this.sentimentSpiderResultService.page(page, wrapper);

        return Result.instance(Result.Code.SUCCESS).setData(resultData);
    }
}
