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.MessageNoticeCompanyService;
import com.jpsoft.shinestar.modules.base.service.MessageNoticeService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
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.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
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.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/messageNotice")
@Api(description = "messageNotice")
public class MessageNoticeController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private MessageNoticeService messageNoticeService;
    @Autowired
    private MessageNoticeCompanyService messageNoticeCompanyService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;


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

        MessageNotice messageNotice = new MessageNotice();

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

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

        try {
            messageNotice.setId(UUID.randomUUID().toString());
            messageNotice.setDelFlag(false);
            messageNotice.setCreateBy(subject);
            messageNotice.setCreateTime(new Date());
            //默认保存修改时间,做查询排序用
            messageNotice.setUpdateTime(new Date());

            if (StringUtils.isNotEmpty(messageNotice.getNoticeType())) {
                String[] noticeTypes = messageNotice.getNoticeType().split(",");
                String sortNoticeTypes = Arrays.stream(noticeTypes).sorted(Comparator.naturalOrder()).collect(Collectors.joining(","));
                messageNotice.setNoticeType(sortNoticeTypes);
            }
            
            int affectCount = messageNoticeService.insert(messageNotice);

            if (affectCount > 0) {
                String noticeCompany = messageNotice.getNoticeCompany();
                String[] companyIds = noticeCompany.split(",");
                MessageNoticeCompany messageNoticeCompany = null;
                //删除
                messageNoticeCompanyService.deleteByNoticeId(messageNotice.getId());
                //查找新创建用户ID
                for(String companyId : companyIds){
                    //添加
                    messageNoticeCompany = new MessageNoticeCompany();
                    messageNoticeCompany.setId(UUID.randomUUID().toString());
                    messageNoticeCompany.setCompanyId(companyId);
                    messageNoticeCompany.setNoticeId(messageNotice.getId());
                    messageNoticeCompany.setDelFlag(false);
                    messageNoticeCompany.setCreateBy(subject);
                    messageNoticeCompany.setCreateTime(new Date());
                    messageNoticeCompanyService.insert(messageNoticeCompany);
                }
                msgResult.setResult(true);
                msgResult.setData(messageNotice);
            } 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<MessageNotice> edit(@PathVariable("id") String id){
        MessageResult<MessageNotice> msgResult = new MessageResult<>();

        try {
            MessageNotice messageNotice = messageNoticeService.get(id);

            if (messageNotice != null) {
                //查询用户关联子公司表
                List<MessageNoticeCompany> messageNoticeList = messageNoticeCompanyService.findByNoticeId(id);
                String mnc = "";
                for(MessageNoticeCompany messageNoticeCompany : messageNoticeList){
                    mnc += messageNoticeCompany.getCompanyId() + ",";
                }
                if(mnc.length() > 0) {
                    mnc = mnc.substring(0, mnc.length() - 1);
                }
                messageNotice.setNoticeCompany(mnc);
                msgResult.setResult(true);
                msgResult.setData(messageNotice);
            } 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<MessageNotice> update(@RequestBody MessageNotice messageNotice, @RequestAttribute String subject){
        MessageResult<MessageNotice> msgResult = new MessageResult<>();

        try {
            messageNotice.setUpdateBy(subject);
            messageNotice.setUpdateTime(new Date());
            if (StringUtils.isNotEmpty(messageNotice.getNoticeType())) {
                String[] noticeTypes = messageNotice.getNoticeType().split(",");
                String sortNoticeTypes = Arrays.stream(noticeTypes).sorted(Comparator.naturalOrder()).collect(Collectors.joining(","));
                messageNotice.setNoticeType(sortNoticeTypes);
            }
            
            int affectCount = messageNoticeService.update(messageNotice);

            if (affectCount > 0) {
                String noticeCompany = messageNotice.getNoticeCompany();
                String[] companyIds = noticeCompany.split(",");
                MessageNoticeCompany messageNoticeCompany = null;
                //删除
                messageNoticeCompanyService.deleteByNoticeId(messageNotice.getId());
                //查找新创建用户ID
                for(String companyId : companyIds){
                    //添加
                    messageNoticeCompany = new MessageNoticeCompany();
                    messageNoticeCompany.setId(UUID.randomUUID().toString());
                    messageNoticeCompany.setCompanyId(companyId);
                    messageNoticeCompany.setNoticeId(messageNotice.getId());
                    messageNoticeCompany.setDelFlag(false);
                    messageNoticeCompany.setCreateBy(subject);
                    messageNoticeCompany.setCreateTime(new Date());
                    messageNoticeCompanyService.insert(messageNoticeCompany);
                }
                msgResult.setResult(true);
                msgResult.setData(messageNotice);
            } 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 {
            MessageNotice messageNotice = messageNoticeService.get(id);
            messageNotice.setDelFlag(true);
            messageNotice.setUpdateBy(subject);
            messageNotice.setUpdateTime(new Date());

            int affectCount = messageNoticeService.update(messageNotice);

            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) {
                MessageNotice messageNotice = messageNoticeService.get(id);
                messageNotice.setDelFlag(true);
                messageNotice.setUpdateBy(subject);
                messageNotice.setUpdateTime(new Date());

                affectCount += messageNoticeService.update(messageNotice);
            }

            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 companyId,
            String companyCode,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        //当前用户ID
        User user = userService.get(subject);

        CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

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

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

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

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

        if (!userService.hasRole(subject,"SYSADMIN")) {
            String[] arr = companyInfo.getCode().split(",");
            searchParams.put("companyIds",  Arrays.asList(arr));
            //非系统管理员只能查看自己发的通知
            //searchParams.put("createBy", subject);
        }

        Page<MessageNotice> page = messageNoticeService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(MessageNotice mn : page.getResult()){
            mn.setClassifyN(dataDictionaryService.findNameByCatalogNameAndValue("通知分类",mn.getClassify()));
        }

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

        return msgResult;
    }

    @ApiOperation(value="发送微信通知")
    @RequestMapping(value = "sendWechat",method = RequestMethod.POST)
    public MessageResult<Integer> sendWechat(String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            MessageNotice messageNotice = messageNoticeService.get(id);
            messageNotice.setSendWechat(true);
            messageNotice.setUpdateBy(subject);
            messageNotice.setUpdateTime(new Date());

            int affectCount = messageNoticeService.update(messageNotice);

            if (affectCount > 0) {
                List<MessageNoticeCompany> mbcList = messageNoticeCompanyService.findByNoticeId(messageNotice.getId());

                for(MessageNoticeCompany mnc : mbcList){
                    int pageIndex = 1;
                    int pageSize = 500;

                    Page<PersonInfo> page = sendPersonList(mnc.getCompanyId(),messageNotice.getNoticeType(),pageIndex, pageSize,true);
                    int totalPage = page.getPages();

                    while(pageIndex<=totalPage) {
                        for (PersonInfo pi : page.getResult()) {
                            MessageNoticePerson messageNoticePerson = new MessageNoticePerson();
                            messageNoticePerson.setNoticeId(messageNotice.getId());
                            messageNoticePerson.setPersonId(pi.getId());

                            //rabbitTemplate.convertAndSend("schoolMessageNoticeQueue", messageNoticePerson);
                        }

                        pageIndex++;
                        page = sendPersonList(mnc.getCompanyId(),messageNotice.getNoticeType(),pageIndex, pageSize,false);
                    }
                }

                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 = "sendPersonList",method = RequestMethod.POST)
    public Page<PersonInfo> sendPersonList(
            String companyId,
            String noticePopedom,
            int pageIndex,
            int pageSize,
            boolean count){
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("id_","asc"));

        Map<String,Object> searchParams = new HashMap<>();
        //获取公司CODE
        CompanyInfo parentCompanyInfo = companyInfoService.get(companyId);

        String parentCode = parentCompanyInfo.getCode();
        searchParams.put("companyCode", parentCode + "%");

        //角色权限
        String[] popedoms = noticePopedom.split(",");
        searchParams.put("popedomlist", popedoms);

        Page<PersonInfo> page = personInfoService.pageSearch(searchParams, pageIndex, pageSize, count, sortList);

        return page;
    }
}
