管道基础大数据平台系统开发-【CS】-ExportMap
13693261870
2024-09-03 3cfb6aa02516135fb174ab1b30620f2007924663
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
using JavaCode.cs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
 
namespace JavaCode
{
    public partial class FrmEtown : Form
    {
        #region 成员变量+构造函数
        private static List<string> excludes = new List<string>() { "gid", "eventid", "parentid", "dir", "dep", "createuser", "createtime", "updateuser", "updatetime", "geom", "remarks", "source", "fromsystem", "frequency", "objectid", "shape_leng", "shape_area" };
 
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;
 
        private PostgreHelper _dbHelper;
 
        private List<TabInfo> _list;
 
        public FrmEtown()
        {
            InitializeComponent();
            this.Load += new System.EventHandler(this.FrmEtown_Load);
        }
 
        private void FrmEtown_Load(object sender, EventArgs e)
        {
            _dbHelper = new PostgreHelper(DbEnum.etown);
        }
        #endregion
 
        #region 查询表结构:
        private void btnReadTab_Click(object sender, EventArgs e)
        {
            try
            {
                string tabName = this.txtTabPre.Text.Trim();
                string tabFilter = string.IsNullOrEmpty(tabName) ? "" : string.Format("and c.relname like '{0}%'", tabName);
 
                string sql = string.Format("select c.relname \"tab\", cast(obj_description(c.oid) as varchar) \"desc\", a.attnum \"num\", a.attname \"col\", t.typname \"type\", d.description \"bak\" from pg_attribute a left join pg_description d on d.objoid = a.attrelid and d.objsubid = a.attnum left join pg_class c on a.attrelid = c.oid left join pg_type t on a.atttypid = t.oid where a.attnum >= 0 and reltype>0 and relnamespace in ({0}) {1} and position('pg.dropped' in a.attname) = 0 order by c.relname desc, a.attnum asc", this.txtTabNS.Text.Trim(), tabFilter);
 
                DataTable dt = _dbHelper.GetDataTable(sql, null);
                _list = ModelHandler.FillModel<TabInfo>(dt);
                if (_list == null || _list.Count == 0)
                {
                    MessageBox.Show("没有查询到数据!");
                    return;
                }
 
                List<string> tabList = new List<string>();
                foreach (TabInfo ti in _list)
                {
                    if (!tabList.Contains(ti.tab))
                    {
                        tabList.Add(ti.tab);
                    }
                }
                this.tabList.DataSource = tabList;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void btnAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                this.tabList.SetSelected(i, true);
            }
        }
 
