package com.ag.web.websocket.service.topic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ag.entity.topic.RemqMsgCustom;
import com.ag.log.TopicResp;
import com.ag.log.TopicUserCol;
import com.ag.log.service.impl.TopicRespServiceImpl;
import com.ag.log.service.impl.TopicUserColServiceImpl;
import com.ag.topic.IRedisTopicCtl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wb.util.SysUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: redis频道
 * @author: WangN
 * @create: 2019-10-15
 */
@Component
public class RedisTopicService {

    @Autowired
    private JdbcTemplate jdbcTemplatebusiness;
    @Autowired
    private IRedisTopicCtl redisTopicCtl;

    @Autowired
    private TopicUserColServiceImpl topicUserColService;
    @Autowired
    private TopicRespServiceImpl topicRespService;


    private static Logger logger = LoggerFactory.getLogger(RedisTopicService.class);

    /**
     * 频道信息维护
     * @param object
     * @param response
     * @param request
     */
    public void topicSave(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String userName=String.valueOf(request.getSession().getAttribute("sys.username"));
        TopicResp topicResp= JSON.parseObject(object.getString("panelData"),TopicResp.class);

        if(StrUtil.isEmpty(topicResp.getId())){
            topicResp.setCreatedBy(userName);
            topicResp.setCreatedOn(DateUtil.date());
        }
        topicResp.setUpdatedBy(userName);
        topicResp.setUpdatedOn(DateUtil.date());

        topicRespService.saveOrUpdate(topicResp);

        redisTopicCtl.putTopic();
        redisTopicCtl.initChannelToUser();
    }
    //@Transactional
    public void topicUserSave(JSONObject object, HttpServletResponse response, HttpServletRequest request){

        String userId=String.valueOf(request.getSession().getAttribute("sys.user"));
        String userName=String.valueOf(request.getSession().getAttribute("sys.username"));
        List<TopicResp> topicRespList= JSONArray.parseArray(request.getParameter("dataArray"),TopicResp.class);
        if (CollUtil.isEmpty(topicRespList)){
            return;
        }
        List<TopicResp> checkColList=topicRespList.
                stream().
                filter(bean -> "true".equals(bean.getCheckFlag()))
                .collect(Collectors.toList());
        // 删掉订阅重新插
        topicUserColService.deleteByUserId(userId);
        // 重新插入订阅频道信息
        logger.info("size:"+checkColList.size());

        List<TopicUserCol> topicUserColList=CollUtil.newArrayList();
        TopicUserCol topicUserCol=null;



        for (int i = 0; !CollUtil.isEmpty(checkColList) && i <checkColList.size() ; i++) {
            TopicResp topicResp=checkColList.get(i);
            topicUserCol=new TopicUserCol();
            topicUserCol.setId(SysUtil.getId());
            topicUserCol.setUserId(userId);
            topicUserCol.setUserName(userName);
            topicUserCol.setTopicRespId(topicResp.getId());
            topicUserCol.setTopicRespName(topicResp.getTopicName());
            topicUserCol.setCreatedBy(userName);
            topicUserCol.setCreatedOn(DateUtil.date());
            topicUserCol.setUpdatedBy(userName);
            topicUserCol.setUpdatedOn(DateUtil.date());

            topicUserColList.add(topicUserCol);
        }

        topicUserColService.saveBatch(topicUserColList,1000);
        redisTopicCtl.initChannelToUser();
    }
    public void topicBatchUserSave(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        List<TopicResp> topicRespList= JSONArray.parseArray(request.getParameter("dataArray"),TopicResp.class);
        List<String> userArray= idList(request.getParameter("userArray"));
        if (CollUtil.isEmpty(topicRespList)||CollUtil.isEmpty(userArray)){
            return;
        }
        List<TopicResp> checkColList=topicRespList.
                stream().
                filter(bean -> "true".equals(bean.getCheckFlag()))
                .collect(Collectors.toList());
        // 删掉订阅重新插
        topicUserColService.deleteByUserIds(userArray);

        // 重新插入订阅频道信息
        logger.info("size:"+checkColList.size());

        List<TopicUserCol> topicUserColList=CollUtil.newArrayList();
        TopicUserCol topicUserCol=null;

        for (int i = 0; !CollUtil.isEmpty(checkColList) && i <checkColList.size() ; i++) {
            TopicResp topicResp=checkColList.get(i);
            for (String userId:userArray) {
                String[] users=userId.split("#");
                topicUserCol=new TopicUserCol();
                topicUserCol.setId(SysUtil.getId());
                topicUserCol.setUserId(users[0]);
                topicUserCol.setUserName(users[1]);
                topicUserCol.setTopicRespId(topicResp.getId());
                topicUserCol.setTopicRespName(topicResp.getTopicName());
                topicUserCol.setCreatedBy(users[1]);
                topicUserCol.setCreatedOn(DateUtil.date());
                topicUserCol.setUpdatedBy(users[1]);
                topicUserCol.setUpdatedOn(DateUtil.date());

                topicUserColList.add(topicUserCol);
            }
        }
        topicUserColService.saveBatch(topicUserColList,1000);
        redisTopicCtl.initChannelToUser();
    }

    @Transactional
    public void sendMQ(JSONObject object, HttpServletResponse response, HttpServletRequest request){

        RemqMsgCustom remqMsgCustom= com.alibaba.fastjson.JSONObject.parseObject("{\"businessKey\":\"C722179221284E26868C4EB209B18EE1\",\"businessType\":\"在线预约换单确认\",\"businessUrl\":\"m?xwl=AGIlogContainerIn/smaisMod/onlineOrderChangeConfirmation\",\"chatName\":\"进口换单预约\",\"createdBy\":\"中国外运华东有限公司\",\"createdOn\":1577338364968,\"id\":\"3F1AE1680A01444DBE869CE5D1254389\",\"msgInfo\":\"您收到一条新的进口换单预约，预约编号【201912261332440014】\",\"updatedBy\":\"中国外运华东有限公司\",\"updatedOn\":1577338364968}", RemqMsgCustom.class);
        redisTopicCtl.send(remqMsgCustom,"测试频道");
    }
    public void init(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        // 初始化频道信息
        redisTopicCtl.putTopic();
        // 初始化 redis 频道订阅   /initListener
        redisTopicCtl.initRdsChannel();
        // 初始化 用户-频道 信息到redis   /initChannelToUser
        redisTopicCtl.initChannelToUser();

        logger.info("频道列表："+redisTopicCtl.getChannel());
    }

    /**
     * 频道删除
     * @param object
     * @param response
     * @param request
     */
    @Transactional
    public void delChannel(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        String parentId=request.getParameter("id");

        topicRespService.deleteAllByParentId(parentId);
        try {
            double bl = 1/0;
        }catch (Exception ex){
            throw new RuntimeException("11111");
        }

    }



    public static List<String> idList(String dataArray) {
        return StringUtils.isEmpty(dataArray) ? new ArrayList() : Arrays.asList(instrIdArrays(dataArray).split(","));
    }
    public static String instrIdArrays(String dataArray) {
        return dataArray.replace("\"", "").replace("[", "").replace("]", "");
    }

}
