Blame view

sys/Hh.Mes.Service/WebService/Base/SysFileService.cs 10.3 KB
赖素文 authored
1
2
3
4
5
6
7
8
9
10
11
12
using Hh.Mes.Common.Infrastructure;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Data;
using System.IO;
赖素文 authored
13
using Hh.Mes.Pojo.System;
14
15
using System.Text;
using Org.BouncyCastle.Crypto;
16
using System.Collections.Generic;
赖素文 authored
17
18
19
20
21
22

namespace Hh.Mes.Service.Base
{
    public class SysFileService : RepositorySqlSugar<sys_File>
    {
        /// <summary>
23
        /// 文件存储路径  new JoinQueryInfos(JoinType.Left, file.targetId == vw.code)
赖素文 authored
24
25
26
        /// </summary>
        private readonly string FileNamePath = "\\wwwroot\\Document";
27
        #region 列表、树结构数据
赖素文 authored
28
29
30
31
32
33
34
        public dynamic Load(PageReq pageReq, sys_File entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var expression = LinqWhere(entity);
                //先组合查询表达式
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
                var query = Context.Queryable<sys_File, VW_CurrentUserDevice>((x,vw) =>  new JoinQueryInfos(JoinType.Left, x.targetId == vw.equipmentCode)  )
                                   .Where(expression)
                                   .Select((x, vw) => new
                                   {
                                       x.fileName,
                                       x.id,
                                       x.targetId,
                                       x.host,

                                       x.url,
                                       x.size,
                                       x.suffix,
                                       x.remark,

                                       x.createBy,
                                       x.createTime
                                   });
53
赖素文 authored
54
55
56
57
                //Exelture就不分页,因为导出的话是全部导出
                if (pageReq != null)
                {
                    int total = 0;
58
                    var list = query .ToOffsetPage(pageReq.page, pageReq.limit, ref total);
59
                    result.Result = list;
赖素文 authored
60
61
62
63
64
                    result.Count = total;
                }
                else
                {
                    result.Result = query.ToList();
65
                    result.Count = result.Result.Count;
赖素文 authored
66
67
68
69
70
                }
                return result;
            }, catchRetrunValue: "list");
        }
71
        public Expression<Func<sys_File, VW_CurrentUserDevice, bool>> LinqWhere(sys_File model)