        private void btnAnti_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                bool flag = this.tabList.GetSelected(i);
                this.tabList.SetSelected(i, !flag);
            }
        }
 
        private void btnNone_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                this.tabList.SetSelected(i, false);
            }
        }
 
        private void tabList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string tab = this.tabList.SelectedItem as string;
            List<TabInfo> tabs = (from p in _list where p.tab == tab orderby p.num select p).ToList<TabInfo>();
 
            this.dgvTab.DataSource = new BindingList<TabInfo>(tabs);
            if (tabs != null && tabs.Count > 1)
            {
                this.dgvTab.Rows[1].Selected = true;
                this.dgvTab.CurrentCell = this.dgvTab.Rows[1].Cells[0];
            }
        }
        #endregion
 
        #region 按钮事件
        private void btnGeneMapper_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Path.Combine(baseDir, "Result\\Mapper");
 
                List<string> names = GetTabList();
                foreach (string name in names)
                {
                    List<TabInfo> tabs = GetTabInfo(name);
                    GenerateMapper(path, name, tabs);
                }
 
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void btnGeneEntity_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Path.Combine(baseDir, "Result\\Entity");
 
                List<string> names = GetTabList();
                foreach (string name in names)
                {
                    List<TabInfo> tabs = GetTabInfo(name);
                    GenerateEntity(path, name, tabs);
                }
 
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
 
        #region 生成 Mapper
        private void GenerateMapper(string path, string name, List<TabInfo> tabs)
        {
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
 
            string tabName = this.txtTabPrefix.Text.Trim() + name;
            string shortName = GetEntityName(name);
 
            string mapperNS = this.txtMapperNS.Text.Trim();
            string mapperName = shortName + "Mapper";
 
            string entityNS = this.txtEntityNS.Text.Trim();
            string entityName = shortName + "Entity";
 
            string ns = this.txtTabPrefix.Text.Trim();
            string bak = shortName;
            if (!string.IsNullOrEmpty(tabs[0].desc)) bak = tabs[0].desc.Replace("表", "");
 
            List<SysDict> dicts = SelectSysDicts(tabName);
            if (dicts != null) bak = dicts[0].descr;
 
            string javaFile = "Mapper.java";
            string xml = File.ReadAllText(Path.Combine(baseDir, "EtownTemplate\\" + javaFile));
            xml = xml
                .Replace("{mapperNS}", mapperNS)
                .Replace("{mapperName}", mapperName)
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{ns}", ns)
                .Replace("{bak}", bak)
                .Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd"));
 
            string fileName = shortName + "Mapper.java";
            File.WriteAllText(Path.Combine(path, fileName), xml);
        }
        #endregion
 
        #region 生成 Entity
        private void GenerateEntity(string path, string name, List<TabInfo> tabs)
        {
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
 
            string tabName = this.txtTabPrefix.Text.Trim() + name;
            //string shortName = NameConvert(name, true);
            string shortName = GetEntityName(name);
 
            string entityNS = this.txtEntityNS.Text.Trim();
            string entityName = shortName + "Entity";
 
            string ns = this.txtTabPrefix.Text.Trim();
            long uid = (long)Math.Floor((new Random()).NextDouble() * 1000000000000000000D);
 
            string bak = shortName;
            if (!string.IsNullOrEmpty(tabs[0].desc)) bak = tabs[0].desc.Replace("表", "");
            List<SysDict> dicts = SelectSysDicts(tabName);
            if (dicts != null) bak = dicts[0].descr;
 
            string javaFile = "Entity.java";
            string xml = File.ReadAllText(Path.Combine(baseDir, "EtownTemplate\\" + javaFile));
            xml = xml
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{bak}", bak)
                .Replace("{tabName}", tabName)
                .Replace("{ns}", ns)
                .Replace("{uid}", uid.ToString())
                .Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd"));
 
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\n    public " + entityName + "() {\r\n    }\r\n");
            foreach (TabInfo ti in tabs)
            {
                string type = GetJavaType(ti);
                if (excludes.Contains(ti.col)) continue;
                if (ti.col == "class")
                {
                    MessageBox.Show(ti.tab + "." + ti.col);
                    return;
                }
 
                sb.Append("\r\n");
                string colName = NameConvert(ti.col, false);
                //if ("references" == colName) sb.Append("    @TableField(value = \"\\\"references\\\"\")").Append("\r\n");
 
                SysDict dict = FindSysDict(dicts, ti.col);
                string alias = null == dict || string.IsNullOrEmpty(dict.alias) ? (string.IsNullOrEmpty(ti.bak) ? "" : ti.bak.Trim()) : dict.alias.Trim();
                sb.Append("    @ApiModelProperty(value = \"" + alias + "\")\r\n");
 
                sb.Append("    private " + type + " " + colName + ";\r\n");
            }
 
            foreach (TabInfo ti in tabs)
            {
                if (excludes.Contains(ti.col)) continue;
 
                string type = GetJavaType(ti);
                string col1 = NameConvert(ti.col, true);
                string col2 = NameConvert(ti.col, false);
 
                sb.Append("\r\n    public " + type + " get" + col1 + "() {\r\n        return " + col2 + ";\r\n    }\r\n");
                sb.Append("\r\n    public void set" + col1 + "(" + type + " " + col2 + ") {\r\n        this." + col2 + " = " + col2 + ";\r\n    }\r\n");
            }
            sb.Append("}\r\n");
            sb.Insert(0, xml);
 
            string fileName = shortName + "Entity.java";
            File.WriteAllText(Path.Combine(path, fileName), sb.ToString());
        }
        #endregion
 
        #region 生成所有
        private void btnGeneAll_Click(object sender, EventArgs e)
        {
            try
            {
                string mapperPath = Path.Combine(baseDir, "Result\\Mapper");
                string entityPath = Path.Combine(baseDir, "Result\\Entity");
 
                List<string> names = GetTabList();
                foreach (string name in names)
                {
                    try
                    {
                        List<TabInfo> tabs = GetTabInfo(name);
                        GenerateMapper(mapperPath, name, tabs);
                        GenerateEntity(entityPath, name, tabs);
                    }
                    catch (Exception ec)
                    {
                        MessageBox.Show(name + "\r\n" + ec.Message);
                    }
                }
 
                string path = Path.Combine(baseDir, "Result");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void txtTabPrefix_TextChanged(object sender, EventArgs e)
        {
            txtChanged(sender, e);
        }
 
        private void txtChanged(object sender, EventArgs e)
        {
            string pre = txtTabPrefix.Text.Replace(".", "").Trim();
            txtMapperNS.Text = "com.smartearth.system.mapper.sd".Replace("sd", pre).Replace("sd", pre);
            txtEntityNS.Text = "com.smartearth.system.domain.sd".Replace("sd", pre).Replace("sd", pre);
        }
        #endregion
 
        #region 公共方法
        private List<SysDict> SelectSysDicts(string table)
        {
            string[] strs = table.Split(new char[] { '.' });
            string sql = string.Format("select id,ns||'.'||tab table, descr, field, alias, type from se.sys_dict where ns='{0}' and tab='{1}' order by orderid", strs[0], strs[1]);
 
            DataTable dt = _dbHelper.GetDataTable(sql, null);
 
            List<SysDict> list = ModelHandler.FillModel<SysDict>(dt);
 
            return null == list || list.Count == 0 ? null : list;
        }
 
        private SysDict FindSysDict(List<SysDict> list, string field)
        {
            if (null == list) return null;
 
            return (from sd in list where sd.field == field select sd).FirstOrDefault();
        }
 
        private List<string> GetTabList()
        {
            List<string> list = new List<string>();
            for (int i = 0, c = this.tabList.SelectedItems.Count; i < c; i++)
            {
                string item = this.tabList.SelectedItems[i] as String;
                if (!string.IsNullOrEmpty(item))
                {
                    list.Add(item);
                }
            }
 
            return list;
        }
 
        private List<TabInfo> GetTabInfo(string name)
        {
            List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
 
            return tabs;
        }
 
        private static string GetEntityName(string name)
        {
            string[] strs = name.ToLower().Split(new char[] { '_' });
            for (int i = 0, c = strs.Length; i < c; i++)
            {
                strs[i] = ToUpperFirst(strs[i]);
            }
 
            return string.Join("", strs);
        }
 
        private static string NameConvert(string name, bool firstUpper)
        {
            string[] strs = name.ToLower().Split(new char[] { '_' });
            for (int i = 0, c = strs.Length; i < c; i++)
            {
                if (0 == i && !firstUpper) continue;
 
                strs[i] = ToUpperFirst(strs[i]);
            }
 
            return string.Join("", strs);
        }
 
        public static string ToUpperFirst(string str)
        {
            return Regex.Replace(str, @"^\w", t => t.Value.ToUpper());
        }
 
        private string GetJavaType(TabInfo ti)
        {
            switch (ti.type)
            {
                case "timestamptz":
                case "timestamp":
                    return "Timestamp";
                case "date":
                    return "LocalDate";
                case "time":
                    return "LocalTime";
                case "float4": // float
                    return "Float";
                case "float8": // double
                    return "Double";
                case "bool": // boolean
                    return "Boolean";
                case "numeric":
                    return "BigDecimal";
                case "int8": // long
                    return "Long";
                case "int2":
                case "int4": // int
                    return "Integer";
                default: // text, varchar
                    return "String";
            }
        }
 
        private bool HasGeom(List<TabInfo> tabs)
        {
            foreach (TabInfo ti in tabs)
            {
                if (ti.col == "geom") return true;
            }
 
            return false;
        }
 
        private static void OpenFolder(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath)) return;
 
            Process process = new Process();
            ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
            psi.Arguments = folderPath;
            process.StartInfo = psi;
 
            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                process.Close();
            }
        }
        #endregion
    }
}