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.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataFormInfoAction extends DefaultAction {
    //表单组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_FORM_JSON="system.settings.ds.form.json";
    @Autowired
    private BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApiService apiService;
    @Autowired
    private KHCRedisCache khcRedisCache;
    private static DataFormInfoAction 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> initFormField(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 queryTableNameSql="SELECT ds_table_name FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_form WHERE status=0 and uuid='"+formUUID+"')";
        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_form_info where status=0 and name='"+name+"' and page_parent_uuid='"+formUUID+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count==0){
                    Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_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", formUUID);
                    viewMap.put("name",name);
                    viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("comment")));
                    action.baseService.save("tbl_data_form_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_form_info where status=0 and name='"+name+"' and page_parent_uuid='"+formUUID+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count==0){
                    Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_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", formUUID);
                    viewMap.put("name",name);
                    viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("Comment")));
                    action.baseService.save("tbl_data_form_info",viewMap);
                }
            }
        }
        map.put("message","同步成功");
        action.khcRedisCache.deleteAllFormInfo();//清除缓存的表结构信息
        return map;
    }

    @Override
    public JackJSONArray saveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            JackJSONObject formFieldInfo=array.getJackJSONObject(i);
            String textMaskStringConfig=String.valueOf(formFieldInfo.get("text_mask_string_config"));
            if(!textMaskStringConfig.equals("null")&&textMaskStringConfig.length()>0&&!textMaskStringConfig.contains("\\\\")){
                array.getJackJSONObject(i).put("text_mask_string_config",textMaskStringConfig.replace("\\","\\\\"));
            }
            String textMaskNumberConfig=String.valueOf(formFieldInfo.get("text_mask_number_config"));
            if(!textMaskNumberConfig.equals("null")&&textMaskNumberConfig.length()>0&&!textMaskNumberConfig.contains("\\\\")){
                array.getJackJSONObject(i).put("text_mask_number_config",textMaskNumberConfig.replace("\\","\\\\"));
            }
        }
        return super.saveBefore(jsonStr, retJson, request, array);
    }

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

    @Override
    public String deleteAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        action.khcRedisCache.deleteAllFormInfo();//清除缓存的表结构信息
        return super.deleteAfter(jsonStr, retJson, request);
    }
    public Map<String,Object> queryDsCodeAndFormCode(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 queryFormCodeSql="SELECT form_code FROM tbl_data_form WHERE status=0 and uuid='"+formUUID+"'";
        String formCode=this.getJdbcTemplate().queryForObject(queryFormCodeSql,String.class);
        String queryDsCodeSql="SELECT ds_code FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_form WHERE status=0 and uuid='"+formUUID+"')";
        String dsCode=this.getJdbcTemplate().queryForObject(queryDsCodeSql,String.class);
        map.put("message","查询成功");
        map.put("ds_code",dsCode);
        map.put("form_code",formCode);
        action.khcRedisCache.deleteAllFormInfo();//清除缓存的表结构信息 todo 这里应该按uuid清除 暂时清除全部的
        return map;
    }
}

