package com.jpsoft.shinestar.modules.mobile.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mobile/messageApi")
@Api(description = "消息api")
public class MessageApiController {
    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private MessageReceiverService messageReceiverService;

    @Autowired
    private MessageSendConditionService messageSendConditionService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @GetMapping("prefetch")
    @ApiOperation(value="预获取消息")
    public MessageResult<Integer> prefetch(@RequestAttribute String subject){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
//            Integer affectCount = 0;

            Long personId = Long.valueOf(subject);

            //当前用户的所有身份
            List<PersonPopedom> popedomList = personPopedomService.findByPersonId(personId);

            for (PersonPopedom popedom : popedomList) {
                String companyId = popedom.getCompanyId();

                if (StringUtils.isEmpty(companyId)){
                    //未关联单位
                    continue;
                }

                String companyStructureId = popedom.getCompanyStructureId();
                String personRoleId = popedom.getPersonRoleId();

                Map<String,Object> searchParams = new HashMap<>();

                CompanyInfo companyInfo = companyInfoService.get(companyId);

                if (companyInfo==null){
                    //单位不存在，则不会有群发消息
                    continue;
                }

                searchParams.put("companyId",companyId);
                searchParams.put("companyCode", companyInfo.getCode());
                searchParams.put("companyStructureId", companyStructureId);
                searchParams.put("personRoleId", personRoleId);
                searchParams.put("personId", personId);

                //查询当前身份是否有新消息
                List<String> idList = messageSendConditionService.findNewMessage(searchParams);

                for (String messageId : idList) {
                    //有则添加
                    MessageReceiver receiver = messageReceiverService.findByMessageIdAndPersonId(messageId,personId);

                    //避免重复添加
                    if (receiver==null) {
                        receiver = new MessageReceiver();

                        receiver.setId(UUID.randomUUID().toString());
                        receiver.setPersonId(Long.valueOf(personId));
                        receiver.setMessageId(messageId);
                        receiver.setCreateTime(new Date());
                        receiver.setCreateBy(subject);
                        receiver.setReadStatus(false);
                        receiver.setDelFlag(false);

                        messageReceiverService.insert(receiver);
                    }
                }
            }

            //查询当前用户的未读消息数
            int total = messageReceiverService.countUnReadByPersonIdAndType(personId, null);

            messageResult.setData(total);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping(value="topList")
    @ApiOperation(value = "最近消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "消息类型", required = true, paramType = "form"),
            @ApiImplicitParam(name = "limit", value = "数量", required = true, paramType = "form"),
            @ApiImplicitParam(name = "excludeMessageId", value = "排除消息编号", paramType = "form")
    })
    public MessageResult<List> topList(
            @RequestParam(name = "type",defaultValue = "1") String type,
            @RequestParam(name = "limit",defaultValue = "5") int limit,
            @RequestParam(name = "excludeMessageId",defaultValue = "") String excludeMessageId,
            @RequestAttribute String subject){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            Long personId = Long.valueOf(subject);

            if (limit>10){
                limit = 10;
            }

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time","desc"));

            Map<String,Object> searchParams = new HashMap<>();

            searchParams.put("personId",personId);
            searchParams.put("type", type);
            searchParams.put("status", true);

            if (StringUtils.isNotEmpty(excludeMessageId)){
                searchParams.put("excludeMessageId",excludeMessageId);
            }

            Page<MessageReceiver> page = messageReceiverService.messagePageSearch(searchParams,1,limit,false, sortList);

            List<Map> mapList = new ArrayList<>();

            for (MessageReceiver receiver : page) {
                Map<String,Object> map = new HashMap<>();

                map.put("messageId", receiver.getMessageId());
                map.put("title",receiver.getTitle());
                map.put("readStatus", receiver.getReadStatus());

                DateTime time = new DateTime(receiver.getMessageCreateTime());

                map.put("date", time.getMonthOfYear() + "月" + time.getDayOfMonth() + "日");

                mapList.add(map);
            }

            messageResult.setData(mapList);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping(value="groupList")
    @ApiOperation(value = "消息分组")
    public MessageResult<List> groupList(@RequestAttribute String subject){
        MessageResult<List> messageResult = new MessageResult<>();
    
        try {
            Long personId = Long.valueOf(subject);

            List<DataDictionary> ddList = dataDictionaryService.findByCatalogName("消息类型");

            List<Map> mapList = new ArrayList<>();

            for (DataDictionary dd : ddList) {
                Map<String,Object> map = new HashMap<>();

                int total = messageReceiverService.countUnReadByPersonIdAndType(personId, dd.getValue());

                map.put("name",dd.getName());
                map.put("type", dd.getValue());
                map.put("total", total);

                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("create_time","desc"));

                Map<String,Object> searchParams = new HashMap<>();

                searchParams.put("personId",personId);
                searchParams.put("type", dd.getValue());
                searchParams.put("status", true);

                Page<MessageReceiver> page = messageReceiverService.messagePageSearch(searchParams,1,1,false,sortList);

                if (page.size()>0){
                    Map<String,Object> lastMsgMap = new HashMap<>();

                    MessageReceiver messageReceiver = page.get(0);

                    lastMsgMap.put("messageId",messageReceiver.getMessageId());
                    lastMsgMap.put("title",messageReceiver.getTitle());
                    lastMsgMap.put("readStatus", messageReceiver.getReadStatus());

                    DateTime time = new DateTime(messageReceiver.getMessageCreateTime());
                    lastMsgMap.put("date", time.getMonthOfYear() + "月" + time.getDayOfMonth() + "日");

                    map.put("message", lastMsgMap);
                }
                else{
                    map.put("message", null);
                }

                mapList.add(map);
            }

            messageResult.setData(mapList);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }
        
        return messageResult;
    }
    
    @PostMapping(value="pageList")
    @ApiOperation(value = "消息分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "消息类型", required = true, paramType = "form"),
            @ApiImplicitParam(name = "pageIndex", value = "页数", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "数量", paramType = "form")
    })
    public MessageResult<Map> pageList(
            @RequestAttribute String subject,String type,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize){
        MessageResult<Map> messageResult = new MessageResult<>();
    
        try {
            Long personId = Long.valueOf(subject);

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time","desc"));

            Map<String,Object> searchParams = new HashMap<>();

            searchParams.put("personId",personId);
            searchParams.put("type", type);
            searchParams.put("status", true);

            if (pageSize>100){
                pageSize = 100;
            }

            Page<MessageReceiver> page = messageReceiverService.messagePageSearch(searchParams,pageIndex,pageSize,true,sortList);

            messageResult.setResult(true);
            messageResult.setData(PojoUtils.pageWrapper(page));
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }
        
        return messageResult;
    }

    @GetMapping(value="view/{id}")
    @ApiOperation(value = "查看消息")
    public MessageResult<MessageInfo> view(@PathVariable("id") String id, @RequestAttribute String subject){
        MessageResult<MessageInfo> messageResult = new MessageResult<>();

        try {
            Long personId = Long.valueOf(subject);
            MessageReceiver receiver = messageReceiverService.findByMessageIdAndPersonId(id,personId);
            MessageInfo messageInfo = messageInfoService.get(receiver.getMessageId());

            receiver.setReadStatus(true);
            receiver.setUpdateTime(new Date());
            receiver.setUpdateBy(subject);
            messageReceiverService.update(receiver);

            messageResult.setData(messageInfo);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
