package cn.axzo.msg.center.inside.notices.service.impl;

import cn.axzo.core.domain.PageResult;
import cn.axzo.core.service.ServiceException;
import cn.axzo.msg.center.api.InsideNoticesApi;
import cn.axzo.msg.center.api.enums.MsgStateEnum;
import cn.axzo.msg.center.api.request.*;
import cn.axzo.msg.center.api.response.*;
import cn.axzo.msg.center.common.utils.CustomBeanUtils;
import cn.axzo.msg.center.domain.entity.MessageModule;
import cn.axzo.msg.center.domain.entity.MessageRelation;
import cn.axzo.msg.center.domain.entity.MessageTemplate;
import cn.axzo.msg.center.domain.enums.ModuleBizTypeEnum;
import cn.axzo.msg.center.domain.enums.UserTypeEnum;
import cn.axzo.msg.center.inside.notices.service.*;
import cn.azxo.framework.common.model.CommonResponse;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangPeng
 * @description
 * @date 2021/2/2 14:24
 */
@Slf4j
@RestController
public class InsideNoticesApiImpl implements InsideNoticesApi {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "yyyy-MM-dd HH:mm:ss");

    @Resource
    private MessageRecordService messageRecordService;
    @Resource
    private MessageTemplateService messageTemplateService;
    @Resource
    private MessageRelationService messageRelationService;
    @Resource
    private MessageCoreService messageCoreService;

    @Resource
    private MessageModuleService messageModuleService;

    @Override
    /*@RepeatSubCheck(value = 3000, unique = true, containParams = false)*///pudge做了前置校验
    public CommonResponse<List<MsgReturnParamRes>> pushMsg(@RequestBody GeneralMessageReq message) {
        List<MsgReturnParamRes> result = messageRecordService.pushMsg(message);
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<MessageTotalRes> statisticsMsg(MessageTotalReq req) {
        if(req== null || req.getIdentityId() ==null || req.getPersonId() == null || req.getUserType() == null){
            throw new IllegalArgumentException("personId、identityId、userType不能为空");
        }
        UserTypeEnum userTypeEnum = UserTypeEnum.valueOf(req.getUserType());
        MessageTotalRes result = messageCoreService.statisticsMsg(req.getPersonId(), req.getIdentityId(), userTypeEnum);
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<MessageTotalRes> statisticsMsg(@RequestBody @Valid StatisticsReq req) {
        UserTypeEnum userTypeEnum =UserTypeEnum.valueOf(req.getUserType());
        ModuleBizTypeEnum moduleBizType = ModuleBizTypeEnum.valueOf(req.getModuleBizType());
        switch (moduleBizType) {
            case TRADE:
                MessageTotalRes messageTotalRes = messageRecordService.statisticsMsg4Trade(req.getPersonId());
                return CommonResponse.success(messageTotalRes);
            default:
                MessageTotalRes result = messageRecordService.statisticsMsg4Construction(req.getIdentityId(), userTypeEnum);
                return CommonResponse.success(result);
        }
    }

    @Override
    public CommonResponse<PageResult<MessageNewRes>> msgList(CmsMsgQueryReq req) {
        log.info("MessageRecordServiceImpl#msgList value={}",JSONUtil.toJsonStr(req));
        PageResult<MessageNewRes> result = messageCoreService.listMsgInfo(req);
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<List<InsideMessageModuleRes>> listModule(Integer userType) {
        UserTypeEnum userTypeEnum =UserTypeEnum.valueOf(userType);
        List<MessageModule> messageModules = messageModuleService.listModuleByUserType(userTypeEnum);
        List<InsideMessageModuleRes> resList = new ArrayList<>();
        if(com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(messageModules)){
            messageModules.forEach(k->{
                if(!k.getModuleName().equals("项目公告")){
                    InsideMessageModuleRes res = new InsideMessageModuleRes();
                    res.setModuleId(k.getId());
                    res.setModuleName(k.getModuleName());
                    res.setModuleIcon(k.getIcon());
                    resList.add(res);
                }
            });
        }
        return CommonResponse.success(resList);
    }

    @Override
    public CommonResponse<Boolean> changeMessageState(@RequestBody @Valid ChangeMessageStateReq req) {
        if (CollectionUtils.isEmpty(req.getMsgIds())) {
            throw new ServiceException("msgId 不能为空");
        }

        Boolean aBoolean = messageRecordService.changeMessageState(req.getMsgIds(), req.getState());
        return CommonResponse.success(aBoolean);
    }

    @Override
    public CommonResponse<Boolean> changeMessageState(@RequestBody @Valid  ChangeMessageReq req) {
        log.info("修改消息状态入参: req={}", JSONUtil.toJsonStr(req));
        if (Objects.isNull(req.getToId()) || Objects.isNull(req.getRelationId()) || Objects.isNull(req.getBizId())) {
            log.warn("缺失必要参数");
            throw new ServiceException("修改消息状态失败,缺失必要参数");
        }
        MsgStateEnum code = MsgStateEnum.getByCode(req.getState());
        if (Objects.isNull(code)) {
            throw new ServiceException("非法消息状态");
        }
        try {
            Boolean result= messageRecordService.changeMessageState(req.getToId(), req.getRelationId(), req.getBizId(), code);
            return CommonResponse.success(result);
        } catch (IllegalStateException e) {
            // 由于 starter 内部判断重试有结合code,所以这里统一返回 200 的状态码
            return CommonResponse.success(true);
        }
    }

    @Override
    public CommonResponse<List<TemplateRes>> getTemplates(String lastUpdate) {
        //log.info("获取模板列表: {}", lastUpdate);
        List<TemplateRes> result;
        if (!messageTemplateService.hasTemplateGtUpdateAt(LocalDateTime.parse(lastUpdate, formatter))) {
            result = Lists.newArrayList();
        } else {
            List<MessageTemplate> templates = messageTemplateService.getAllTemplates();
            if (CollectionUtils.isEmpty(templates)) {
                result = Lists.newArrayList();
            } else {
                result = CustomBeanUtils.copyListProperties(templates, TemplateRes::new);
            }
        }
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<List<RelationRes>> getRelations(String lastUpdate) {
        List<RelationRes> result;
        if (!messageRelationService.hasRelationGtUpdateAt(LocalDateTime.parse(lastUpdate, formatter))) {
            return CommonResponse.success(new ArrayList<>());
        }
        List<MessageRelation> relations = messageRelationService.getAllRelations();
        if (CollectionUtils.isEmpty(relations)) {
            return CommonResponse.success(new ArrayList<>());
        }
        result = CustomBeanUtils.copyListProperties(relations, RelationRes::new);
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<Void> updateReadMsgStatus(CmsReadMsgReq req) {
        log.info("updateReadMsgStatus, req={}", req);
        messageRecordService.updateReadMsgStatus(req);
        return CommonResponse.success();
    }


    @Override
    public CommonResponse<PageResult<MessageNewRes>> listMsgInfo4Trade(CmsMsgQueryReq req) {
        PageResult<MessageNewRes> result = messageCoreService.listMsgInfo4Trade(req);
        return CommonResponse.success(result);
    }
}
