package com.crunii.micro.service.sysmgr.service.impl;

import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.domain.repo.main.YcqMessageRecordRepo;
import com.crunii.micro.service.sysmgr.api.domain.dto.SendMessageTaskQueryDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqBatchReadMessageDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqMessageQueryKeywordDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageUserMessageRecordDTO;
import com.crunii.micro.service.sysmgr.api.domain.vo.SendMessageTaskPageVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqExportMessageRecordVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqPageMessageRecordVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqPageUserMessageRecordVO;
import com.crunii.micro.service.sysmgr.api.enums.PushTerminalEnum;
import com.crunii.micro.service.sysmgr.api.enums.PushTypeEnum;
import com.crunii.micro.service.sysmgr.dto.sysmgr.WorkerRoleInfo;
import com.crunii.micro.service.sysmgr.jdbc.SendMessageTaskDao;
import com.crunii.micro.service.sysmgr.jdbc.WorkerJdbcDao;
import com.crunii.micro.service.sysmgr.jdbc.YcqMessageRecordDao;
import com.crunii.micro.service.sysmgr.service.YcqMessageRecordService;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class YcqMessageRecordServiceImpl implements YcqMessageRecordService {

    @Resource
    private YcqMessageRecordRepo repo;

    @Resource
    private YcqMessageRecordDao dao;

    @Resource
    private SendMessageTaskDao messageTaskDao;

    @Resource
    private WorkerJdbcDao workerJdbcDao;

    @Override
    public PageRsp<YcqPageMessageRecordVO> pageByCondition(PageReq<YcqMessageQueryKeywordDTO> req) {
        PageRsp<YcqPageMessageRecordVO> ycqPageMessageRecordVOPageRsp = dao.pageQuery(req);
        // 查询用户角色信息
        List<YcqPageMessageRecordVO> result = ycqPageMessageRecordVOPageRsp.getResult();
        if (!CollectionUtils.isEmpty(result)){
            this.setRoleInfo(result);
            result.forEach(item -> {
                item.setSendWayStr(PushTypeEnum.convert(item.getSendWay()));
            });
        }
        return ycqPageMessageRecordVOPageRsp;
    }

    @Override
    public List<YcqExportMessageRecordVO> list(YcqMessageQueryKeywordDTO req){
        List<YcqPageMessageRecordVO> result = dao.list(req);
        // 查询用户角色信息
        if (!CollectionUtils.isEmpty(result)){
            this.setRoleInfo(result);
            List<YcqExportMessageRecordVO> objects = new ArrayList<>(result.size());
            result.forEach(item -> {
                YcqExportMessageRecordVO ycqExportMessageRecordVO = new YcqExportMessageRecordVO();
                BeanUtils.copyProperties(item, ycqExportMessageRecordVO);
                objects.add(ycqExportMessageRecordVO);
                ycqExportMessageRecordVO.setSendWayStr(PushTypeEnum.convert(item.getSendWay()));
            });
            return objects;
        }
        // 写入到excel 并返回
        return null;
    }

    @Override
    public PageRsp<SendMessageTaskPageVO> pageTaskByCondition(PageReq<SendMessageTaskQueryDTO> req){
        PageRsp<SendMessageTaskPageVO> sendMessageTaskPageVOPageRsp = messageTaskDao.pageByCondition(req);
        List<SendMessageTaskPageVO> result = sendMessageTaskPageVOPageRsp.getResult();
        // 解析
        if (!CollectionUtils.isEmpty(result)){
            result.forEach(item -> {
                String endpointStr = PushTerminalEnum.convert(item.getMessageType());
                item.setMessageTypeStr(endpointStr);
                String pushTypeStr = PushTypeEnum.convert(item.getSendWay());
                item.setSendWayStr(pushTypeStr);
                Integer scopeType = item.getScopeType();
                if (Objects.equals(1, scopeType) || Objects.equals(4, scopeType)){
                    item.setNotifyTarget("用户");
                } else if (Objects.equals(2, scopeType)) {
                    item.setNotifyTarget("角色");
                }else {
                    item.setNotifyTarget("组织");
                }
            });
        }
        return sendMessageTaskPageVOPageRsp;
    }

    @Override
    public PageRsp<YcqPageUserMessageRecordVO> pageUserMessage(PageReq<YcqPageUserMessageRecordDTO> req, Integer loginId){
        PageRsp<YcqPageUserMessageRecordVO> page = dao.pageUserMessage(req, loginId);
        List<YcqPageUserMessageRecordVO> list = page.getResult();
        list.forEach(item -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            Date pushTime = item.getPushTime();
            String format = simpleDateFormat.format(pushTime);
            item.setPushTimeStr(format);
            LocalDate localDate = new LocalDate(pushTime.getTime());
            int dayOfWeek = localDate.getDayOfWeek();
            String dayOfWeek1 = this.getDayOfWeek(dayOfWeek);
            int dayOfMonth = localDate.getDayOfMonth();
            String join = String.join("-", dayOfWeek1, dayOfMonth + "");
            item.setDay(join);
        });
        return page;
    }

    @Override
    public Boolean batchRead(List<Long> ids, Integer loginId){
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        dao.batchRead(ids, loginId);
        return true;
    }

    private void setRoleInfo(List<YcqPageMessageRecordVO> target){
        if (!CollectionUtils.isEmpty(target)){
            Set<Integer> collect = target.stream().map(YcqPageMessageRecordVO::getLoginId).collect(Collectors.toSet());
            List<WorkerRoleInfo> workerRoleInfos = workerJdbcDao.listRoleInfo(new ArrayList<>(collect));
            if (!CollectionUtils.isEmpty(workerRoleInfos)){
                Map<Integer, WorkerRoleInfo> map = workerRoleInfos.stream().collect(Collectors.toMap(WorkerRoleInfo::getLoginId, Function.identity()));
                target.forEach(item -> {
                    WorkerRoleInfo workerRoleInfo = map.get(item.getLoginId());
                    if (null != workerRoleInfo){
                        item.setRoleName(workerRoleInfo.getRoleNames());
                    }
                });
            }
        }
    }


    private String getDayOfWeek(int dayOfWeek){
        switch (dayOfWeek) {
            case Calendar.SUNDAY:
                return "周日";
            case Calendar.MONDAY:
                return "周一";
            case Calendar.TUESDAY:
                return "周二";
            case Calendar.WEDNESDAY:
                return "周三";
            case Calendar.THURSDAY:
                return "周四";
            case Calendar.FRIDAY:
                return "周五";
            case Calendar.SATURDAY:
                return "周六";
        }
        return null;
    }
}
