package cn.com.capcloud.core.noentitydb;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
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.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.JdbcTemplate;
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.List;
import java.util.Map;

@Component
public class DefaultAction implements DefaultActionFace {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private ApiService apiService;
    @Resource
    private UserService userService;
    @Resource
    private BaseService baseService;
    @Resource
    private RedisPublication redisPublication;
    private static DefaultAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.jdbcTemplate=this.jdbcTemplate;
        setJdbcTemplate(this.jdbcTemplate);
        action.apiService =this.apiService;
        action.userService =this.userService;
        action.baseService=this.baseService;
    }
    @Override
    public String buildSql(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        User user=action.userService.getUser(request);
        List<Map<String,Object>> fieldList=action.apiService.getQueryInfo(jsonStr);
        String uuid=action.apiService.getDataSourceUuid(jsonStr);
        Map<String,Object> dsMap=action.apiService.findDataSourceByUuid(uuid);
        Map<String,Object> formMap=action.apiService.getForm(jsonStr);
        Map<String,Object> queryMap=action.apiService.getQuery(jsonStr);
        String isChildPage=String.valueOf(formMap.get("is_child_page"));//是否子表 如果是判断有没有查询条件（parentUuid），没有则不做查询
        String queryNotNullField=String.valueOf(queryMap.get("query_not_null_field"));//必查项字段，如果为空则返回不查询
        String tableName=action.apiService.getDsTableName(dsMap,queryMap,user);
        JackJSONObject queryParamJson=JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        if(isChildPage.equals("Y")){//todo 这个以后废弃了，从query组件设置字段
            if(queryParamJson!=null){
                String parentUUID=String.valueOf(queryParamJson.get("page_parent_uuid"));
                if("null".equals(parentUUID)||parentUUID.length()==0){
                    return "select * from "+tableName+" _khc where 1=2";
                }
            }
        }
        if(!queryNotNullField.equals("null")&&queryNotNullField.length()>0){
            String[] arr = queryNotNullField.split(",");
            for (int i = 0; i < arr.length; i++) {
                if(!arr[i].equals("")){
                    String notNullField=String.valueOf(queryParamJson.get(arr[i]));
                    if("null".equals(notNullField)||notNullField.length()==0){
                        return "select * from "+tableName+" _khc where 1=2";
                    }
                }
            }
        }
        String isTree=String.valueOf(formMap.get("is_tree"));//是否tree
        if(isTree.equals("Y")&&queryParamJson!=null){
            String isRecursion=String.valueOf(formMap.get("is_recursion"));//是否递归
            JackJSONObject requestJson=JackJSONObject.fromObject(jsonStr);
            requestJson.getJackJSONObject("queryParam").put("isRecursion",isRecursion);
            jsonStr= JackJSON.toJSONString(requestJson);
        }
        String tableSql="select * from "+tableName+" _khc ";
        String whereSql="";
        whereSql+=action.apiService.getWhereSqlByFieldInfo(tableSql,fieldList, jsonStr,jdbcTemplate,retJson);
        return whereSql;
    }

    @Override
    public String buildPowerSql(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        User user=action.userService.getUser(request);
        String sql=" ";
        Map<String,Object> queryMap=action.apiService.getQuery(jsonStr);
        List<Map<String,Object>> fieldList=action.apiService.getQueryInfo(jsonStr);
        String viewAllRoleId=String.valueOf(queryMap.get("view_all_data_role_id"));
        boolean isQueryAll=false;
        if(!"null".equals(viewAllRoleId)&&viewAllRoleId.length()>0) {
            String[] roleIdArray = viewAllRoleId.split(",");
            for(int i=0;i<roleIdArray.length;i++) {
                if(action.userService.isExistsRole(roleIdArray[i], user.getId())) {
                    isQueryAll=true;
                }
            }
        }
        if(!isQueryAll){
            //这里拼接时判断是否有该字段，没有则不拼接
            Map<String,Object> map=new HashMap<>();
            for (int i = 0; i < fieldList.size(); i++) {
                String fieldName=String.valueOf(fieldList.get(i).get("name"));
                map.put(fieldName,fieldList.get(i));//map里存一份用fieldInfo,fieldName为key
            }
            String queryStrategy=String.valueOf(queryMap.get("query_strategy"));
            if(queryStrategy.equals("1")) {
                Map<String,Object> fieldInfo= (Map<String, Object>) map.get("create_user_id");
                if(fieldInfo!=null){
                    sql+=" and create_user_id='"+user.getId()+"' ";
                }
            }else if(queryStrategy.equals("2")) {
                Map<String,Object> fieldInfo= (Map<String, Object>) map.get("create_org_id");
                if(fieldInfo!=null){
                    sql+=" and create_org_id="+user.getOrgId()+" ";
                }
            }else if(queryStrategy.equals("3")) {
                Map<String,Object> fieldInfo= (Map<String, Object>) map.get("create_org_id");
                if(fieldInfo!=null){
                    sql+=" and FIND_IN_SET(create_org_id,tree_org('"+user.getOrgId()+"')) ";
                }
            }
        }
        return sql;
    }

    @Override
    public String buildSqlCount(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        return this.buildSql(jsonStr,retJson, request);
    }

    @Override
    public String buildDeleteSql(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        String uuid=action.apiService.getDataSourceUuid(jsonStr);
        Map<String, Object>  dsMap=action.apiService.findDataSourceByUuid(uuid);
        String tableName=String.valueOf(dsMap.get("ds_table_name"));
        DateTime d = new DateTime();
        JackJSONArray pkIds=JackJSONObject.fromObject(jsonStr).getJackJSONArray("pkIds");
        String sql="UPDATE "+tableName+" SET status=1 ,update_time='"+d.toString("yyyy-MM-dd HH:mm:ss")+"'";
        String pkFieldName=String.valueOf(dsMap.get("ds_pk_id"));
        String whereIds="";
        for (int i = 0; i < pkIds.size(); i++) {
            whereIds+=pkIds.getJackJSONObject(i).get("pkId")+",";
        }
        whereIds=whereIds.substring(0,whereIds.length()-1);
        sql+=" where "+pkFieldName +" in ("+whereIds+")";
        return sql;
    }

    @Override
    public JtPage showAllDesensitize(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        List<Map<String,Object>> fieldList=action.apiService.getQueryInfo(jsonStr);
        for (int i = 0; i < fieldList.size(); i++) {
            Map<String,Object> filedMap=fieldList.get(i);
            String name=String.valueOf(filedMap.get("name"));
            String isDesensitize=String.valueOf(filedMap.get("is_desensitize"));
            String desensitizeType=String.valueOf(filedMap.get("desensitize_type"));
            if(isDesensitize.equals("Y")&&(desensitizeType.equals("1")||desensitizeType.equals("2"))){//type:1查询和导出都脱敏，type：2仅查询加密
                String desensitizeExpr=String.valueOf(filedMap.get("desensitize_expr"));
                String desensitizeReplacement=String.valueOf(filedMap.get("desensitize_replacement"));
                for (int j = 0; j < jtPage.getContent().size(); j++) {
                    String fileValue=String.valueOf(jtPage.getContent().get(j).get(name));
                    fileValue=fileValue.replaceAll(desensitizeExpr, desensitizeReplacement);
                    jtPage.getContent().get(j).put(name,fileValue);
                }
            }
        }
        return jtPage;
    }

    @Override
    public JtPage showAllDesensitizeExportExcel(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        List<Map<String,Object>> fieldList=action.apiService.getQueryInfo(jsonStr);
        for (int i = 0; i < fieldList.size(); i++) {
            Map<String,Object> filedMap=fieldList.get(i);
            String name=String.valueOf(filedMap.get("name"));
            String isDesensitize=String.valueOf(filedMap.get("is_desensitize"));
            String desensitizeType=String.valueOf(filedMap.get("desensitize_type"));
            if(isDesensitize.equals("Y")&&(desensitizeType.equals("1")||desensitizeType.equals("3"))){//type:1查询和导出都脱敏，type：3仅导出加密
                String desensitizeExpr=String.valueOf(filedMap.get("desensitize_expr"));
                String desensitizeReplacement=String.valueOf(filedMap.get("desensitize_replacement"));
                for (int j = 0; j < jtPage.getContent().size(); j++) {
                    String fileValue=String.valueOf(jtPage.getContent().get(j).get(name));
                    fileValue=fileValue.replaceAll(desensitizeExpr, desensitizeReplacement);
                    jtPage.getContent().get(j).put(name,fileValue);
                }
            }
        }
        return jtPage;
    }

    @Override
    public JtPage showAllAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        return jtPage;
    }
    @Override
    public JtPage showAllAfterExportExcel(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        return this.showAllAfter(jsonStr,retJson,request,jtPage);
    }

    @Override
    public Map<String, Object> importExcelDataBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        User user=action.userService.getUser(request);
        action.redisPublication.importExcelDataNew(jsonStr,retJson,request,user);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("message","操作成功");
        return dataMap;
    }

    @Override
    public String buildExcelSql(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        return this.buildSql(jsonStr, retJson, request);
    }

    @Override
    public JackJSONArray saveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        return array;
    }

    @Override
    public JackJSONArray saveAfter(String jsonStr,JackJSONObject retJson, HttpServletRequest request,JackJSONArray array) {
        return array;
    }

    @Override
    public Map<String, Object> findOneAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request,Map<String, Object> map) {
        return map;
    }

    @Override
    public Map<String, Object> findOneAfterExportExcel(String jsonStr, JackJSONObject retJson, HttpServletRequest request,Map<String, Object> map) {
        return this.findOneAfter(jsonStr,retJson,request,map);
    }

    @Override
    public Map<String, Object> findOneAfterExportWord(String jsonStr, JackJSONObject retJson, HttpServletRequest request, Map<String, Object> map) {
        return this.findOneAfter(jsonStr,retJson,request,map);
    }

    @Override
    public String deleteBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        return "0";//返回-1终止流程，其他则相反
    }

    @Override
    public String deleteAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        return "0";//返回-1终止流程，其他则相反
    }
    @Override
    public String createPdf(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        return "0";//返回-1终止流程，其他则相反
    }

    @Override
    public Map<String, Object> initPageParameters(String jsonStr, HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        return dataMap;
    }

    @Override
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate=jdbcTemplate;
    }

    @Override
    public JdbcTemplate getJdbcTemplate() {
        return action.jdbcTemplate;
    }

}
