hejianhao
2026-08-18 fb78f55a5b010d560a4673e4bf046133c07966c6
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
package com.tcm.training.admin.member.service;
 
import cn.idev.excel.FastExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tcm.training.admin.agent.entity.ProvincialAgent;
import com.tcm.training.admin.agent.excel.ClinicAgentImportRow;
import com.tcm.training.admin.agent.mapper.ProvincialAgentMapper;
import com.tcm.training.admin.common.DateTimes;
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.member.dto.ClinicBankAccountUpdateRequest;
import com.tcm.training.admin.member.excel.ClinicExcelRow;
import com.tcm.training.admin.member.mapper.ClinicQueryMapper;
import com.tcm.training.admin.member.row.ClinicBoundUserRow;
import com.tcm.training.admin.member.row.ClinicDetailRow;
import com.tcm.training.admin.member.row.ClinicListRow;
import com.tcm.training.admin.member.row.ClinicRegionOptionRow;
import com.tcm.training.admin.member.vo.ClinicBoundUserItemVO;
import com.tcm.training.admin.member.vo.ClinicDetailVO;
import com.tcm.training.admin.member.vo.ClinicListItemVO;
import com.tcm.training.admin.member.vo.ClinicRegionOptionVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
 
@Service
public class ClinicAppService {
 
    private final ClinicQueryMapper clinicQueryMapper;
    private final ClinicMapper clinicMapper;
    private final ProvincialAgentMapper provincialAgentMapper;
 
    public ClinicAppService(ClinicQueryMapper clinicQueryMapper, ClinicMapper clinicMapper, ProvincialAgentMapper provincialAgentMapper) {
        this.clinicQueryMapper = clinicQueryMapper;
        this.clinicMapper = clinicMapper;
        this.provincialAgentMapper = provincialAgentMapper;
    }
 
