package cn.com.capcloud.api.action.myself.system.data;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.websocket.RedisPublication;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DefaultAction;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
public class DataSystemNotifyAction extends DefaultAction {
    @Resource
    private BaseService baseService;
    @Resource
    private UserService userService;
    @Resource
    private KHCRedisCache khcRedisCache;
    @Resource
    private ApiService apiService;
    @Resource
    private RedisPublication redisPublication;
    private static DataSystemNotifyAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.khcRedisCache =this.khcRedisCache;
        action.redisPublication =this.redisPublication;
    }

    @Override
    public JackJSONArray saveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        JackJSONObject json =array.getJackJSONObject(0);
        String sendTime=String.valueOf(json.get("send_time"));
        if(!sendTime.equals("null")&&sendTime.length()>0){//有发送时间直接return;
            return super.saveAfter(jsonStr, retJson, request, array);
        }
        String systemNotifyStatus=String.valueOf(json.get("system_notify_status"));
        if(!systemNotifyStatus.equals("1")){//1立即发送，2暂存  (暂存立即return;)
            return super.saveAfter(jsonStr, retJson, request, array);
        }
        String receiveUserStr=String.valueOf(json.get("receive_user"));
        String pageParentUuid=String.valueOf(json.get("uuid"));
        String[] userIdArr=receiveUserStr.split(",");
        for (int i = 0; i < userIdArr.length; i++) {
            if(!userIdArr[i].equals("")){
                User receiveUser=action.userService.getUser(Long.valueOf(userIdArr[i]));
                String queryCountSql="select count(1) from tbl_data_system_notify_user " +
                        "where page_parent_uuid='"+pageParentUuid+"' and create_user_id='"+receiveUser.getId()+"'";
                Integer count=this.getJdbcTemplate().queryForObject(queryCountSql,Integer.class);
                if(count==0){
                    Map<String,Object> saveDataMap=new HashMap<>();
                    saveDataMap.put("page_parent_uuid",pageParentUuid);//父级uuid
                    saveDataMap.put("is_read","N");//是否阅读，默认否
                    saveDataMap.put("read_time","");//阅读时间，默认空
                    action.baseService.save("tbl_data_system_notify_user",saveDataMap,receiveUser);
                    action.redisPublication.sendMessage("{\"wsCode\":\"initSystemNotify\",\"message\":\"你有新的系统通知\"}",String.valueOf(receiveUser.getId()));
                }
            }
        }
        DateTime d=new DateTime();
        sendTime=d.toString("yyyy-MM-dd HH:mm:ss");
        String uuid=action.apiService.getDataSourceUuid(jsonStr);
        String tableName=String.valueOf(action.apiService.findDataSourceByUuid(uuid).get("ds_table_name"));
        String updateSql="update "+tableName+" set send_time='"+sendTime+"',system_notify_status='3' " +
                "where uuid='"+pageParentUuid+"'";
        this.getJdbcTemplate().execute(updateSql);
        return super.saveAfter(jsonStr, retJson, request, array);
    }

    public JackJSONArray systemNotifyInfoSaveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        User user=action.userService.getUser(request);
        DateTime d=new DateTime();
        String readTime=d.toString("yyyy-MM-dd HH:mm:ss");
        String updateSql="update tbl_data_system_notify_user set is_read='Y' ,read_time='"+readTime+"'" +
                "where page_parent_uuid='"+array.getJackJSONObject(0).get("uuid")+"' and create_user_id='"+user.getId()+"';";
        this.getJdbcTemplate().execute(updateSql);
        retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("ok")));
        Map<String,Object> map=new HashMap<>();
        map.put("saveData",array);
        retJson.put("data",map);
        action.redisPublication.sendMessage("{\"wsCode\":\"initSystemNotify\"}",String.valueOf(user.getId()));
        return new JackJSONArray();
    }

    public Map<String,Object> getSystemNotifyList(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        User user=action.userService.getUser(request);
        Map<String,Object> map=new HashMap<>();
        String uuid=action.apiService.getDataSourceUuid(jsonStr);
        String tableName=String.valueOf(action.apiService.findDataSourceByUuid(uuid).get("ds_table_name"));
        String sql="select s.* from "+tableName+" s left join tbl_data_system_notify_user su on s.uuid=su.page_parent_uuid \n" +
                "WHERE su.create_user_id='"+user.getId()+"' AND su.is_read='N' order by send_time desc;";
        map.put("data",this.getJdbcTemplate().queryForList(sql));
        return map;
    }

}
