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.cache.KHCRedisCache;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.noentitydb.BaseDao;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DBCheck;
import cn.com.capcloud.core.noentitydb.DefaultAction;
import cn.com.capcloud.core.system.user.UserService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class DataQueryInfoAction extends DefaultAction {
    //查询组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_QUERY_JSON="system.settings.ds.query.json";
    @Autowired
    private BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApiService apiService;
    @Autowired
    private KHCRedisCache khcRedisCache;
    private static DataQueryInfoAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.khcRedisCache =this.khcRedisCache;
    }
    public Map<String,Object> initQueryField(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        Map<String,Object> map=new HashMap<>();
        String queryParentUUID=String.valueOf(json.get("page_parent_uuid"));
        String queryTableNameSql="SELECT ds_table_name FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_query WHERE status=0 and uuid='"+queryParentUUID+"')";
        String tableName=this.getJdbcTemplate().queryForObject(queryTableNameSql,String.class);
        if(DBCheck.isKingbase()){
            List<Map<String,Object>> colInfoList= BaseDao.getAllCommentsByTableNameNotPkField(tableName, this.getJdbcTemplate(),"");
            for(int i=0;i<colInfoList.size();i++) {
                String name=String.valueOf(colInfoList.get(i).get("column_name"));
                String sql="select count(1) from tbl_data_query_info where status=0 and name='"+name+"' and page_parent_uuid='"+queryParentUUID+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count==0){
                    Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_QUERY_JSON));
                    if(colInfoList.get(i).get("data_type").toString().indexOf("int4")>=0) {
                        viewMap.put("type","long");
                    }else {
                        viewMap.put("type","String");
                    }
                    if(name.equals("status")){
                        viewMap.put("default_value", "0");
                    }
                    DateTime d = new DateTime();
                    viewMap.put("create_time", d.toString("yyyy-MM-dd HH:mm:ss"));
                    viewMap.put("page_parent_uuid", queryParentUUID);
                    viewMap.put("name",name);
                    viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("comment")));
                    action.baseService.save("tbl_data_query_info",viewMap);
                }
            }
        }else{
            List<Map<String,Object>> colInfoList= BaseDao.getAllCommentsByTableName(tableName, this.getJdbcTemplate());
            for(int i=0;i<colInfoList.size();i++) {
                String name=String.valueOf(colInfoList.get(i).get("Field"));
                String sql="select count(1) from tbl_data_query_info where status=0 and name='"+name+"' and page_parent_uuid='"+queryParentUUID+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count==0){
                    Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_QUERY_JSON));
                    if(colInfoList.get(i).get("Type").toString().indexOf("int")>=0) {
                        viewMap.put("type","long");
                    }else {
                        viewMap.put("type","String");
                    }
                    if(name.equals("status")){
                        viewMap.put("default_value", "0");
                    }
                    DateTime d = new DateTime();
                    viewMap.put("create_time", d.toString("yyyy-MM-dd HH:mm:ss"));
                    viewMap.put("page_parent_uuid", queryParentUUID);
                    viewMap.put("name",name);
                    viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("Comment")));
                    action.baseService.save("tbl_data_query_info",viewMap);
                }
            }
        }
        map.put("message","同步成功");
        action.khcRedisCache.deleteAllQueryInfo();//清除缓存的表结构信息
        return map;
    }
    @Override
    public JackJSONArray saveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        action.khcRedisCache.deleteAllQueryInfo();//清除缓存的表结构信息
        return super.saveAfter(jsonStr, retJson, request, array);
    }

    @Override
    public String deleteAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        action.khcRedisCache.deleteAllQueryInfo();//清除缓存的表结构信息
        return super.deleteAfter(jsonStr, retJson, request);
    }

    public Map<String,Object> queryDsCodeAndQueryCode(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        Map<String,Object> map=new HashMap<>();
        String formUUID=String.valueOf(json.get("page_parent_uuid"));
        String queryQueryCodeSql="SELECT query_code FROM tbl_data_query WHERE status=0 and uuid='"+formUUID+"'";
        String queryCode=this.getJdbcTemplate().queryForObject(queryQueryCodeSql,String.class);
        String queryDsCodeSql="SELECT ds_code FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_query WHERE status=0 and uuid='"+formUUID+"')";
        String dsCode=this.getJdbcTemplate().queryForObject(queryDsCodeSql,String.class);
        map.put("message","查询成功");
        map.put("ds_code",dsCode);
        map.put("query_code",queryCode);
        action.khcRedisCache.deleteAllFormInfo();//清除缓存的表结构信息 todo 这里应该按uuid清除 暂时清除全部的
        return map;
    }

}

