package com.huigou.topsun.dataPermission.application.impl;

import com.huigou.context.Operator;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.topsun.dataPermission.application.DataPermissionApplication;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author xin.lu
 * @Description: TODO
 * @date 2022/2/717:13
 */
@Service("dataPermissionApplication")
public class DataPermissionApplicationImpl extends BaseApplication implements DataPermissionApplication {

    static String QUERY_XML_FILE_PATH = "config/topsun/dataPermission/dataPermissions.xml";

    private QueryDescriptor getQueryDescriptor(String entityName) {
        return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, entityName);
    }
    @Override
    public void getDataManagePermission(StringBuffer sb) {
        List <Map<String,Object>>bizListdatas= this.queryBizDataManagePermission();
        if (bizListdatas.size()>0) {
            sb.append(" and ( t.PERSON_MEMBER_ID like '").append(ThreadLocalUtil.getOperator().getUserId()).append("%'");
            bizListdatas.forEach((o) -> {
                sb.append(" or t.full_id like '%" + o.get("fullId").toString() + "%'");
            });
            sb.append(")");
        } else {//默认只能查看自己的数据
            sb.append(" and t.PERSON_MEMBER_ID like '").append(ThreadLocalUtil.getOperator().getUserId()).append("%'");
        }
    }

    public  List<Map<String, Object>> queryDataManagePermissions(){
        String sql = getQueryDescriptor("queryDataManagePermissions").getSql();
        Operator operator = ThreadLocalUtil.getOperator();
        String  psmId=operator.getFullId().replaceAll("\\.ogn","");
        psmId=psmId.replaceAll("\\.dpt","");
        psmId=psmId.replaceAll("\\.pos","");
        psmId=psmId.replaceAll("\\.psm","");
        String []allCondi=psmId.split("/");
        sql+=" and (";
        for (int u=1;u<allCondi.length;u++){
            sql+="t.manager_id='"+allCondi[u]+"'";
            if (u<allCondi.length-1){
                sql+=" or ";
            }
        }
        sql+=" )";

        return this.sqlExecutorDao.queryToListMap(sql);

    }

    public  List<Map<String, Object>> queryBizDataManagePermission(){
        String sql = getQueryDescriptor("queryBizDataManagePermission").getSql();
        Operator operator = ThreadLocalUtil.getOperator();
        return this.sqlExecutorDao.queryToListMap(sql,operator.getUserId()+"%");

    }

    public void getDataPermission(StringBuffer sb,Map map,List <Map<String,Object>>bizListdatas){

        List<Map<String, Object>> permissions = this.queryDataManagePermissionDetail(map.get("dataManagedetalId").toString());
        switch(map.get("dataKind").toString())
        {
            case "org":
                sb.append(getOrgConditions(permissions,bizListdatas));
                break;

            case "dictionary":
                sb.append(getDictionaryConditions(permissions,map.get("dataManageId").toString(),map.get("dataKindCode").toString(),bizListdatas));
                break;

            case "enum":
                sb.append(getEnumConditions(permissions,map.get("dataManageId").toString(),map.get("dataKind").toString(),bizListdatas));
                break;

            case "define":
                //sb=new StringBuffer("");    //待完善
                // List<Map<String, Object>> bussinessFields = this.queryDataManageBussinessFields(map.get("dataManageId").toString(),map.get("dataKind").toString());
                String sql="";
                break;

            case "input":

                List<Map<String, Object>> bussinessFields2 = this.queryDataManageBussinessFields(map.get("dataManageId").toString(),map.get("dataKind").toString());
                final StringBuffer  sqlInput=new StringBuffer("");
                sqlInput.append( " and (");
                for (int u=0;u<permissions.size();u++) {
                    String resourceVal = permissions.get(u).get("resourceKey").toString();
                    for (Map mapField:bussinessFields2) {
                        String tableColumn = mapField.get("tableColumn").toString();
                        String columnSymbol =  mapField.get("columnSymbol").toString();
                        if (u>0){
                            sqlInput.append(  " or ");
                        }
                        sqlInput.append("  t.").append(tableColumn).append(" ").append(columnSymbol).append(" '");
                        if ("like".equals(columnSymbol)){
                            sqlInput.append("%");
                        }
                        sqlInput.append(resourceVal);
                        if ("like".equals(columnSymbol)){
                            sqlInput.append("%");
                        }
                        sqlInput.append("'");
                    }
                }
                bizListdatas.forEach((o) -> {
                    sqlInput.append(" or  t.full_id like '%").append(o.get("fullId").toString()).append("%'");
                });
                sqlInput.append(")");
                sb.append(sqlInput.toString());
                break;

            default:
        }
    }

    public  List<Map<String, Object>> queryDataManagePermissionDetail(String dataManagedetalId){
        String sql = getQueryDescriptor("queryDataManagePermissionDetail").getSql();
        return this.sqlExecutorDao.queryToListMap(sql,dataManagedetalId);

    }

    public  String  getOrgConditions(List<Map<String, Object>> permissions,List <Map<String,Object>>bizListdatas){
        Operator operator = ThreadLocalUtil.getOperator();
        final StringBuffer  sql=new StringBuffer("");
        if (permissions.size() > 0) {
            sql.append( " and (");
            for (int k = 0; k < permissions.size(); k++) {
                Map map = permissions.get(k);
                //if ("org".equals(map.get("dataKind").toString())) {  //是组织机构
                String []fullIds=map.get("fullId").toString().replaceFirst("/","").split("\\/");
                String bus=fullIds[fullIds.length-1].split("\\.")[1];
                sql.append( " t.full_id like '%").append( map.get("resourceKey").toString()).append(".").append(bus).append("%'");
                if (k < permissions.size() - 1) {
                    sql.append( " or ");
                }
                //}
            }
            bizListdatas.forEach((o) -> {
                sql.append( " or  t.full_id like '%").append(o.get("fullId").toString()).append("%'");
            });
            sql.append(" or t.full_id like '%").append( operator.getPersonMemberId()).append(".psm%'");  //允许查看自己的
            sql.append(  ")");
            if (sql.toString().length() < 10) {
                sql.append("");
            }
        } else {
            sql.append(" or  t.full_id like '%").append(operator.getPersonMemberId()).append(".psm%'");
        }
        return  sql.toString();
    }



    public String getDictionaryConditions(List<Map<String, Object>> permissions,String dataManageId,String dataKindCode,List <Map<String,Object>>bizListdatas){

        List<Map<String, Object>> permissionFields=this.queryDataManagePermissionFields(dataManageId,dataKindCode);
        final StringBuffer  sql=new StringBuffer("");
        sql.append(" and (t.");
        Map map=permissionFields.get(0);
        //and f.table_column and f.column_data_type  and f.column_symbol
        sql.append(map.get("tableColumn").toString());
        if (permissions.size() > 0) {
            if (permissions.size()>1){  //多个值 ，换成in
                sql.append(" in (");
            } else {
                sql.append(map.get("columnSymbol").toString());
            }
            for (int k = 0; k < permissions.size(); k++) {
                Map maps = permissions.get(k);
                if (map.get("columnDataType").toString().indexOf("String")>0
                        ||map.get("columnDataType").toString().indexOf("Date")>0
                ) {   //Integer   Long  Bigdecimal
                    sql.append("'").append(maps.get("resourceKey").toString()).append("'");
                }  else if (map.get("columnDataType").toString().indexOf("Integer")>0
                        ||map.get("columnDataType").toString().indexOf("Long")>0
                        ||map.get("columnDataType").toString().indexOf("Bigdecimal")>0
                ) {   //Integer   Long  Bigdecimal
                    sql.append( maps.get("resourceKey").toString());
                }
                if (k<permissions.size()-1){
                    sql.append(",");
                }
            }
            if (permissions.size()>1){  //多个值 ，换成in
                sql.append(" ) ");
            }
            bizListdatas.forEach((o) -> {
                sql.append( " or  t.full_id like '%").append(o.get("fullId").toString()).append("%'");
            });
            sql.append(")");
        }
        return sql.toString();
    }
    //枚举条件in ('','')   定义时格式,,
    public String getEnumConditions(List<Map<String, Object>> permissions,String dataManageId,String dataKindCode,List <Map<String,Object>>bizListdatas){

        List<Map<String, Object>> bussinessFields = this.queryDataManageBussinessFields(dataManageId,dataKindCode);
        final StringBuffer  sql=new StringBuffer("");
        sql.append(" and  (t.");
        Map map=bussinessFields.get(0);

        sql.append(map.get("tableColumn").toString());
        sql.append(" ").append(map.get("columnSymbol").toString()).append(" (");
        if (bussinessFields.size()>0){
            for (int k = 0; k < bussinessFields.size(); k++) {
                Map maps = bussinessFields.get(k);
                String dataVals=maps.get("dataSource").toString();
                // dataVals=dataVals.replaceAll("{","");
                // dataVals=dataVals.replaceAll("}","");
                String []dataval=dataVals.split(",");
                for (int n = 0; n <dataval.length;n++) {
                    if (map.get("columnDataType").toString().indexOf("String") > 0
                            || map.get("columnDataType").toString().indexOf("Date") > 0
                    ) {   //Integer   Long  Bigdecimal
                        sql.append("'").append( dataval[n]).append("'");
                    } else if (map.get("columnDataType").toString().indexOf("Integer") > 0
                            || map.get("columnDataType").toString().indexOf("Long") > 0
                            || map.get("columnDataType").toString().indexOf("Bigdecimal") > 0
                    ) {   //Integer   Long  Bigdecimal
                        sql.append(dataval[n]);
                    }
                    if (n<dataval.length-1){
                        sql.append(",");
                    }
                }
            }
            sql.append(")");
            bizListdatas.forEach((o) -> {
                sql.append( " or  t.full_id like '%").append(o.get("fullId").toString()).append("%'");
            });
            sql.append(")");
        }
        return sql.toString();

    }

    public String getDefineConditions(List<Map<String, Object>> permissions,String dataManageId,String dataKindCode){
        return "";
    }
    public String getInputConditions(List<Map<String, Object>> permissions,String dataManageId,String dataKindCode){
        return "";
    }

    public  List<Map<String, Object>> queryDataManagePermissionFields(String dataManageId,String dataKindCode){
        String sql = getQueryDescriptor("queryDataManagePermissionFields").getSql();
        return this.sqlExecutorDao.queryToListMap(sql,dataManageId,dataKindCode);

    }

    public  List<Map<String, Object>> queryDataManageBussinessFields(String dataManageId,String dataKind){
        String sql = getQueryDescriptor("queryDataManageBussinessFields").getSql();
        return this.sqlExecutorDao.queryToListMap(sql,dataManageId,dataKind);

    }
}
