package com.testor.module.news.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.module.isRead.model.domain.TSysIsRead;
import com.testor.module.isRead.service.TSysIsReadService;
import com.testor.module.news.model.domain.SysNews;
import com.testor.module.news.model.dto.SysNewsDelParam;
import com.testor.module.news.model.dto.SysNewsParam;
import com.testor.module.news.service.SysNewsService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 新闻模块Controller
 *
 * @author gaobingzhuo@testor.com.cn
 * @date 2022-05-07 14:02:06
 */
@RestController
@RequestMapping("/news")
@Api(value = "SysNews", tags = "新闻模块")
@Slf4j
public class SysNewsController extends SuperController {
    @Autowired
    private SysNewsService sysNewsService;
    @Autowired
    private TSysIsReadService tSysIsReadService;

    /* Generated Method*/
    @ApiOperation(value = "新增 新闻模块", notes = "只需要传标题和内容")
    @PostMapping(value = "/add")
    public BaseResponse<SysNews> addEntity(@RequestBody SysNews addRequest) throws Exception {

        return sysNewsService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取 新闻模块 ", notes = "需要传 新闻Id")
    @GetMapping(value = "/get")
    public BaseResponse<SysNews> getById(String id) throws Exception {
        return sysNewsService.getByIds(id);
    }

    @ApiOperation(value = "获取新闻模块 修改已读未读状态", notes = "需要传 新闻Id 在台账页面调详情")
    @GetMapping(value = "/getIsRead")
    public BaseResponse<SysNews> getIsRead(String id) throws Exception {
        return sysNewsService.getIsRead(id);
    }

    @ApiOperation(value = "修改 新闻模块 ", notes = "需要传新闻id  如果保存草稿 processStatus 等于 4")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody SysNews updateRequest) throws Exception {

        return sysNewsService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 新闻模块 ", notes = "需要传新闻id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody SysNewsDelParam deleteRequest) throws Exception {

        return sysNewsService.deleteEntity(deleteRequest);
    }

    @ApiOperation(value = "物理删除新闻模块", notes = "需要传新闻id")
    @GetMapping("/drop")
    public BaseResponse dropNews(String id) throws Exception {
        BaseResponse<SysNews> response = new BaseResponse<>();
        LambdaQueryWrapper<SysNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysNews::getId, id);
        SysNews one = sysNewsService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException("数据不存在");
        }
        boolean b = sysNewsService.removeById(id);
        return response;
    }

    @ApiOperation(value = "年度新闻数量统计 ", notes = "areaCom 区域公司名称  newCount 区域公司新闻总数  newAvg 基层粮库均值")
    @GetMapping(value = "/getCount")
    public BaseResponse getCount() {

        return sysNewsService.getCount();
    }

    //	@ApiOperation(value = "批量删除新闻模块", notes = "delete SysNews by batch Id")