赖素文 authored
72
73
74
        {
            try
            {
75
                var exp = Expressionable.Create<sys_File, VW_CurrentUserDevice>();
赖素文 authored
76
                //数据过滤条件
77
78
                //根节点
                if (!string.IsNullOrWhiteSpace(model.targetTableName) && model.targetTableName != "root")
赖素文 authored
79
                {
80
                    exp.And((x, vw) => x.targetTableName.Contains(model.targetTableName));
赖素文 authored
81
82
83
                }
                if (!string.IsNullOrWhiteSpace(model.fileCode))
                {
84
                    exp.And((x, vw) => x.fileCode.Contains(model.fileCode));
赖素文 authored
85
86
87
                }
                if (!string.IsNullOrWhiteSpace(model.host))
                {
88
                    exp.And((x, vw) => x.host.Contains(model.host));
赖素文 authored
89
                }
90
                //根节点
91
                if (!string.IsNullOrEmpty(model.targetId) && model.targetId != "r-1")
赖素文 authored
92
                {
93
                    exp.And((x, vw) => x.targetId.Equals(model.targetId));
赖素文 authored
94
95
96
                }
                if (!string.IsNullOrWhiteSpace(model.fileName))
                {
97
                    exp.And((x, vw) => x.fileName.Contains(model.fileName));
赖素文 authored
98
                }
99
100
                //读取当前用户下面所有的设备
                string currentUser = sysWebUser.Account;
101
                if (currentUser != SystemVariable.DefaultCreated) exp.And((x, vw) => vw.userAccount == currentUser);
赖素文 authored
102
103
104
105
106
107
108
109
110
                return exp.ToExpression();//拼接表达式
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        /// <summary>
111
        /// /左侧列表 设备类型+设备
赖素文 authored
112
113
114
115
116
        /// </summary>
        public DataTable GetTreeList()
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
117
                var stringBuilder = new StringBuilder();
赖素文 authored
118
                string equipmentTypeCodes = string.Join("', '", SystemVariable.IotNotContainDevice);
119
                string user = sysWebUser.Account;
120
121
                string userWhere = "";
                if (user != SystemVariable.DefaultCreated) userWhere = $" and t1.userAccount='{user}'";
122
                stringBuilder.AppendLine($@" select id = newid(),
123
124
125
126
                                                    name = '根节点',
                                                    keys = 'r-1',
                                                    parentId =  '0',
                                                    isok = '',
127
128
                                                    code = 'root',
		                                            projectKeys=null
129
130
                                            union all
                                            select id = newid(),
131
132
133
134
135
136
                                                   name = Name, 
                                                   keys = e.code,
                                                   parentId = 'r-1',
                                                   isok = 'true',
                                                   code='eqType',
		                                           projectKeys=null
137
                                            from base_equipment_type e
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
                                            where e.code not in ('{equipmentTypeCodes}')
                                            union all
                                            select id = newid(),
                                                    name = e.equipmentName +' '+e.otherCode,
                                                    keys=e.otherCode,
                                                    parentId =( select base_equipment_type.code  from base_equipment_type  where code=e.equipmentTypeCode  ),
                                                    isok = 'true',
                                                    code='eq',
								                    e.projectKeys
                                            from (			   
					   					        select   t2.projectKeys ,t2.equipmentName ,t2.otherCode   ,t2.equipmentTypeCode 
												from sys_user_project_rel t1
								                left join base_equipment t2 on t1.clientKeys=t2.projectKeys
												where   t2.equipmentTypeCode not in ('{equipmentTypeCodes}')  {userWhere}
											)e");
153
154

                var dt = base.Context.Ado.GetDataTableAsync(stringBuilder.ToString()).Result;
赖素文 authored
155
156
157
                return dt == null || dt.Rows.Count == 0 ? null : dt;
            });
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
        } 
        #endregion


        public dynamic DelByIds(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var docs = Context.Queryable<sys_File>().Where(x => ids.Contains(x.id)).ToList();
                docs.ForEach((item) =>
                {
                    DeleteDocument(item.url);
                });
                Context.Deleteable<sys_File>(t => ids.Contains(t.id)).ExecuteCommand();
                return response;
            });
        }

        /// <summary>
        /// 删除服务器内文件
        /// </summary>
        /// <param name="fileName"></param>
        private void DeleteDocument(string fileName)
        {
            string path = $"{Directory.GetCurrentDirectory()}{FileNamePath}\\{fileName}";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        public dynamic AddOrUpdate(sys_File entity)
        {
            return ExceptionsHelp.Instance.ExecuteT<dynamic>(() =>
            {
                var response = new Response();
                string fileEmptyErrorMessage = "上传文件数据时,文件不能为空!";

                if (entity.excelfile == null || entity.excelfile.Count == 0)
                {
                    return response.ResponseError(fileEmptyErrorMessage);
                }

                if (string.IsNullOrEmpty(entity.targetId))
                {
                    return response.ResponseError("适用的设备Code不能为空!");
                }

                foreach (var file in entity.excelfile)
                {
                    if (file == null || file.Length == 0)
                    {
                        return response.ResponseError(fileEmptyErrorMessage);
                    }

                    switch (entity.targetTableName)
                    {
                        case "eqType":
                            entity.targetTableName = "base_equipment_type";
                            break;
                        case "eq":
                            entity.targetTableName = "base_equipment";
                            break;
                    }

                    var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Document");
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }

                    var suffix = Path.GetExtension(file.FileName);
                    var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                    var newFileName = $"{fileName}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}{suffix}";

                    long size;
                    using (var fs = File.Create(Path.Combine(uploadPath, newFileName)))
                    {
                        file.CopyTo(fs);
                        size = fs.Length / 1024;
                    }

                    entity.size = size > 1024 ? $"{size / 1024:N1}M" : $"{size:N1}Kb";
                    entity.suffix = suffix;
                    entity.fileName = fileName;
                    entity.url = newFileName;
                    entity.createBy = sysWebUser.Account;
                    entity.createTime = DateTime.Now;

                    Context.Insertable(entity).ExecuteCommand();
                }
                return response;
            });
赖素文 authored
252
253
254
        }
    }
}