package com.yonge.cooleshow.student.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.admin.io.request.SysSuggestionVo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.SysMessageConfig;
import com.yonge.cooleshow.biz.dal.entity.SysSuggestionV2;
import com.yonge.cooleshow.biz.dal.entity.SysUser;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageSendMode;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.SysMessageConfigService;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.service.SysSuggestionV2Service;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.wrapper.SysMessageWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.SysSuggestionWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.student:}/sysSuggestionV2")
@Api(tags = "平台建议表")
public class SysSuggestionV2Controller extends BaseController {

    @Autowired
    private SysSuggestionV2Service sysSuggestionService;

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private SysMessageConfigService sysMessageConfigService;

    /**
     * 查询分页
     *
     * @param query SysSuggestionWrapper.SysSuggestionQuery
     * @return R<PageInfo < SysSuggestionWrapper.SysSuggestion>>
     */
    @ApiOperation(value = "查询分页", notes = "传入sysSuggestionSearch")
    @PostMapping("/page")
    public R<PageInfo<SysSuggestionWrapper.SysSuggestion>> page(@RequestBody SysSuggestionWrapper.SysSuggestionQuery query) {
        com.yonge.cooleshow.auth.api.entity.SysUser sysUser = sysUserFeignService.queryUserInfo();
        query.setUserId(sysUser.getId());
        Student student = studentService.getById(sysUser.getId());
        if (student.getTenantId() != null && student.getTenantId() != -1) {
            query.setClientType(ClientEnum.TENANT_STUDENT);
        } else {
            query.setClientType(ClientEnum.STUDENT);
        }

        IPage<SysSuggestionWrapper.SysSuggestion> pages = sysSuggestionService.selectPage(QueryInfo.getPage(query), query);

        List<SysSuggestionWrapper.SysSuggestion> records = pages.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<Long> userIdList = records.stream()
                    .map(SysSuggestionWrapper.SysSuggestion::getUserId)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList());

            List<Long> handUserIdList = records.stream()
                    .map(SysSuggestionWrapper.SysSuggestion::getHandleBy)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList());
            if (!handUserIdList.isEmpty()) {
                userIdList.addAll(handUserIdList);
            }
            Map<Long, SysUser> userIdMap = sysUserService.getMapByIds(userIdList);

            records.forEach(next -> {
                next.setNickname(userIdMap.getOrDefault(next.getUserId(), new SysUser()).getUsername());
                next.setHandleName(userIdMap.getOrDefault(next.getHandleBy(), new SysUser()).getUsername());
            });
        }
        return R.from(QueryInfo.pageInfo(pages, records));
    }


    /**
     * 新增
     *
     * @param suggestion SysSuggestionVo.SysSuggestion
     * @return R<Boolean>
     */
    @ApiOperation(value = "新增", notes = "传入sysSuggestion")
    @PostMapping("/save")
    public R<Boolean> add(@Validated @RequestBody SysSuggestionVo.SysSuggestion suggestion,
                          @RequestHeader(name = "user-agent") String userAgent) {
        com.yonge.cooleshow.auth.api.entity.SysUser sysUser = sysUserFeignService.queryUserInfo();
        suggestion.setUserId(sysUser.getId());
        String userAgent1 = suggestion.getUserAgent();
        if(StringUtils.isEmpty(userAgent1)){
            userAgent1 = userAgent;
        }
        suggestion.setUserAgent(userAgent1);

        Student student = studentService.getById(sysUser.getId());
        if (student.getTenantId() != null && student.getTenantId() != -1) {
            suggestion.setClientType(ClientEnum.TENANT_STUDENT);
        } else {
            suggestion.setClientType(ClientEnum.STUDENT);
        }

        SysSuggestionV2 sysSuggestion = JSON.parseObject(suggestion.jsonString(), SysSuggestionV2.class);
        sysSuggestion.setCreateTime(new Date());
        return R.from(sysSuggestionService.add(sysSuggestion));
    }

    @ApiOperation(value = "未读消息统计", notes = "统计当前用户推送未读消息数")
    @GetMapping("/suggestMessageUnread")
    public R<List<SysMessageWrapper.MessageUnreadStat>> suggestMessageUnread() {
        com.yonge.cooleshow.auth.api.entity.SysUser userInfo = sysUserFeignService.queryUserInfo();

        SysMessageConfig one = sysMessageConfigService.queryByType(MessageTypeEnum.SYS_SUGGEST_FEEDBACK_STUDENT.getCode());

        // 未读消息统计条件
        SysMessageWrapper.SysMessageQuery query = SysMessageWrapper.SysMessageQuery.builder()
                .userId(userInfo.getId())
                .clientType(ClientEnum.STUDENT)
                .readStatus(false)
                .type(MessageSendMode.PUSH)
                .sendTime(DateTime.now().toDate())
                .messageConfigId(one.getId())
                .build();

        // 统计未读消息数
        List<SysMessageWrapper.MessageUnreadStat> unreadStats = sysMessageService.userMessageUnreadStat(query);

        return R.from(unreadStats);
    }
}
