package com.chenyang.nse.bussiness.service.info.db;

import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleFastManage;
import com.power.xml.entity.ColumnInfo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

public class MSSQLSERVER extends CommonMethod implements DatabaseTool {
   public static final String[][] exporttype = new String[][]{{"normal", "正常导出", "selected"}};
   public static final String[][] importtype = new String[][]{{"normal", "正常导入", "selected"}};

   public String ImportMethod() {
      StringBuffer targetradio = new StringBuffer();
      List<TConsoleFastManage> list = this.tConsoleFastManageDao.queryAll(new Criterion[]{Restrictions.eq("databasetype", this.getClass().getSimpleName())});
      if (!list.isEmpty()) {
         TConsoleFastManage tConsoleFastManage = (TConsoleFastManage)list.get(0);
         if (tConsoleFastManage.getFastimport() == 0) {
            targetradio.append(MessageFormat.format(this.targetradio(), "'normal'", "正常导出", "selected"));
         } else {
            targetradio.append("<select name='execution_type' >");

            for(String[] radio : importtype) {
               targetradio.append(MessageFormat.format(this.sourceradio(), "'" + radio[0] + "'", radio[1], radio[2]));
            }

            targetradio.append("</select>");
         }
      } else {
         targetradio.append("<select name='execution_type' >");

         for(String[] radio : importtype) {
            targetradio.append(MessageFormat.format(this.sourceradio(), "'" + radio[0] + "'", radio[1], radio[2]));
         }

         targetradio.append("</select>");
      }

      return targetradio.toString();
   }

   public String ExportMethod() {
      StringBuffer sourceradio = new StringBuffer();
      sourceradio.append("<select name='execution_type' >");

      for(String[] radio : exporttype) {
         sourceradio.append(MessageFormat.format(this.sourceradio(), "'" + radio[0] + "'", radio[1], radio[2]));
      }

      sourceradio.append("</select>");
      return sourceradio.toString();
   }

   public Map TargetParameter_normal() {
      Map<String, String> map = this.TargetParameter_fnormal();
      map.put("targetParameter", this.isrebuild() + this.isindex() + this.isprimary() + this.istrigger() + this.isfunction() + this.isconstraint() + this.isview());
      return map;
   }

   public Map TargetParameter_normal1() {
      Map<String, String> map = this.TargetParameter_fnormal();
      map.put("targetParameter", this.isrebuild() + this.isindex() + this.isprimary() + this.istrigger() + this.isfunction());
      return map;
   }

   public Map TargetParameter_notNormal() {
      Map<String, String> map = new HashMap();
      map.put("targetParameter", this.isrebuild());
      return map;
   }