    public PageResponse<ClinicListItemVO> page(int page,
                                               int pageSize,
                                               String regionCode,
                                               String name,
                                               String phone,
                                               LocalDateTime createdFrom,
                                               LocalDateTime createdTo,
                                               Integer status) {
        IPage<ClinicListRow> result = clinicQueryMapper.selectClinicPage(
                new Page<ClinicListRow>(page, pageSize),
                trimToNull(regionCode),
                trimToNull(name),
                trimToNull(phone),
                createdFrom,
                createdTo,
                status
        );
        List<ClinicListItemVO> list = new ArrayList<ClinicListItemVO>();
        for (ClinicListRow row : result.getRecords()) {
            list.add(toListItem(row));
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    public void downloadClinicImportTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("诊所省区代理导入模板", "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
        FastExcel.write(response.getOutputStream(), ClinicAgentImportRow.class)
                .sheet("诊所省区代理导入模板")
                .doWrite(Collections.emptyList());
    }
 
    @Transactional
    public void importAgentBindings(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("请选择导入文件");
        }
        List<ClinicAgentImportRow> rows = FastExcel.read(file.getInputStream())
                .head(ClinicAgentImportRow.class).sheet().doReadSync();
        if (rows == null || rows.isEmpty()) {
            throw new IllegalArgumentException("导入文件不能为空");
        }
 
        Set<String> clinicNames = new LinkedHashSet<String>();
        Set<String> agentNames = new LinkedHashSet<String>();
        Map<String, String> bindingByClinicName = new HashMap<String, String>();
        int rowNumber = 1;
        for (ClinicAgentImportRow row : rows) {
            rowNumber++;
            if (row == null || (trimToNull(row.getClinicName()) == null && trimToNull(row.getAgentName()) == null))
                continue;
            String clinicName = trimToNull(row.getClinicName());
            String agentName = trimToNull(row.getAgentName());
            if (clinicName == null) {
                throw new IllegalArgumentException("第" + rowNumber + "行诊所不能为空");
            }
            if (agentName == null) {
                throw new IllegalArgumentException("第" + rowNumber + "行省区代理名称不能为空");
            }
            String previous = bindingByClinicName.put(clinicName, agentName);
            if (previous != null && !previous.equals(agentName)) {
                throw new IllegalArgumentException("诊所“" + clinicName + "”存在多个代理绑定");
            }
 
            clinicNames.add(clinicName);
            agentNames.add(agentName);
        }
        if (bindingByClinicName.isEmpty()) {
            throw new IllegalArgumentException("导入文件没有可用数据");
        }
 
        List<Clinic> clinics = clinicMapper.selectList(new LambdaQueryWrapper<Clinic>().in(Clinic::getName, clinicNames));
        List<ProvincialAgent> agents = provincialAgentMapper.selectList(new LambdaQueryWrapper<ProvincialAgent>()
                .eq(ProvincialAgent::getDeleted, 0).in(ProvincialAgent::getAgentName, agentNames));
        Map<String, ProvincialAgent> agentByName = new LinkedHashMap<String, ProvincialAgent>();
        for (ProvincialAgent agent : agents) {
            agentByName.put(agent.getAgentName(), agent);
        }
        for (String agentName : agentNames) {
            if (!agentByName.containsKey(agentName)) {
                throw new IllegalArgumentException("省区代理不存在:" + agentName);
            }
        }
 
 
        Set<String> foundClinicNames = new LinkedHashSet<String>();
        for (Clinic clinic : clinics) {
            foundClinicNames.add(clinic.getName());
            ProvincialAgent agent = agentByName.get(bindingByClinicName.get(clinic.getName()));
            clinic.setAgentId(agent.getId());
            clinicMapper.updateById(clinic);
        }
        for (String clinicName : clinicNames) {
            if (!foundClinicNames.contains(clinicName)) {
                throw new IllegalArgumentException("诊所不存在:" + clinicName);
            }
        }
    }
 
    public void export(String regionCode,
                       String name,
                       String phone,
                       LocalDateTime createdFrom,
                       LocalDateTime createdTo,
                       Integer status,
                       HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("诊所列表", "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
 
        List<ClinicListRow> rows = clinicQueryMapper.selectClinicList(
                trimToNull(regionCode),
                trimToNull(name),
                trimToNull(phone),
                createdFrom,
                createdTo,
                status
        );
        List<ClinicExcelRow> exports = new ArrayList<ClinicExcelRow>();
        for (int i = 0; i < rows.size(); i++) {
            ClinicListRow row = rows.get(i);
            ClinicExcelRow excel = new ClinicExcelRow();
            excel.setSerialNo(i + 1);
            excel.setName(defaultText(row.getName()));
            excel.setPhone(defaultText(PhoneMasker.mask(row.getPhone())));
            excel.setRegionName(defaultText(row.getRegionName()));
            excel.setUserCount(row.getUserCount() == null ? 0 : row.getUserCount());
            excel.setStatus(statusText(row.getStatus()));
            excel.setCreatedAt(DateTimes.format(row.getCreatedAt()));
            exports.add(excel);
        }
        FastExcel.write(response.getOutputStream(), ClinicExcelRow.class)
                .sheet("诊所列表")
                .doWrite(exports);
    }
 
    public List<ClinicRegionOptionVO> regionOptions() {
        List<ClinicRegionOptionRow> rows = clinicQueryMapper.selectRegionOptions();
        List<ClinicRegionOptionVO> list = new ArrayList<ClinicRegionOptionVO>();
        for (ClinicRegionOptionRow row : rows) {
            list.add(new ClinicRegionOptionVO(row.getRegionCode(), row.getRegionName()));
        }
        return list;
    }
 
    public ClinicDetailVO detail(Long id) {
        ClinicDetailRow row = clinicQueryMapper.selectClinicDetail(id);
        if (row == null) {
            throw new IllegalArgumentException("诊所不存在");
        }
        ClinicDetailVO vo = new ClinicDetailVO();
        vo.setId(row.getId());
        vo.setName(row.getName());
        vo.setPhone(defaultText(row.getContactPhone()));
        vo.setAddress(defaultText(row.getAddress()));
        vo.setBusinessLicenseUrl(trimToNull(row.getBusinessLicenseUrl()));
        vo.setUserCount(row.getUserCount() == null ? 0 : row.getUserCount());
        vo.setBankName(defaultText(row.getBankName()));
        vo.setAccountHolder(defaultText(row.getAccountHolder()));
        vo.setAccountNumber(defaultText(row.getAccountNumber()));
        vo.setBranchName(defaultText(row.getBranchName()));
        return vo;
    }
 
    public ClinicDetailVO updateBankAccount(Long id, ClinicBankAccountUpdateRequest request) {
        Clinic clinic = clinicMapper.selectById(id);
        if (clinic == null || (clinic.getDeleted() != null && clinic.getDeleted() == 1)) {
            throw new IllegalArgumentException("诊所不存在");
        }
        clinic.setBankName(trimToNull(request.getBankName()));
        clinic.setAccountHolder(trimToNull(request.getAccountHolder()));
        clinic.setAccountNumber(trimToNull(request.getAccountNumber()));
        clinic.setBranchName(trimToNull(request.getBranchName()));
        clinicMapper.updateById(clinic);
        return detail(id);
    }
 
    public PageResponse<ClinicBoundUserItemVO> clinicUsers(Long clinicId,
                                                           int page,
                                                           int pageSize,
                                                           String nickname,
                                                           String phone,
                                                           Integer status,
                                                           Integer isMember,
                                                           LocalDateTime registeredFrom,
                                                           LocalDateTime registeredTo) {
        requireClinic(clinicId);
        IPage<ClinicBoundUserRow> result = clinicQueryMapper.selectClinicUserPage(
                new Page<ClinicBoundUserRow>(page, pageSize),
                clinicId,
                trimToNull(nickname),
                trimToNull(phone),
                status,
                isMember,
                registeredFrom,
                registeredTo
        );
        List<ClinicBoundUserItemVO> list = new ArrayList<ClinicBoundUserItemVO>();
        for (ClinicBoundUserRow row : result.getRecords()) {
            ClinicBoundUserItemVO item = new ClinicBoundUserItemVO();
            item.setId(row.getId());
            item.setNickname(defaultText(row.getNickname()));
            item.setPhone(row.getPhone() == null ? "-" : PhoneMasker.mask(row.getPhone()));
            item.setAvatar(trimToNull(row.getAvatar()));
            item.setLivePoints(row.getLivePoints() == null ? 0 : row.getLivePoints());
            item.setIsMember(row.getIsMember() != null && row.getIsMember() == 1);
            item.setStatus(row.getStatus());
            item.setCreatedAt(row.getCreatedAt());
            list.add(item);
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    private String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
 
    private String defaultText(String value) {
        return value == null || value.trim().isEmpty() ? "-" : value;
    }
 
    private ClinicListItemVO toListItem(ClinicListRow row) {
        ClinicListItemVO item = new ClinicListItemVO();
        item.setId(row.getId());
        item.setName(defaultText(row.getName()));
        item.setPhone(row.getPhone() == null ? "-" : PhoneMasker.mask(row.getPhone()));
        item.setRegionName(defaultText(row.getRegionName()));
        item.setStatus(row.getStatus());
        item.setUserCount(row.getUserCount() == null ? 0 : row.getUserCount());
        item.setCreatedAt(row.getCreatedAt());
        item.setBusinessLicenseUrl(trimToNull(row.getBusinessLicenseUrl()));
        return item;
    }
 
    private void requireClinic(Long clinicId) {
        if (clinicQueryMapper.selectClinicDetail(clinicId) == null) {
            throw new IllegalArgumentException("诊所不存在");
        }
    }
 
    private String statusText(Integer status) {
        if (status != null && status == 1) {
            return "启用";
        }
        if (status != null && status == 2) {
            return "注销";
        }
        return "禁用";
    }
}