hejianhao
2026-09-01 f4e8dfd7f8f11966f4b5dc8c6661cbc3feccc4cf
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
package com.tcm.training.admin.agent.service;
 
import cn.hutool.json.JSONUtil;
import cn.idev.excel.FastExcel;
import com.fasterxml.jackson.databind.JsonNode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tcm.training.admin.agent.dto.ProvincialAgentSaveRequest;
import com.tcm.training.admin.agent.entity.AgentRegion;
import com.tcm.training.admin.agent.entity.ProvincialAgent;
import com.tcm.training.admin.agent.mapper.AgentRegionMapper;
import com.tcm.training.admin.agent.mapper.ProvincialAgentMapper;
import com.tcm.training.admin.agent.vo.ProvincialAgentDetailVO;
import com.tcm.training.admin.agent.vo.ProvincialAgentListItemVO;
import com.tcm.training.admin.app.register.entity.SysRegion;
import com.tcm.training.admin.app.register.mapper.SysRegionMapper;
import com.tcm.training.admin.common.PageResponse;
import com.tcm.training.admin.common.PhoneMasker;
import com.tcm.training.admin.live.entity.Clinic;
import com.tcm.training.admin.live.mapper.ClinicMapper;
import com.tcm.training.admin.utils.VzanHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tcm.training.admin.common.enums.EnabledStatusEnum;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
@Slf4j
@Service
public class ProvincialAgentAppService {
    private final ProvincialAgentMapper agentMapper;
    private final AgentRegionMapper regionMapper;
    private final SysRegionMapper sysRegionMapper;
    private final ClinicMapper clinicMapper;
    private final VzanHttpUtil vzanHttpUtil;
 
    public ProvincialAgentAppService(ProvincialAgentMapper agentMapper, AgentRegionMapper regionMapper,
                                     SysRegionMapper sysRegionMapper, ClinicMapper clinicMapper, VzanHttpUtil vzanHttpUtil) {
        this.agentMapper = agentMapper;
        this.regionMapper = regionMapper;
        this.sysRegionMapper = sysRegionMapper;
        this.clinicMapper = clinicMapper;
        this.vzanHttpUtil = vzanHttpUtil;
    }
 
