cdk
2025-11-27 53c7de340f55ab0c917a03d54d883b4a8082f42d
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
 
using Kingdee.CDP.WebApi.SDK;
using MES.Service.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NewPdaSqlServer.DB;
using NewPdaSqlServer.Dto;
using NewPdaSqlServer.entity;
using NewPdaSqlServer.util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Text;
 
namespace MES.Service.service.Warehouse;
 
 
public class MesSuppScManager : Repository<MesSuppSc>
{
    private const string SourceUrl = "https://qixizhaopin.modaniot.com:8443/wetchat/ToGSMesServlet?password=gsmes";
 
    /// <summary>
    /// 从指定网址读取 JSON 数据并保存到 MES_SUPPSCORE 表
    /// </summary>
    public bool FetchAndSaveFromUrl()
    {
        string json;
        try
        {
            using var http = new HttpClient();
            // 可根据需要设置超时
            http.Timeout = TimeSpan.FromSeconds(30);
            json = http.GetStringAsync(SourceUrl).Result;
        }
        catch (Exception ex)
        {
            throw new Exception($"获取远程数据失败: {ex.Message}", ex);
        }
 
        if (string.IsNullOrWhiteSpace(json))
            throw new Exception("远程返回内容为空");
 
        JToken root;
        try
        {
            root = JToken.Parse(json);
        }
        catch (Exception ex)
        {
            throw new Exception($"解析 JSON 失败: {ex.Message}");
        }
 
        var data = root["data"] as JArray;
        if (data == null || data.Count == 0)
            throw new Exception("JSON 中未包含 data 或 data 为空");
 
        var list = new List<MesSuppSc>();
        foreach (var item in data)
        {
            var rq = item["rq"]?.ToString();
            var gysmc = item["gysmc"]?.ToString();
            var zf = item["zf"]?.ToString();
 
            decimal? zfDec = null;
            if (!string.IsNullOrWhiteSpace(zf) && decimal.TryParse(zf, out var tmp))
                zfDec = tmp;
 
            list.Add(new MesSuppSc
            {
                ID = Guid.NewGuid(),
                SuppDate = rq,
                SuppName = gysmc,
                SuppNum = zfDec
            });
        }
 
        // 写入数据库:先清空表再插入(按原逻辑)
        var result = UseTransaction(db =>
        {
            // 注意:这里使用传入的 db(SqlSugarScope)执行原子操作
            db.Deleteable<MesSuppSc>().ExecuteCommand();
            var inserted = db.Insertable(list).ExecuteCommand();
            return inserted > 0 ? 1 : 0;
        }) > 0;
 
        return result;
    }
}