//	@PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody SysNewsDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<SysNews> sysNewsList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                SysNews data = new SysNews();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                sysNewsList.add(data);
            }
            boolean result = sysNewsService.updateBatchById(sysNewsList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取新闻列表我的发布和草稿", notes = "获取草稿箱时传processStatus=4 ， 获取我的发布不需要传参数")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<SysNews>> listEntity(SysNewsParam param, String startTime, String endTime) {

        return sysNewsService.listEntity(param, startTime, endTime);
    }

    @ApiOperation(value = "获取新闻模块列表", notes = "时间查询条件 startTime 开始时间  endTime 结束时间  ")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<SysNews>> listAllEntity(SysNewsParam param, String startTime, String endTime, String levels) {
        BaseResponse<BaseResponseList<SysNews>> baseResponse = new BaseResponse<>();
        BaseResponseList<SysNews> baseResponseList = new BaseResponseList<>();
        String loginUserId = ContextUtils.getLoginUserId();
        if ("1".equals(param.getIsRead())) {
            //获取已读数据
            String[] split = levels.split(",");
            List<String> list = Arrays.asList(split);
            IPage<SysNews> read = sysNewsService.getRead(param, startTime+" 00:00:00", endTime+" 23:59:59", list, loginUserId);
            read.getRecords().stream().forEach(item->{
                item.setIsRead("1");
            });
            baseResponseList.setData(read.getRecords());
            baseResponseList.setTotal(read.getTotal());
            baseResponse.setData(baseResponseList);
            return baseResponse;
        }
        if ("0".equals(param.getIsRead())) {
            // 获取未读数据
            String[] split = levels.split(",");
            List<String> list = Arrays.asList(split);
            IPage<SysNews> unRead = sysNewsService.getUnRead(param, startTime+" 00:00:00", endTime+" 23:59:59", list, loginUserId);
            baseResponseList.setData(unRead.getRecords());
            baseResponseList.setTotal(unRead.getTotal());
            baseResponse.setData(baseResponseList);
            return baseResponse;
        }
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<SysNews> resultPage = new Page<>(page, limit);
        QueryWrapper<SysNews> queryWrapper = this.createQuery(param, startTime, endTime, levels);
        Page<SysNews> resultList = sysNewsService.page(resultPage, queryWrapper);


        //判断已读未读数据
        List<SysNews> records = resultList.getRecords();
        if (records.size() == 0) {
            baseResponseList.setData(records);
            baseResponseList.setTotal(records.size());
            baseResponse.setData(baseResponseList);
            return baseResponse;
        }
        QueryWrapper<TSysIsRead> wrapper = new QueryWrapper<>();
        List<String> idList = new ArrayList<>();
        records.stream().forEach(item -> {
            String id = item.getId();
            idList.add(id);
        });
        wrapper.in(TSysIsRead.ARTICLE_ID, idList).eq(TSysIsRead.USER_ID, loginUserId);
        List<TSysIsRead> list = tSysIsReadService.list(wrapper);

        records.stream().forEach(p -> {
            p.setIsRead("0");
            list.stream().forEach(r -> {
                if ((p.getId().equals(r.getArticleId())) && (r.getUserId().equals(loginUserId))) {
                    p.setIsRead(r.getIsRead());
                }
            });
        });
        if ("0".equals(param.getIsRead())) {
            records = records.stream().filter(item -> item.getIsRead().equals("0")).collect(Collectors.toList());
        } else if ("1".equals(param.getIsRead())) {
            records = records.stream().filter(item -> item.getIsRead().equals("1")).collect(Collectors.toList());
        }

//        records = records.stream().sorted(Comparator.comparing(p -> p.getIsRead())).collect(Collectors.toList());
        records = records.stream()
                .sorted(Comparator.comparing(SysNews::getReleaseTime).reversed()
                        .thenComparing(SysNews::getIsRead)
                )
                .collect(Collectors.toList());

        //返回数据
        if ("0".equals(param.getIsRead()) || "1".equals(param.getIsRead())) {
            baseResponseList.setTotal(records.size());
        } else {
            baseResponseList.setTotal(resultList.getTotal());
        }
        baseResponseList.setData(records);
//        baseResponseList.setData(resultList.getRecords());
//        baseResponseList.setTotal(records.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }
    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<SysNews> createQuery(SysNewsParam queryParam, String startTime, String endTime, String levels) {
        QueryWrapper<SysNews> queryWrapper = new QueryWrapper<>();
        if (levels != null) {
            String[] split = levels.split(",");
            queryWrapper.in("\"level\"", split);
        }
        if (!StringUtils.isEmpty(startTime)) {
            String start = startTime + " 00:00:00";
            queryWrapper.ge("release_time", start);
        }
        if (!StringUtils.isEmpty(endTime)) {
            String end = endTime + " 23:59:59";
            queryWrapper.le("release_time", end);
        }
        queryWrapper.orderByDesc("release_time");
        if (StringHelper.isNotEmpty(queryParam.getCreateBy())) {
            queryWrapper.eq(SysNews.CREATE_BY, queryParam.getCreateBy());
        }
        if (StringHelper.isNotEmpty(queryParam.getReleaseUnit())) {
            queryWrapper.eq(SysNews.RELEASE_UNIT, queryParam.getReleaseUnit());
        }
        if (StringHelper.isNotEmpty(queryParam.getTitle())) {
            queryWrapper.like(SysNews.TITLE, queryParam.getTitle());
        }
        if (StringHelper.isNotEmpty(queryParam.getContent())) {
            queryWrapper.eq(SysNews.CONTENT, queryParam.getContent());
        }
//		if(StringHelper.isNotEmpty(queryParam.getIsRead())){
//			queryWrapper.eq(SysNews.IS_READ,queryParam.getIsRead());
//		}
//		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
        queryWrapper.eq(SysNews.PROCESS_STATUS, "5");
        queryWrapper.ne(SysNews.PROCESS_STATUS, "6");
//		}
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(SysNews.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(SysNews.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getRejectOpinion())) {
            queryWrapper.eq(SysNews.REJECT_OPINION, queryParam.getRejectOpinion());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(SysNews.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(SysNews.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(SysNews.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(SysNews.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
