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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.MessageReceiverService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.service.MessageInfoService;
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.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/base/message")
@Api(description = "消息通知")
public class MessageInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private MessageReceiverService messageReceiverService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<MessageInfo> create(){
        MessageResult<MessageInfo> msgResult = new MessageResult<>();

        MessageInfo messageInfo = new MessageInfo();

        msgResult.setData(messageInfo);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<MessageInfo> add(@RequestBody MessageInfo messageInfo,@RequestAttribute String subject){
        MessageResult<MessageInfo> msgResult = new MessageResult<>();

        try {
            messageInfo.setId(UUID.randomUUID().toString());
            messageInfo.setDelFlag(false);
            messageInfo.setCreateBy(subject);
            messageInfo.setCreateTime(new Date());
            
            int affectCount = messageInfoService.insert(messageInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(messageInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<MessageInfo> edit(@PathVariable("id") String id){
        MessageResult<MessageInfo> msgResult = new MessageResult<>();

        try {
            MessageInfo messageInfo = messageInfoService.get(id);

            if (messageInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(messageInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
}

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<MessageInfo> update(@RequestBody MessageInfo messageInfo,@RequestAttribute String subject){
        MessageResult<MessageInfo> msgResult = new MessageResult<>();

        try {
            messageInfo.setUpdateBy(subject);
            messageInfo.setUpdateTime(new Date());
            
            int affectCount = messageInfoService.update(messageInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(messageInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            MessageInfo messageInfo = messageInfoService.get(id);
            messageInfo.setDelFlag(true);
            messageInfo.setUpdateBy(subject);
            messageInfo.setUpdateTime(new Date());

            int affectCount = messageInfoService.update(messageInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                MessageInfo messageInfo = messageInfoService.get(id);
                messageInfo.setDelFlag(true);
                messageInfo.setUpdateBy(subject);
                messageInfo.setUpdateTime(new Date());

                affectCount += messageInfoService.update(messageInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String title,
            String type,
            String status,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="field",defaultValue="create_time") String field,
            @RequestParam(value="direction",defaultValue="desc") String direction,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort(field,direction));

        if (StringUtils.isNotEmpty(title)) {
            searchParams.put("title","%" + title + "%");
        }

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

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

        Map<String, DataDictionary> messageTypeMap = dataDictionaryService.findMapByCatalogName("消息类型");

        Page<MessageInfo> page = messageInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        for (MessageInfo messageInfo:page) {
            if (messageTypeMap.containsKey(messageInfo.getType())) {
                messageInfo.setTypeN(messageTypeMap.get(messageInfo.getType()).getName());
            }
        }

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="待接受人查询列表")
    @RequestMapping(value = "recvPageSearch",method = RequestMethod.POST)
    public MessageResult<Map> recvPageSearch(
            String messageId,
            String companyId,
            String companyStructureId,
            String roleId,
            String personName,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="field",defaultValue="a.id_") String field,
            @RequestParam(value="direction",defaultValue="asc") String direction,
            @RequestAttribute String subject){
        MessageResult<Map> msgResult = new MessageResult<>();

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort(field,direction));

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

        if (StringUtils.isNotEmpty(companyId)) {
            //查询所有下级单位
            CompanyInfo companyInfo = companyInfoService.get(companyId);

            searchParams.put("companyCode",companyInfo.getCode() + "%");
        }

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

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

        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("personName","%" + personName + "%");
        }

        Page<MessagePerson> page = messageInfoService.personSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @PostMapping("sendAll")
    @ApiOperation(value="向全部人发送")
    public MessageResult<Integer> sendAll(String messageId,String companyId,
                                          String companyStructureId,String roleId,
                                          String personName,@RequestAttribute String subject){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
            List<Sort> sortList = new ArrayList<>();
            Map<String,Object> searchParams = new HashMap<>();

            sortList.add(new Sort("a.id_","asc"));

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

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

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

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

            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("personName","%" + personName + "%");
            }

            int pageIndex = 1;
            int pageSize = 500;
            int affectCount = 0;

            Page<MessagePerson> page = messageInfoService.personSearch(searchParams,pageIndex, pageSize,true,sortList);

            int totalPages = page.getPages();

            while(pageIndex<=totalPages){
                for (MessagePerson personInfo : page) {
                    if (StringUtils.isEmpty(personInfo.getReceiverId())) {
                        MessageReceiver receiver = new MessageReceiver();
                        receiver.setId(UUID.randomUUID().toString());
                        receiver.setPersonId(personInfo.getId());
                        receiver.setMessageId(messageId);
                        receiver.setCreateTime(new Date());
                        receiver.setCreateBy(subject);
                        receiver.setReadStatus(false);
                        receiver.setDelFlag(false);

                        messageReceiverService.insert(receiver);

                        affectCount++;
                    }
                }

                pageIndex++;
                page = messageInfoService.personSearch(searchParams,pageIndex, pageSize,false,sortList);
            }

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

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

        return messageResult;
    }

    @PostMapping("batchSend")
    @ApiOperation(value="批量发送")
    public MessageResult<Integer> batchSend(String messageId,String personIds,@RequestAttribute String subject){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
            int affectCount = 0;

            String[] idArr = personIds.split(",");

            for (String personId : idArr) {
                MessageReceiver 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);

                affectCount++;
            }

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

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

        return messageResult;
    }
}
