package com.testor.module.news.service.impl;

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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.isRead.model.domain.TSysIsRead;
import com.testor.module.isRead.service.TSysIsReadService;
import com.testor.module.news.dao.SysNewsDao;
import com.testor.module.news.model.domain.AcceptNewsCount;
import com.testor.module.news.model.domain.NewStatice;
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.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
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 com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 新闻模块Service业务层处理
 *
 * @author gaobingzhuo@testor.com.cn
 * @date 2022-05-07 14:02:06
 */
@Service
public class SysNewsServiceImpl extends SuperServiceImpl<SysNewsDao, SysNews> implements SysNewsService {
    @Autowired(required = false)
    private SysNewsDao sysNewsDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysNewsService sysNewsService;
    @Autowired
    private TSysIsReadService tSysIsReadService;

    @Override
    public BaseResponse<SysNews> addEntity(SysNews addRequest) throws Exception {
        BaseResponse<SysNews> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            String loginName = "";
            try {
                loginName = ContextUtils.getLoginUser().getLoginName();
            } catch (Exception e) {
                throw new BusinessException("未登录");
            }
            String id = IdHelper.getId32bit();
            SysNews data = BeanHelper.beanToBean(addRequest, SysNews.class);
            data.setId(id);
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getLoginName, loginName);
            wrapper.eq(SysUser::getStatus, "0");
            SysUser sysUser = sysUserService.getOne(wrapper);
            LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysOrg::getOrgId, sysUser.getOrgId());
            queryWrapper.eq(SysOrg::getStatus, "0");
            SysOrg sysOrg = sysOrgService.getOne(queryWrapper);
            data.setReleaseUnit(sysOrg.getOrgName());
            data.setReleaseOrgId(sysOrg.getOrgId());
            data.setLevel(sysOrg.getTreeLevel());
//            data.setIsRead("0");
            data.setStatus("0");
            data.setReceiverType("0");
            data.setCreateBy(sysUser.getUserId());
            data.setUpdateBy(sysUser.getUserId());
            boolean result = this.save(data);
            if (result) {
                SysNews newEntity = new SysNews();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<SysNews> getIsRead(String id) throws Exception {
        BaseResponse<SysNews> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            SysNews data = this.getById(id);
            if (data == null || data.getStatus().equals("1")) {
                throw new BusinessException("新闻不存在");
            }

            //设置已读未读
            setIsRead(id);

            baseResponse.setData(data);
        } else {
            throw new BusinessException("参数有误");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<SysNews> getByIds(String id) throws Exception {
        BaseResponse<SysNews> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            SysNews data = this.getById(id);
            if (data == null || data.getStatus().equals("1")) {
                throw new BusinessException("新闻不存在");
            }
            baseResponse.setData(data);
        } else {
            throw new BusinessException("参数有误");
        }
        return baseResponse;
    }

    public void setIsRead(String id) {
        String loginUserId = ContextUtils.getLoginUserId();
        QueryWrapper<TSysIsRead> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TSysIsRead.USER_ID, loginUserId)
                .eq(TSysIsRead.ARTICLE_ID, id);
        TSysIsRead one = tSysIsReadService.getOne(queryWrapper);
        if (one == null) {
            String bit = IdHelper.getId32bit();
            TSysIsRead tSysIsRead = new TSysIsRead();
            tSysIsRead.setId(bit);
            tSysIsRead.setUserId(loginUserId);
            tSysIsRead.setArticleId(id);
            tSysIsRead.setIsRead("1");
            tSysIsReadService.saveOrUpdate(tSysIsRead);
        }
    }

    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(SysNews updateRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            SysNews data = BeanHelper.beanToBean(updateRequest, SysNews.class);
            LambdaUpdateWrapper<SysNews> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysNews::getId, updateRequest.getId());
            SysNews one = this.getOne(wrapper);
            if (!"0".equals(one.getStatus())) {
                throw new BusinessException("数据已删除");
            }
            if ("5".equals(data.getProcessStatus())) {
                data.setReleaseTime(new Date());
            }
            boolean result = this.updateById(data);
            if (!result) {
                throw new BusinessException("修改失败");
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(SysNewsDelParam deleteRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            LambdaUpdateWrapper<SysNews> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysNews::getId, deleteRequest.getId());
            SysNews one = this.getOne(wrapper);
            if (one == null) {
                throw new BusinessException("数据不存在");
            }
            if (!"0".equals(one.getStatus())) {
                throw new BusinessException("数据不存在");
            }
            SysNews data = new SysNews();
            String newsid = deleteRequest.getId();
            data.setId(newsid);
            data.setStatus(BizConstants.STATUS_DELETE);
            SysNews sysnews = sysNewsService.getById(newsid);
            boolean result = false;
            if (sysnews != null) {
                result = this.updateById(data);
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("参数异常");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BaseResponseList<SysNews>> listEntity(SysNewsParam param, String startTime, String endTime) {
        BaseResponse<BaseResponseList<SysNews>> baseResponse = new 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);
        Page<SysNews> resultList = this.page(resultPage, queryWrapper);
        BaseResponseList<SysNews> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    @Override
    public BaseResponse getCount() {
        BaseResponse<Object> response = new BaseResponse<>();
        // 区域公司新闻总数和基层粮库均值
        List<NewStatice> areaCount = sysNewsDao.getAreaCount();
        List<AcceptNewsCount> acceptList = new ArrayList<>();
        areaCount.stream().forEach(item -> {
            AcceptNewsCount acceptNewsCount = new AcceptNewsCount();
            acceptNewsCount.setAreaCom(item.getAreaCom());
            acceptNewsCount.setNewCount((int) Math.ceil(item.getNewCount()));
            acceptNewsCount.setNewAvg((int) Math.ceil(item.getNewAvg()));
            acceptList.add(acceptNewsCount);
        });
        response.setData(acceptList);

        return response;
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<SysNews> createQuery(SysNewsParam queryParam, String startTime, String endTime) {
        QueryWrapper<SysNews> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(startTime)) {
            String start = startTime + " 00:00:00";
            queryWrapper.ge("create_date", start);
        }
        if (!StringUtils.isEmpty(endTime)) {
            String end = endTime + " 23:59:59";
            queryWrapper.le("create_date", end);
        }
        queryWrapper.orderByDesc("create_date");
        String loginName = "";
        try {
            loginName = ContextUtils.getLoginUser().getLoginName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getLoginName, loginName).eq(SysUser::getStatus, "0");
        SysUser one = sysUserService.getOne(lambdaQueryWrapper);
        if (one != null) {
            String createBy = one.getUserId();
            if (StringHelper.isNotEmpty(createBy)) {
                queryWrapper.eq(SysNews.CREATE_BY, createBy);
            }
        }
        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 ("4".equals(queryParam.getProcessStatus())) {
            queryWrapper.eq(SysNews.PROCESS_STATUS, queryParam.getProcessStatus());
        } else {
            queryWrapper.ne(SysNews.PROCESS_STATUS, "4");
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(SysNews.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        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;
    }

    @Override
    public IPage<SysNews> getRead(SysNewsParam param, String startTime, String endTime, List<String> list, String loginUserId) {
        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);
        return sysNewsDao.getRead(resultPage, param, startTime, endTime, list, loginUserId);
    }

    @Override
    public IPage<SysNews> getUnRead(SysNewsParam param, String startTime, String endTime, List<String> list, String loginUserId) {
        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);
        return sysNewsDao.getUnRead(resultPage, param, startTime, endTime, list, loginUserId);
    }
}