   public List<StringBuffer> SynTriggersParam(Connection s_conn, Map map) {
      List<StringBuffer> listTriggers = new ArrayList();
      String targetSchemaName = (String)map.get("targetSchemaName");
      String sourceSchemaName = (String)map.get("sourceSchema");
      PreparedStatement ps = null;
      ResultSet rs = null;
      String sql = "select  b.[definition] from sys.all_objects a,sys.sql_modules b where a.is_ms_shipped=0 and a.object_id = b.object_id and a.[type] in ('TR') order by a.[name] asc";

      try {
         ps = s_conn.prepareStatement(sql);
         rs = ps.executeQuery();

         while(rs.next()) {
            StringBuffer sb = new StringBuffer();
            if (rs.getString("definition").contains("[" + sourceSchemaName + "]")) {
               sb.append(rs.getString("definition").replaceAll(sourceSchemaName, targetSchemaName));
               listTriggers.add(sb);
               System.out.println(sb.toString());
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (ps != null) {
               ps.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return listTriggers;
   }

   public List<StringBuffer> SynFunctionParam(Connection s_conn, Map map) {
      List<StringBuffer> listTriggers = new ArrayList();
      String targetSchemaName = (String)map.get("targetSchemaName");
      String sourceSchemaName = (String)map.get("sourceSchema");
      PreparedStatement ps = null;
      ResultSet rs = null;
      String sql = "select  b.[definition] from sys.all_objects a,sys.sql_modules b where a.is_ms_shipped=0 and a.object_id = b.object_id and a.[type] in ('FN') order by a.[name] asc";

      try {
         ps = s_conn.prepareStatement(sql);
         rs = ps.executeQuery();

         while(rs.next()) {
            StringBuffer sb = new StringBuffer();
            if (rs.getString("definition").contains("[" + sourceSchemaName + "]")) {
               sb.append(rs.getString("definition").replaceAll(sourceSchemaName, targetSchemaName));
               listTriggers.add(sb);
               System.out.println(sb.toString());
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (ps != null) {
               ps.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return listTriggers;
   }

   public List<StringBuffer> SynProcedureParam(Connection s_conn, Map map) {
      List<StringBuffer> listTriggers = new ArrayList();
      String targetSchemaName = (String)map.get("targetSchemaName");
      String sourceSchemaName = (String)map.get("sourceSchema");
      PreparedStatement ps = null;
      ResultSet rs = null;
      String sql = "select  b.[definition] from sys.all_objects a,sys.sql_modules b where a.is_ms_shipped=0 and a.object_id = b.object_id and a.[type] in ('P') order by a.[name] asc";

      try {
         ps = s_conn.prepareStatement(sql);
         rs = ps.executeQuery();

         while(rs.next()) {
            StringBuffer sb = new StringBuffer();
            if (rs.getString("definition").contains("[" + sourceSchemaName + "]")) {
               sb.append(rs.getString("definition").replaceAll(sourceSchemaName, targetSchemaName));
               listTriggers.add(sb);
               System.out.println(sb.toString());
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (ps != null) {
               ps.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return listTriggers;
   }

   public ColumnInfo getPwc_columnInfo_target(Map map) {
      ColumnInfo columnInfo = this.getPwc_columnInfo_target_all_base(map);
      return columnInfo;
   }

   public ColumnInfo getPwc_columnInfo_source(Map map) {
      ColumnInfo columnInfo = this.getPwc_columnInfo_source_all_base(map);
      return columnInfo;
   }

   public List<StringBuffer> SynViewParam(Connection s_conn, Map map) {
      List<StringBuffer> listProcedure = new ArrayList();
      PreparedStatement ps = null;
      ResultSet rs = null;
      ResultSet rss = null;
      String targetSchemaName = (String)map.get("targetSchemaName");
      String sourceSchemaName = (String)map.get("sourceSchemaName");
      String sourceSchema = (String)map.get("sourceSchema");
      String tableName = (String)map.get("tableName");
      String sql_user = "select distinct text from syscomments where id in (select id from sysobjects where type  in('V')) and text like '%" + tableName + "%'";

      try {
         ps = s_conn.prepareStatement(sql_user);
         rs = ps.executeQuery();

         while(rs.next()) {
            StringBuffer sb = new StringBuffer();
            String sql = rs.getString("text");
            String substring = sql.substring(0, sql.indexOf("VIEW") + 5);
            String substring1 = sql.substring(sql.indexOf("VIEW") + 5);
            if (substring1.indexOf(".") != -1) {
               substring1 = substring1.substring(substring1.indexOf(".") + 1);
            }

            sql = substring + targetSchemaName + "." + substring1;
            String sbustring2 = sql.substring(0, sql.indexOf("FROM") + 5);
            String sbustring3 = substring1.substring(substring1.indexOf("FROM") + 5);
            if (sbustring3.indexOf(".") != -1) {
               sbustring3 = sbustring3.substring(sbustring3.indexOf(".") + 1);
            }

            sql = sbustring2 + targetSchemaName + "." + sbustring3;
            sb.append(sql);
            listProcedure.add(sb);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (ps != null) {
               ps.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return listProcedure;
   }

   public String SynConstraintParam(Connection srcconn, Map map) {
      return null;
   }

   public String SynPartition(Connection s_conn, Map map) {
      PreparedStatement ps = null;
      ResultSet rs1 = null;
      ResultSet rss = null;
      ResultSet rsss = null;
      ResultSet rssss = null;
      ResultSet rsssss = null;
      ResultSet rssssss = null;
      Connection t_conn = (Connection)map.get("t_conn");
      String sourceSchemaName = (String)map.get("sourceSchemaName");
      String sourceTableName = (String)map.get("tableName");
      String returnsql = "";
      String sql = "select convert(varchar(50), ps.name ) as partition_scheme,p.partition_number,convert(varchar(30), ds2.name ) as filegroup,convert(varchar(30), isnull(v.value, ''), 120) as range_boundary,str(p.rows, 9) as rows from sys.indexes i join sys.partition_schemes ps on i.data_space_id = ps.data_space_id join sys.destination_data_spaces dds on ps.data_space_id = dds.partition_scheme_id join sys.data_spaces ds2 on dds.data_space_id = ds2.data_space_id join sys.partitions p on dds.destination_id = p.partition_number and p.object_id = i.object_id and p.index_id = i.index_id join sys.partition_functions pf on ps.function_id = pf.function_id LEFT JOIN sys.Partition_Range_values v on pf.function_id = v.function_id and v.boundary_id = p.partition_number - pf.boundary_value_on_right WHERE i.object_id = object_id('" + sourceTableName + "') and i.index_id in (0, 1)  order by p.partition_number";
      String sqlType = "false";
      String filegroup = "";
      String range_boundary = "";
      String partition_scheme = "";
      String sql111 = "";
      int cnt1 = 0;
      int cnt = 0;
      Boolean s = false;

      try {
         ps = s_conn.prepareStatement(sql);

         for(rs1 = ps.executeQuery(); rs1.next(); ++cnt1) {
            s = true;
            filegroup = rs1.getString("filegroup");
            range_boundary = rs1.getString("range_boundary");
            partition_scheme = rs1.getString("partition_scheme");
            if (!"primary".equalsIgnoreCase(filegroup)) {
               String selectFileGroup = "select * from sys.filegroups S where S.name ='" + filegroup + "'";
               ps = s_conn.prepareStatement(selectFileGroup);
               rss = ps.executeQuery();
               if (!rss.next()) {
                  String creatGroup = "ALTER DATABASE " + sourceSchemaName + " ADD FILEGROUP  " + filegroup;
                  ps = t_conn.prepareStatement(creatGroup);
                  rsss = ps.executeQuery();
               }
            }

            if (range_boundary != null && !"".equals(range_boundary)) {
               if (cnt == 0) {
                  sql111 = "CREATE PARTITION FUNCTION  " + partition_scheme + " ( Date )\tAS RANGE  RIGHT FOR VALUES ('" + range_boundary + "',";
                  ++cnt;
               } else {
                  sql111 = sql111 + "'" + range_boundary + "')";
               }
            }
         }

         if (s) {
            String sql11111 = "CREATE PARTITION SCHEME  " + partition_scheme + " \tAS PARTITION parfn_Date5 TO (";
            s_conn.prepareStatement(sql111);

            for(int i = 0; i == cnt1; ++i) {
               sql11111 = sql11111 + "[primary]";
               if (i != cnt1) {
                  sql11111 = sql11111 + ",";
               } else {
                  sql11111 = sql11111 + ")";
               }
            }

            s_conn.prepareStatement(sql11111);
            String sqlwww = "select c.name,a.* from sys.index_columns a join sys.tables b on a.object_id=b.object_id join sys.columns c on c.object_id=b.object_id and a.column_id=c.column_id \twhere b.name='" + sourceTableName + "' and a.partition_ordinal=1 and a.index_id<2";
            ps = s_conn.prepareStatement(sqlwww);
            rssssss = ps.executeQuery();

            String name1;
            for(name1 = ""; rssssss.next(); name1 = rssssss.getString("name")) {
            }

            if (!"".equals(name1)) {
               returnsql = "ON  " + partition_scheme + "([" + name1 + "])";
            } else {
               returnsql = "false";
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs1 != null) {
               rs1.close();
            }

            if (ps != null) {
               ps.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return returnsql;
   }

   public Map TargetParameter_normalEM() {
      return null;
   }
}
