package com.xjrsoft.module.oa.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.IsReadTypeEnum;
import com.xjrsoft.common.enums.MessageType;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageInput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.oa.dto.MessageListDto;
import com.xjrsoft.module.oa.entity.Message;
import com.xjrsoft.module.oa.service.IMessageService;
import com.xjrsoft.module.oa.vo.MessageListVo;
import com.xjrsoft.module.oa.vo.MessageVo;
import com.xjrsoft.module.organization.dto.ResetPasswordDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 消息状态 前端控制器
 * </p>
 *
 * @author zlf
 * @since 2022-06-16
 */
@RestController
@RequestMapping(GlobalConstant.OA_MODULE_PREFIX + "/message")
@Api(value = GlobalConstant.OA_MODULE_PREFIX + "/message", tags = "消息")
@AllArgsConstructor
public class MessageController {

    private IMessageService messageService;


    @GetMapping("/list")
    @ApiOperation(value = "获取消息数据")
    public RT<List<MessageListVo>> list(MessageListDto dto) {
        Wrapper<Message> wrapper = Wrappers.<Message>query().lambda()
                .eq(Message::getUserId, StpUtil.getLoginIdAsLong())
//                .like(StrUtil.isNotBlank(dto.getKeyword()), Message::getMessageContent, dto.getKeyword())
                .orderByDesc(Message::getSendTime)
                .select(Message.class, x -> VoToColumnUtil.fieldsToColumns(MessageListVo.class).contains(x.getProperty()));

        PageInput pageInput = new PageInput();
        //最新数据
        pageInput.setLimit(0);
        //只取5条数据
        pageInput.setSize(5);
        IPage<Message> page = messageService.page(ConventPage.getPage(pageInput), wrapper);
        List<MessageListVo> vos = BeanUtil.copyToList(page.getRecords(), MessageListVo.class);

        for (MessageListVo vo : vos) {


            //如果是同一天
            if (
                    vo.getSendTime().getYear() == LocalDateTime.now().getYear() &&
                            vo.getSendTime().getMonth() == LocalDateTime.now().getMonth() &&
                            vo.getSendTime().getDayOfYear() == LocalDateTime.now().getDayOfYear()
            ) {
                if (vo.getSendTime().getMinute()>10){
                    vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.toString(vo.getSendTime().getMinute()));
                }
                else {
                    char zeroChar = '0';
                    vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.fillBefore(StrUtil.toString(vo.getSendTime().getMinute()),zeroChar,2));
                }
            } else {
                Duration between = LocalDateTimeUtil.between(vo.getSendTime(), LocalDateTime.now());

                vo.setTimeFormat(StrUtil.toString(between.toDays() == 0 ? 1 : between.toDays()) + "天前");
            }


//            if(between.toDays() < 2){
//                vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.toString(vo.getSendTime().getMinute()));
//            }
//            if(between.toDays() >= 2){
//                vo.setTimeFormat(StrUtil.toString(between.toDays()) + "天前");
//            }
        }
        return RT.ok(vos);
    }


    @GetMapping(value = "/info")
    @ApiOperation(value = "消息详情")
    public RT<MessageVo> info(@RequestParam Long id) {
        Message msg = messageService.getById(id);
        if (msg == null) {
            RT.error("找不到此消息！");
        }
        return RT.ok(BeanUtil.toBean(msg, MessageVo.class));
    }

    @PutMapping("/read-all-message")
    @ApiOperation(value = "将所有工作流未读消息改为已读")
    public RT<Boolean> readAllMessage() {
        //1、获取用户id
        Long userId = StpUtil.getLoginIdAsLong();
        //2、根据用户id和消息类型修改对应的是否已读字段为已读
        Wrapper<Message> wrapper = Wrappers.<Message>update().lambda().set(Message::getIsRead, IsReadTypeEnum.READ.getCode())
                .eq(Message::getUserId, userId).eq(Message::getMessageType, MessageType.APPROVE.getCode()).or().eq(Message::getMessageType, MessageType.CIRCULATED.getCode());
        return RT.ok(messageService.update(wrapper));
    }

    @PutMapping("/read-message")
    @ApiOperation(value = "将单条未读消息改为已读")
    public RT<Boolean> readMessage(@RequestBody ResetPasswordDto dto) {
        Message message = new Message();
        message.setId(dto.getId());
        message.setIsRead(IsReadTypeEnum.READ.getCode());
        //将是否已读类型改为已读
        return RT.ok(messageService.updateById(message));
    }

    @PutMapping("/read-all-schedule-message")
    @ApiOperation(value = "将所有日程未读消息改为已读")
    public RT<Boolean> readAllScheduleMessage() {
        //1、获取用户id
        Long userId = StpUtil.getLoginIdAsLong();
        //2、根据用户id和消息类型修改对应的是否已读字段为已读
        Wrapper<Message> wrapper = Wrappers.<Message>update().lambda().set(Message::getIsRead, IsReadTypeEnum.READ.getCode())
                .eq(Message::getUserId, userId).eq(Message::getMessageType, MessageType.SCHEDULE.getCode());
        return RT.ok(messageService.update(wrapper));
    }
}
