package com.gree.mall.manager.logic.notice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.notice.*;
import com.gree.mall.manager.commonmapper.NoticeRecordBeanMapper;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.logic.admin.AdminUserLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.AdminUserService;
import com.gree.mall.manager.plus.service.NoticeRecordService;
import com.gree.mall.manager.plus.service.NoticeService;
import com.gree.mall.manager.plus.service.UserService;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class NoticeLogic {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    NoticeRecordService noticeRecordService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    AdminUserLogic adminUserLogic;
    @Autowired
    NoticeRecordBeanMapper noticeRecordMapper;
    @Autowired
    UserService userService;






   /* public IPage<NoticeRecordReadBean> page(HttpServletRequest request,Boolean isNotice,String type,String code,String title,String startTime,String endTime,
                              Boolean readFlag, Integer pageNum, Integer pageSize) {

        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> adminCompanyIds = adminUser.getAdminCompanyIds();

        IPage<NoticeRecordReadBean> page = noticeRecordService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminCompanyIds),NoticeRecord::getAdminCompanyId,adminCompanyIds)
                .eq(NoticeRecord::getAdminUserId,adminUser.getAdminUserId())
                .eq(isNotice != null,NoticeRecord::getIsNotice,isNotice)
                .like(type != null,NoticeRecord::getType,type)
                .like(StringUtils.isNotEmpty(code),NoticeRecord::getCode,code)
                .like(StringUtils.isNotEmpty(title),NoticeRecord::getTitle,title)
                .between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime),NoticeRecord::getCreateTime,startTime,endTime)
                .eq(readFlag!=null,NoticeRecord::getReadFlag,readFlag)
                .orderByDesc(NoticeRecord::getCreateTime)
                .page(new Page(pageNum, pageSize));

        List<NoticeRecordReadBean> noticeRecords = page.getRecords();
        List<NoticeRecordReadBean> newRecords = new ArrayList<>();
        //经销商不去查询已阅数量

        if (noticeRecords != null && noticeRecords.size() > 0){
            List<String> noticeIds = new ArrayList<>();
            //拿到当前页所有消息记录id
            for(NoticeRecord noticeRecord:noticeRecords){
                noticeIds.add(noticeRecord.getNoticeId());
            }
            //拿到每条消息的已读数量
            List<NoticeRecordReadBean> readCountList = noticeRecordMapper.readCount(noticeIds);
            for(NoticeRecord noticeRecord:noticeRecords){
                NoticeRecordReadBean newBean = new NoticeRecordReadBean();
                BeanUtils.copyProperties(noticeRecord,newBean );
                for(NoticeRecordReadBean read:readCountList){
                    //如果id一致赋值已阅数量
                    if(read.getNoticeId().equals(noticeRecord.getNoticeId())){
                        newBean.setReadCount(read.getReadCount());
                    }
                }
                newRecords.add(newBean);
            }
            page.setRecords(newRecords);
        }

      return page;

    }*/

    public NoticeRecordBean detail(String id){
        NoticeRecord byId = noticeRecordService.getById(id);
        List<CommonFile> commonFiles = commonLogic.queryFileByObjId(byId.getNoticeId(), "notice_file");

        NoticeRecordBean noticeRecordBean = new NoticeRecordBean();
        BeanUtils.copyProperties(byId,noticeRecordBean);
        noticeRecordBean.setFiles(commonFiles);
        return noticeRecordBean;
    }

    @Transactional
    public void add(NoticeBean noticeBean){
        AdminUserCom adminUserCom = commonLogic.getAdminUser();
        noticeBean.setIssueUserId(adminUserCom.getAdminUserId());
        noticeBean.setIssueNickName(adminUserCom.getNickName());
        noticeBean.setIssueTime(new Date());
        noticeBean.setAdminCompanyId(adminUserCom.getCompanyWechatId());
        noticeBean.setAdminCompanyName(adminUserCom.getCompanyName());
        noticeBean.insert();


        //新增接收人
        for(String adminUser : noticeBean.getAdminWebsitIds()){

            AdminUser adminuser1 = adminUserService.getById(adminUser);

            NoticeRecord noticeRecord = new NoticeRecord();
            BeanUtils.copyProperties(noticeBean,noticeRecord);
            noticeRecord.setAdminUserId(adminUser);
            noticeRecord.setAdminNickName(adminuser1.getNickName());
            noticeRecord.setAdminCompanyId(adminuser1.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(adminuser1.getCompanyName());

            noticeRecord.insert();
        }

        //新增接收人
        for(String adminUser : noticeBean.getWorkerIds()){

            User user = userService.getById(adminUser);
            NoticeRecord noticeRecord = new NoticeRecord();
            BeanUtils.copyProperties(noticeBean,noticeRecord);
            noticeRecord.setAdminUserId(adminUser);
            noticeRecord.setAdminNickName(user.getNickName());
            noticeRecord.setAdminCompanyId(adminUserCom.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(adminUserCom.getCompanyName());
            noticeRecord.setIsWorker(IsYesNoEnum.YES.getKey());
            noticeRecord.insert();
        }

        //附件
        commonLogic.bindFileFile(noticeBean.getNoticeId(), "notice_file",noticeBean.getFiles());
    }

    public Integer unreadCount(HttpServletRequest request,List<String> noticeType,String readFlag) {
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> adminCompanyIds = adminUser.getAdminWebsitIds();

        return noticeRecordService.lambdaQuery()
                .in( NoticeRecord::getAdminCompanyId , adminUser.getCompanyWechatId())
                .eq(!StringUtil.isEmpty(readFlag),NoticeRecord::getReadFlag, readFlag)
                .in(!CollectionUtils.isEmpty(noticeType),NoticeRecord::getAdminNoticeType, noticeType)
                .eq(NoticeRecord::getAdminUserId, adminUser.getAdminUserId())
                .count();
    }


    public void markRead(List<String> noticeIds) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        noticeRecordService.lambdaUpdate()
                .set(NoticeRecord::getReadFlag, IsYesNoEnum.YES.getKey())
                .set(NoticeRecord::getReadTime,new Date())
                .eq(NoticeRecord::getAdminUserId,adminUser.getAdminUserId())
                .in(NoticeRecord::getId,noticeIds)
                .update();

        for (String noticeId : noticeIds) {
            NoticeRecord not = noticeRecordService.lambdaQuery()
                    .eq(NoticeRecord::getAdminUserId, adminUser.getAdminUserId())
                    .eq(NoticeRecord::getId, noticeId).last("limit 1").one();

            Notice one = noticeService.lambdaQuery()
                    .eq(Notice::getNoticeId, not.getNoticeId()).last("limit 1").one();
            if (one != null){
                one.setNum(one.getNum()+1);
                one.updateById();
            }
        }

    }

    @Transactional
    public void markDel(List<String> noticeIds){
        //删除通知记录 及下面的子记录
        noticeService.lambdaUpdate().in(Notice::getNoticeId,noticeIds).remove();
        noticeRecordService.lambdaUpdate().in(NoticeRecord::getNoticeId,noticeIds).remove();
    }


    public void markReadAll(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<NoticeRecord> list = noticeRecordService.lambdaQuery()
                .eq(NoticeRecord::getReadFlag, IsYesNoEnum.NO.getKey())
                .eq(NoticeRecord::getAdminUserId, adminUser.getAdminUserId()).list();
        for (NoticeRecord noticeRecord : list) {

            Notice one = noticeService.lambdaQuery()
                    .eq(Notice::getNoticeId, noticeRecord.getNoticeId()).last("limit 1").one();
            if (one != null){
                one.setNum(one.getNum()+1);
                one.updateById();
            }
        }


        noticeRecordService.lambdaUpdate()
                .set(NoticeRecord::getReadFlag,IsYesNoEnum.YES.getKey())
                .set(NoticeRecord::getReadTime,new Date())
                .eq(NoticeRecord::getReadFlag,IsYesNoEnum.NO.getKey())
                .eq(NoticeRecord::getAdminUserId,adminUser.getAdminUserId())
                .update();
    }


    public IPage<NoticeRecord> readListPage(String noticeId, Integer pageNum, Integer pageSize) {
        return noticeRecordService.lambdaQuery()
                .eq(NoticeRecord::getNoticeId,noticeId)
                .eq(NoticeRecord::getReadFlag,IsYesNoEnum.YES.getKey())
                .orderByDesc(NoticeRecord::getCreateTime)
                .page(new Page(pageNum, pageSize));
    }

    public IPage<NoticeRecordReadBean> list(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();

        IPage<NoticeRecordReadBean> pageList = noticeRecordMapper.list(page, zfireParam, adminUser.getAdminUserId(), adminCompanyIds);


        return pageList;

    }


    public IPage<NoticeRecordReadBean> readList(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        IPage<NoticeRecordReadBean> pageList = noticeRecordMapper.list(page, zfireParam, adminUser.getAdminUserId(), adminCompanyIds);
        return pageList;

    }

    public IPage<NoticeVO> listNotice(Page page, ZfireParamBean zfireParam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        IPage<NoticeVO> pageList = noticeRecordMapper.listNotice(page, zfireParam, adminCompanyIds);
        return pageList;
    }

    public NoticeDetail detailNotice(String noticeId) {
        NoticeDetail noticeVO = BeanUtil.toBean(noticeService.getById(noticeId), NoticeDetail.class);
        List<CommonFile> commonFiles = commonLogic.queryFileByObjId(noticeVO.getNoticeId(), "notice_file");


        noticeVO.setFiles(commonFiles);

        List<String> collect = noticeRecordService.lambdaQuery().eq(NoticeRecord::getIsWorker, IsYesNoEnum.YES.getKey())
                .eq(NoticeRecord::getNoticeId, noticeId).list()
                .stream().map(NoticeRecord::getAdminUserId).collect(Collectors.toList());

        List<String> collect1 = noticeRecordService.lambdaQuery().eq(NoticeRecord::getIsWorker, IsYesNoEnum.NO.getKey())
                .eq(NoticeRecord::getNoticeId, noticeId).list()
                .stream().map(NoticeRecord::getAdminUserId).collect(Collectors.toList());

        noticeVO.setAdminWebsitIds(collect1);
        noticeVO.setWorkerIds(collect);
        return noticeVO;

    }

    public void update(NoticeBean noticeBean) {
        AdminUserCom adminUserCom = commonLogic.getAdminUser();
        noticeBean.setIssueUserId(adminUserCom.getAdminUserId());
        noticeBean.setIssueNickName(adminUserCom.getNickName());
        noticeBean.setIssueTime(new Date());
        noticeBean.setAdminCompanyId(adminUserCom.getCompanyWechatId());
        noticeBean.setAdminCompanyName(adminUserCom.getCompanyName());
        noticeBean.updateById();

        noticeRecordService.lambdaUpdate().eq(NoticeRecord::getNoticeId,noticeBean.getNoticeId()).remove();
        //新增接收人
        for(String adminUser : noticeBean.getAdminWebsitIds()){

            NoticeRecord noticeRecord = new NoticeRecord();
            BeanUtils.copyProperties(noticeBean,noticeRecord);
            noticeRecord.setAdminUserId(adminUser);
            noticeRecord.setAdminCompanyId(adminUserCom.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(adminUserCom.getCompanyName());
            noticeRecord.insert();
        }

        //新增接收人
        for(String adminUser : noticeBean.getWorkerIds()){

            User user = userService.getById(adminUser);
            NoticeRecord noticeRecord = new NoticeRecord();
            BeanUtils.copyProperties(noticeBean,noticeRecord);
            noticeRecord.setAdminUserId(adminUser);
            noticeRecord.setAdminNickName(user.getNickName());
            noticeRecord.setIsWorker(IsYesNoEnum.YES.getKey());
            noticeRecord.setAdminCompanyId(adminUserCom.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(adminUserCom.getCompanyName());
            noticeRecord.insert();
        }

        //附件
        commonLogic.bindFileFile(noticeBean.getNoticeId(), "notice_file",noticeBean.getFiles());
    }

    public List<NoticeRecord> out(Integer num) {

        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(adminUser) || CollectionUtil.isEmpty(adminUser.getAdminWebsitIds())) {
            return new ArrayList<>();
        }

        List<String> adminCompanyIds = adminUser.getAdminWebsitIds();

        Date date = new Date();
        DateTime dateTime = DateUtil.offsetSecond(date, -1*num);

        Date date1 = new Date();

        List<NoticeRecord> list = noticeRecordService.lambdaQuery()
                .in(!StringUtil.isEmpty(adminUser.getCompanyWechatId()), NoticeRecord::getAdminCompanyId, adminUser.getCompanyWechatId())
                .eq(!StringUtil.isEmpty(adminUser.getAdminUserId()), NoticeRecord::getAdminUserId, adminUser.getAdminUserId())
                //.ne( NoticeRecord::getAdminNoticeType, "NOTICE")
                .between(NoticeRecord::getIssueTime, dateTime, date1)
                .list();

        return list;
    }

    public void updateIsNotic(String isNotice) {

        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        AdminUser adminUser1 = new AdminUser();
        adminUser1.setAdminUserId(adminUser.getAdminUserId());
        adminUser1.setIsNotice(isNotice);
        adminUser1.updateById();
    }

    public IPage<NoticeRecordReadVOBean> listRecord(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        IPage<NoticeRecordReadVOBean> pageList = noticeRecordMapper.listRecord(page, zfireParam, null, adminCompanyIds);
        return pageList;
    }
}