    public PageResponse<ProvincialAgentListItemVO> page(int page, int pageSize, String regionCode,
                                                        String clinicName, String contactInfo, Integer status) {
        LambdaQueryWrapper<ProvincialAgent> query = new LambdaQueryWrapper<ProvincialAgent>()
                .eq(ProvincialAgent::getDeleted, 0)
                .like(trim(contactInfo) != null, ProvincialAgent::getContactInfo, trim(contactInfo))
                .eq(status != null, ProvincialAgent::getStatus, status)
                .orderByAsc(ProvincialAgent::getCreatedAt).orderByAsc(ProvincialAgent::getId);
        if (trim(regionCode) != null) {
            List<Long> ids = new ArrayList<Long>();
            for (AgentRegion region : regionMapper.selectList(new LambdaQueryWrapper<AgentRegion>()
                    .eq(AgentRegion::getRegionCode, trim(regionCode))))
                ids.add(region.getAgentId());
            if (ids.isEmpty()) {
                return emptyPage(page, pageSize);
            }
            query.in(ProvincialAgent::getId, ids);
        }
        if (trim(clinicName) != null) {
            List<Long> ids = new ArrayList<Long>();
            for (Clinic clinic : clinicMapper.selectList(new LambdaQueryWrapper<Clinic>()
                    .like(Clinic::getName, trim(clinicName)))) {
                if (clinic.getAgentId() != null && !ids.contains(clinic.getAgentId())) ids.add(clinic.getAgentId());
            }
            if (ids.isEmpty()) {
                return emptyPage(page, pageSize);
            }
            query.in(ProvincialAgent::getId, ids);
        }
        IPage<ProvincialAgent> result = agentMapper.selectPage(new Page<ProvincialAgent>(page, pageSize), query);
        List<ProvincialAgentListItemVO> list = new ArrayList<ProvincialAgentListItemVO>();
        for (ProvincialAgent item : result.getRecords()) {
            list.add(toList(item));
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    private PageResponse<ProvincialAgentListItemVO> emptyPage(int page, int pageSize) {
        return PageResponse.of(new ArrayList<ProvincialAgentListItemVO>(), 0, page, pageSize);
    }
 
    public ProvincialAgentDetailVO detail(Long id) {
        return toDetail(require(id));
    }
 
    @Transactional(rollbackFor = Exception.class)
    public ProvincialAgentDetailVO create(ProvincialAgentSaveRequest request) {
        boolean firstAgent = agentMapper.selectCount(new LambdaQueryWrapper<ProvincialAgent>()
                .eq(ProvincialAgent::getDeleted, 0)) == 0;
        ProvincialAgent agent = new ProvincialAgent();
        fill(agent, request);
        agent.setDeleted(0);
        agentMapper.insert(agent);
        saveRegions(agent, request);
        if (firstAgent) {
            clinicMapper.update(null, new LambdaUpdateWrapper<Clinic>().set(Clinic::getAgentId, agent.getId()));
        }
        log.info("调用微赞创建代理,入参 agentMobile={}, agentName={}, levelCode={}, parentMobile={}, storeName={}",
                request.getContactInfo(), request.getAgentName(), 2, null, null);
        try {
            JsonNode vzanResponse = vzanHttpUtil.createAgent(
                    request.getContactInfo(), request.getAgentName(), 2, null, null);
            log.info("微赞创建代理成功,出参={}", vzanResponse);
        } catch (RuntimeException ex) {
            log.error("微赞创建代理失败,本地事务将回滚,入参 agentMobile={}, agentName={}, levelCode={}, parentMobile={}, storeName={}",
                    request.getContactInfo(), request.getAgentName(), 1, null, request.getAgentName(), ex);
//            throw ex;
            throw new IllegalStateException("微赞创建代理失败", ex);
        }
        return detail(agent.getId());
    }
 
    @Transactional(rollbackFor = Exception.class)
    public ProvincialAgentDetailVO update(Long id, ProvincialAgentSaveRequest request) {
        ProvincialAgent agent = require(id);
        fill(agent, request);
        agentMapper.updateById(agent);
        regionMapper.delete(new LambdaQueryWrapper<AgentRegion>().eq(AgentRegion::getAgentId, id));
        saveRegions(agent, request);
        return detail(id);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        require(id);
        agentMapper.deleteById(id);
    }
 
    private void fill(ProvincialAgent agent, ProvincialAgentSaveRequest request) {
        agent.setAgentName(trim(request.getAgentName()));
        agent.setProvince("");
        agent.setBankName(trim(request.getBankName()));
        agent.setAccountNumber(trim(request.getAccountNumber()));
        agent.setAccountHolder(trim(request.getAccountHolder()));
        agent.setBranchName(trim(request.getBranchName()));
        agent.setContactInfo(trim(request.getContactInfo()));
        agent.setStatus(request.getStatus() == null ? EnabledStatusEnum.ENABLED.getValue() : request.getStatus());
        agent.setAddress(trim(request.getAddress()));
    }
 
    private void saveRegions(ProvincialAgent agent, ProvincialAgentSaveRequest request) {
        if (request.getRegions() == null) return;
        for (ProvincialAgentSaveRequest.RegionItem item : request.getRegions()) {
            if (item == null || trim(item.getRegionCode()) == null) continue;
            RegionInfo info = resolveRegion(item.getRegionCode());
            AgentRegion region = new AgentRegion();
            region.setAgentId(agent.getId());
            region.setRegionCode(trim(item.getRegionCode()));
            region.setRegionName(info.name);
            region.setRegionLevel(info.path.size());
            regionMapper.insert(region);
        }
    }
 
    private ProvincialAgent require(Long id) {
        ProvincialAgent agent = agentMapper.selectOne(new LambdaQueryWrapper<ProvincialAgent>()
                .eq(ProvincialAgent::getId, id).eq(ProvincialAgent::getDeleted, 0).last("limit 1"));
        if (agent == null) throw new IllegalArgumentException("省代理不存在");
        return agent;
    }
 
    private ProvincialAgentListItemVO toList(ProvincialAgent agent) {
        ProvincialAgentListItemVO vo = new ProvincialAgentListItemVO();
        vo.setId(agent.getId());
        vo.setAgentName(agent.getAgentName());
        vo.setContactInfo(PhoneMasker.mask(agent.getContactInfo()));
        vo.setAddress(agent.getAddress());
        vo.setCreatedAt(agent.getCreatedAt());
        vo.setStatus(agent.getStatus());
        vo.setClinicCount(clinicMapper.selectCount(new LambdaQueryWrapper<Clinic>().eq(Clinic::getAgentId, agent.getId())));
        List<AgentRegion> regions = regions(agent.getId());
        vo.setRegionCount(regions.size());
        List<String> names = new ArrayList<String>();
        for (AgentRegion region : regions) {
            names.add(resolveRegion(region.getRegionCode()).name);
        }
        vo.setRegionNames(names);
        return vo;
    }
 
    private ProvincialAgentDetailVO toDetail(ProvincialAgent agent) {
        ProvincialAgentDetailVO vo = new ProvincialAgentDetailVO();
        ProvincialAgentListItemVO base = toList(agent);
        vo.setId(base.getId());
        vo.setAgentName(base.getAgentName());
        vo.setContactInfo(base.getContactInfo());
        vo.setAddress(base.getAddress());
        vo.setRegionCount(base.getRegionCount());
        vo.setRegionNames(base.getRegionNames());
        vo.setCreatedAt(base.getCreatedAt());
        vo.setStatus(base.getStatus());
        vo.setClinicCount(base.getClinicCount());
        vo.setBankName(agent.getBankName());
        vo.setAccountNumber(agent.getAccountNumber());
        vo.setAccountHolder(agent.getAccountHolder());
        vo.setBranchName(agent.getBranchName());
        vo.setUpdatedAt(agent.getUpdatedAt());
        List<ProvincialAgentDetailVO.RegionVO> values = new ArrayList<ProvincialAgentDetailVO.RegionVO>();
        for (AgentRegion region : regions(agent.getId())) {
            RegionInfo info = resolveRegion(region.getRegionCode());
            ProvincialAgentDetailVO.RegionVO value = new ProvincialAgentDetailVO.RegionVO();
            value.setRegionCode(region.getRegionCode());
            value.setRegionName(info.name);
            value.setRegionLevel(info.path.size());
            value.setRegionPath(info.path);
            values.add(value);
        }
        vo.setRegions(values);
        return vo;
    }
 
    private List<AgentRegion> regions(Long id) {
        return regionMapper.selectList(new LambdaQueryWrapper<AgentRegion>()
                .eq(AgentRegion::getAgentId, id).orderByAsc(AgentRegion::getId));
    }
 
    private RegionInfo resolveRegion(String code) {
        List<String> path = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        SysRegion current = sysRegionMapper.selectByCode(code);
        while (current != null) {
            path.add(0, current.getCode());
            names.add(0, current.getName());
            current = current.getParentId() == null || current.getParentId() == 0 ? null : sysRegionMapper.selectById(current.getParentId());
        }
        if (path.isEmpty()) {
            path.add(code);
            names.add(code);
        }
        return new RegionInfo(path, String.join("", names));
    }
 
    private String trim(String value) {
        if (value == null) return null;
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
 
    private static class RegionInfo {
        private final List<String> path;
        private final String name;
 
        private RegionInfo(List<String> path, String name) {
            this.path = path;
            this.name = name;
        }
    }
}