package com.loan.system.controller.wechat;

import com.loan.system.context.BaseContext;
import com.loan.system.domain.entity.User;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.SysMessageVO;
import com.loan.system.domain.vo.UserVO;
import com.loan.system.service.CustomerService;
import com.loan.system.service.MessageService;
import com.loan.system.service.UserService;
import com.loan.system.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/wechat/message")
@Api(tags = "推送信息接口")
public class MessageController {
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private MessageService messageService;


    @GetMapping
    @ApiOperation(value = "获取消息")
    public Result getMessageByMobile(@RequestParam String mobile,@RequestParam Boolean isCustomer) {
        //按手机号获取消息
        List<SysMessageVO> messageByMobiles = messageService.getMessageByMobile(mobile);
        if (isCustomer)
            return ResultUtil.success("success", messageByMobiles);

        //按角色获取消息
        User user = userService.findByPhoneNumberAndIsDelete(mobile);
        String userRole = user.getRole();
        String[] roles=userRole.split(",");
        for (String role : roles)
            messageByMobiles.addAll(messageService.getMessageByRole(role));

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

        messageByMobiles.sort(Comparator.comparing(
                (SysMessageVO vo) -> LocalDateTime.parse(vo.getCreateTime(), formatter)
        ));

        return ResultUtil.success("success", messageByMobiles);
    }
}
