package com.yida.data.school.news.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.school.EduSchoolManuscript;
import com.yida.data.common.core.entity.school.EduSchoolManuscriptLabel;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.school.news.service.EduSchoolManuscriptLabelService;
import com.yida.data.school.news.service.EduSchoolManuscriptService;
import com.yida.data.school.vo.index.ManuscriptPageInfoVO;
import com.yida.data.school.vo.news.AddManuscriptProgress;
import com.yida.data.system.feign.RemoteDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Controller
 *
 * @author zhanghaijun
 * @date 2021-07-19 17:21:58
 */
@Api(tags = "通知咨询-稿件")
@Slf4j
@RestController
@RequestMapping("/news/manuscript")
@RequiredArgsConstructor
public class EduSchoolManuscriptController {

    private final EduSchoolManuscriptService eduSchoolManuscriptService;
    private final EduSchoolManuscriptLabelService labelService;

    private final RemoteDeptService remoteDeptService;
    private final RedisService redisService;

    @ApiOperation("分页查询稿件列表")
    @GetMapping("/listManuscriptPage")
    public ResultBean<IPage<ManuscriptPageInfoVO>> listManuscriptPage(
        @ApiParam("学校id") @RequestParam(required = false) Long schoolId,
        @ApiParam("关键词") @RequestParam(required = false) String keyword,
        @ApiParam("发布人") @RequestParam(required = false) String author,
        @ApiParam("发布时间(yyyy-MM-dd)") @RequestParam(required = false) String publishDate,
        @ApiParam("发布途径，0-新闻，1-公告，2-公众号") @RequestParam(required = false) Integer path,
        @ApiParam("稿件类型，0-存草稿，1-待发送，2-已发送") Integer status,
        @ApiParam("不查询得稿件Id") @RequestParam(required = false) Long notShowId,
        @ApiParam("稿件类别，0-资讯，1-安全教育,默认0,2-政策") @RequestParam(required = false, defaultValue = "0") Integer type,
        @ApiParam("标签") @RequestParam(required = false) Integer label,
        @ApiParam("当前页码，默认1") @RequestParam(defaultValue = "1") Integer pageNum,
        @ApiParam("页面大小，默认10") @RequestParam(defaultValue = "10") Integer pageSize) {
        if (schoolId == null) {
            schoolId = FebsUtil.getTopDeptId();
        }
        return ResultBean.buildSuccess(eduSchoolManuscriptService.listManuscriptPage(new Page(pageNum,
            pageSize), schoolId, keyword, author, publishDate, path, notShowId, type, status, label));
    }

    @ApiOperation("保存、编辑稿件")
    @PostMapping("/saveManuscript")
    public ResultBean<AddManuscriptProgress> saveManuscript(@RequestBody EduSchoolManuscript manuscript) {
        if (manuscript.getSchoolId() == null) {
            CurrentUser currentUser = FebsUtil.getCurrentUser();
            if (Objects.nonNull(currentUser.getMainDeptId())) {
                manuscript.setSchoolId(currentUser.getMainDeptId());
            } else {
                manuscript.setSchoolId(FebsUtil.getTopDeptId());
            }
        }
        String key = UUID.fastUUID().toString();
        eduSchoolManuscriptService.saveManuscript(manuscript, key);
        return ResultBean.buildSuccess(AddManuscriptProgress.builder().key(key).finish(0).build());
    }

    @ApiOperation("获取增加稿件进度")
    @GetMapping("/getAddManuscriptProgress")
    public ResultBean<AddManuscriptProgress> getAddManuscriptProgress(@ApiParam("操作标识") String key) {
        return ResultBean
            .buildSuccess((AddManuscriptProgress) redisService.hget(CachePrefixConstant.ADD_MANUSCRIPT_PROGRESS, key));
    }

    @ApiOperation("稿件详情")
    @GetMapping("/getManuscript")
    public ResultBean<EduSchoolManuscript> saveManuscript(@ApiParam("稿件id") Long manuscriptId) {
        EduSchoolManuscript byId = eduSchoolManuscriptService.getById(manuscriptId);
        List<EduSchoolManuscriptLabel> list = labelService.list(
            Wrappers.query(new EduSchoolManuscriptLabel()).lambda().eq(EduSchoolManuscriptLabel::getManuscriptId, byId.getId()));
        List<Long> labelIds = new ArrayList<>();
        for (EduSchoolManuscriptLabel label : list) {
            labelIds.add(label.getLabel());
        }
        byId.setTags(labelIds);
        return ResultBean.buildSuccess(byId);
    }

    @ApiOperation("删除稿件")
    @PostMapping("/delManuscriptBatch")
    public ResultBean delManuscriptBatch(@RequestBody List<Long> ids) {
        eduSchoolManuscriptService.delManuscript(ids);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("撤回稿件")
    @PostMapping("/cancelManuscriptBatch")
    public ResultBean<String> cancelManuscriptBatch(@RequestParam Long id) {
        eduSchoolManuscriptService.cancelManuscriptBatch(id);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("根据类型和名称查询稿件列表")
    @GetMapping("/listManuscript")
    public ResultBean<List<EduSchoolManuscript>> listManuscript(@RequestParam(required = false) Long schoolId,
        @ApiParam("名称") @RequestParam(required = false) String name,
        @ApiParam("发布途径，0-新闻，1-公告，2-公众号") @RequestParam(required = false) Integer path,
        @ApiParam("0-资讯，1-安全教育,默认0，2-政策") @RequestParam(required = false, defaultValue = "0") Integer type,
        @ApiParam("0-存草稿，1-待发送，2-已发送") @RequestParam(required = false) Integer status) {
        if (schoolId == null) {
            CurrentUser currentUser = FebsUtil.getCurrentUser();
            if (currentUser.getDeptType() == 0) {
                schoolId = currentUser.getDeptId();
            }
        }
        return ResultBean.buildSuccess(eduSchoolManuscriptService.listManuscript(schoolId, name, path, type, status));
    }

    @ApiOperation("查询校园资讯数量")
    @GetMapping("/countManuscript")
    public ResultBean<Integer> countManuscript(String startDate, String endDate, Integer type) {
        List<Long> schoolIds = remoteDeptService.getSchoolByArea(null, null).getData().stream().map(Dept::getDeptId).collect(
            Collectors.toList());
        return ResultBean.buildSuccess(
            CollUtil.isNotEmpty(schoolIds) ? (int) eduSchoolManuscriptService.count(Wrappers.<EduSchoolManuscript>lambdaQuery()
                .between(EduSchoolManuscript::getCreateDate, LocalDateTimeUtil.parseDate(startDate).atStartOfDay(),
                    LocalDateTimeUtil.parseDate(endDate).atTime(LocalTime.MAX))
                .in(EduSchoolManuscript::getSchoolId, schoolIds)
                .eq(EduSchoolManuscript::getType, type)) : 0);
    }
}
