package com.zfire.mall.manager.logic.admin;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.admin.NoticeRecordReadBean;
import com.zfire.mall.manager.bean.listV2.NoticeRecordReadVO;
import com.zfire.mall.manager.bean.notice.NoticeBean;
import com.zfire.mall.manager.bean.notice.NoticeRecordBean;
import com.zfire.mall.manager.commonmapper.NoticeRecordBeanMapper;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.AdminUser;
import com.zfire.mall.manager.plus.entity.CommonFile;
import com.zfire.mall.manager.plus.entity.Notice;
import com.zfire.mall.manager.plus.entity.NoticeRecord;
import com.zfire.mall.manager.plus.service.AdminUserService;
import com.zfire.mall.manager.plus.service.NoticeRecordService;
import com.zfire.mall.manager.plus.service.NoticeService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
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;

@Component
public class NoticeLogic {

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


    public IPage<NoticeRecordReadVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        return commonCMapper.queryNoticeList(new Page(zfireParamBean.getPageNum(),zfireParamBean.getPageSize()),zfireParamBean);
    }



    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(!adminUser.getIsCustomer()){
            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, Boolean isTopRead){
        NoticeRecord byId = noticeRecordService.getById(id);
        List<CommonFile> commonFiles = commonLogic.queryFileByObjId(byId.getNoticeId(), Constant.File.NOTICE);

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

        if (Objects.nonNull(isTopRead) && isTopRead) {
            byId.setIsTopRead(true)
                    .updateById();
        }

        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.insert();

        List<AdminUser> adminUsers = adminUserLogic.queryAdminUserByWebsit(noticeBean.getAdminWebsitIds());
        //新增接收人
        for(AdminUser adminUser : adminUsers){
            if(adminUser.getAdminUserId().equals(adminUserCom.getAdminUserId())){
                continue;
            }
            NoticeRecord noticeRecord = new NoticeRecord();
            BeanUtils.copyProperties(noticeBean,noticeRecord);
            noticeRecord.setAdminCompanyId(adminUser.getAdminCompanyId());
            noticeRecord.setAdminCompanyName(adminUser.getAdminCompanyName());
            noticeRecord.setAdminUserId(adminUser.getAdminUserId());
            noticeRecord.setAdminNickName(adminUser.getNickName());
            noticeRecord.insert();
        }
        //把自己也添加进去
        NoticeRecord noticeRecord = new NoticeRecord();
        BeanUtils.copyProperties(noticeBean,noticeRecord);
        noticeRecord.setAdminCompanyId(adminUserCom.getAdminCompanyId());
        noticeRecord.setAdminCompanyName(adminUserCom.getAdminCompanyName());
        noticeRecord.setAdminUserId(adminUserCom.getAdminUserId());
        noticeRecord.setAdminNickName(adminUserCom.getNickName());
        noticeRecord.insert();
        //附件
        commonLogic.bindFile(noticeBean.getNoticeId(),Constant.File.NOTICE,noticeBean.getFiles());
    }

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

        return noticeRecordService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminCompanyIds) , NoticeRecord::getAdminCompanyId , adminCompanyIds)
                .eq(NoticeRecord::getReadFlag,false)
                .count();
    }


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

    @Transactional
    public void markDel(List<String> noticeIds){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if(adminUser.getIsCustomer()){
            throw new RemoteServiceException("经销商无权删除。");
        }
        //删除通知记录 及下面的子记录
        noticeService.lambdaUpdate().in(Notice::getNoticeId,noticeIds).remove();
        noticeRecordService.lambdaUpdate().in(NoticeRecord::getNoticeId,noticeIds).remove();
    }


    public void markReadAll(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String adminUserLoginCompanyId = adminUser.getLoginCompanyId();
        if(StringUtils.isEmpty(adminUserLoginCompanyId)){
            throw new RemoteServiceException("无效微信企业id");
        }
        noticeRecordService.lambdaUpdate()
                .set(NoticeRecord::getReadFlag,true)
                .set(NoticeRecord::getReadTime,new Date())
                .eq(NoticeRecord::getAdminCompanyId , adminUserLoginCompanyId)
                .eq(NoticeRecord::getReadFlag,false)
                .update();
    }


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

}
