chengf
2026-01-29 b012b819cb8b2ce883aa68d0c179a156b000598e
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
package org.jeecg.modules.demo.contract.controller;
 
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;
 
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
 
import jakarta.websocket.server.PathParam;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.jeecg.common.aspect.DictAspect;
import org.jeecg.modules.demo.customer.entity.Customer;
import org.jeecg.modules.demo.customer.service.ICustomerService;
import org.jeecg.modules.system.controller.SysUserController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.contract.entity.ContractFile;
import org.jeecg.modules.demo.contract.entity.SemanticWord;
import org.jeecg.modules.demo.contract.entity.Contract;
import org.jeecg.modules.demo.contract.vo.ContractPage;
import org.jeecg.modules.demo.contract.service.IContractService;
import org.jeecg.modules.demo.contract.service.IContractFileService;
import org.jeecg.modules.demo.contract.service.ISemanticWordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
 
 
 /**
 * @Description: 合同
 * @Author: jeecg-boot
 * @Date:   2025-10-11
 * @Version: V1.0
 */
@Tag(name="合同")
@RestController
@RequestMapping("/contract/contract")
@Slf4j
public class ContractController {
    @Autowired
    private IContractService contractService;
    @Autowired
    private IContractFileService contractFileService;
    @Autowired
    private ISemanticWordService semanticWordService;
     @Autowired
     private ICustomerService customerService;
 
     @Autowired
     private ISysUserService sysUserService;
    /**
     * 分页列表查询
     *
     * @param contract
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "合同-分页列表查询")
    @Operation(summary="合同-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Contract>> queryPageList(Contract contract,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                 @RequestParam(name="role", defaultValue="无") String role,
                                                 @RequestParam(name="user", defaultValue="无") String user,
                                   HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        if (contract.getCreateBy() != null) {
            user = contract.getCreateBy();
        }
        // 自定义多选的查询规则为:LIKE_WITH_OR
        customeRuleMap.put("reviewStatus", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<Contract> queryWrapper = QueryGenerator.initQueryWrapper(contract, req.getParameterMap(),customeRuleMap,true);
        if (contract.getAgentAuditorIsNull() != null) {
            if (contract.getAgentAuditorIsNull().equals("false")) {
                queryWrapper.isNotNull("agents_name");
            } else{
                queryWrapper.and(wrapper -> wrapper.isNull("agents_name").or().eq("agents_name", ""));
 
            }
        }
        if (user.equals("无"));
        else if (role.equals("1972228581703651330")){//销售
//        else{
//            if (user.equals("无")){
//                return Result.error("请输入销售名称");//销售根据用户筛选
//            }
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.eq("agent_sales", user);
            Result<IPage<SysUser>> iPageResult = sysUserService.queryPageList(req, sysUserQueryWrapper, pageSize, pageNo);
            List<String> name = new ArrayList<>();
            for (SysUser sysUser : iPageResult.getResult().getRecords()){
                name.add(sysUser.getUsername());
            }
            name.add(user);
            queryWrapper.nested(wrapper -> {
                // 内层第一个条件:(create_by IN (name) AND review_status != 2)
                wrapper.nested(w1 -> w1.in("create_by", name).ne("review_status", 2));
                // 内层 OR 条件:(create_by = 最后一个name AND review_status = 2)
                wrapper.or(w2 -> w2.eq("create_by", name.get(name.size()-1)).eq("review_status", 2));
            });
        }
        if (role.equals("1972228688033452034")){//财务
            queryWrapper.ne("review_status", "8");
        }
        Page<Contract> page = new Page<Contract>(pageNo, pageSize);
        queryWrapper.orderBy(
                true,  // condition:是否启用该排序(true=启用)
                false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                "CASE WHEN review_status = 1 THEN 1 ELSE 0 END" // R column:虚拟排序列(直接传 SQL 片段)
        );
 
        queryWrapper.orderBy(
                true,  // condition:是否启用该排序(true=启用)
                false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                "CASE WHEN review_status = 2 THEN 1 ELSE 0 END" // R column:虚拟排序列(直接传 SQL 片段)
        );
 
        queryWrapper.orderBy(
                true,  // condition:是否启用该排序(true=启用)
                true, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                "emergency_status" // R column:虚拟排序列(直接传 SQL 片段)
        );
 
        queryWrapper.orderBy(
                true,  // condition:是否启用该排序(true=启用)
                false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                "create_time" // R column:虚拟排序列(直接传 SQL 片段)
        );
 
        IPage<Contract> pageList = contractService.page(page, queryWrapper);
        List<SemanticWord> semanticWordList = null;
        for (Contract contract1 : pageList.getRecords()){
            semanticWordList = semanticWordService.selectByMainId(contract1.getId());
            for (SemanticWord semanticWord : semanticWordList){
                if (semanticWord.getPrice() != null){
                    contract1.setCountSum(contract1.getCountSum() + semanticWord.getPrice());
                }
                contract1.setSemanticWordList(contract1.getSemanticWordList() == null ? semanticWord.getWord() : contract1.getSemanticWordList() + ", " + semanticWord.getWord());
            }
            QueryWrapper<Customer> qw = new QueryWrapper<>();
            qw.eq("enterprise_name",contract1.getCustomerName());
            contract1.setCustomer(customerService.getOne(qw));
        }
        return Result.OK(pageList);
    }
 
 
     @Operation(summary="合同-查询该角色合同个数")
     @GetMapping(value = "/count")
     public Result<IPage<Contract>> queryPageList(Contract contract,
                                                  @RequestParam(name="role", defaultValue="无") String role,
                                                  @RequestParam(name="user", defaultValue="无") String user,
                                                  HttpServletRequest req) {
         // 自定义查询规则
         Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
         if (contract.getCreateBy() != null) {
             user = contract.getCreateBy();
         }
         // 自定义多选的查询规则为:LIKE_WITH_OR
         customeRuleMap.put("reviewStatus", QueryRuleEnum.LIKE_WITH_OR);
         QueryWrapper<Contract> queryWrapper = QueryGenerator.initQueryWrapper(contract, req.getParameterMap(),customeRuleMap,true);
         if (contract.getAgentAuditorIsNull() != null) {
             if (contract.getAgentAuditorIsNull().equals("false")) {
                 queryWrapper.isNotNull("agents_name");
             } else{
                 queryWrapper.and(wrapper -> wrapper.isNull("agents_name").or().eq("agents_name", ""));
 
             }
         }
         if (!user.equals("无")){
             QueryWrapper qw = new QueryWrapper<SysUser>();
             qw.eq("id", user);
             String userName = ((SysUser)((Page) sysUserService.queryPageList(req, qw, 1, 1).getResult()).getRecords().get(0)).getUsername();
             queryWrapper.eq("create_by", userName);
         }
         if (role.equals("无"));
         else if (role.equals("1972228581703651330")){//销售
//        else{
//            if (user.equals("无")){
//                return Result.error("请输入销售名称");//销售根据用户筛选
//            }
             QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
             sysUserQueryWrapper.eq("agent_sales", user);
             Result<IPage<SysUser>> iPageResult = sysUserService.queryPageList(req, sysUserQueryWrapper, 100, 1);
             List<String> name = new ArrayList<>();
             for (SysUser sysUser : iPageResult.getResult().getRecords()){
                 name.add(sysUser.getUsername());
             }
             name.add(user);
             queryWrapper.nested(wrapper -> {
                 // 内层第一个条件:(create_by IN (name) AND review_status != 2)
                 wrapper.nested(w1 -> w1.in("create_by", name).ne("review_status", 2));
                 // 内层 OR 条件:(create_by = 最后一个name AND review_status = 2)
                 wrapper.or(w2 -> w2.eq("create_by", name.get(name.size()-1)).eq("review_status", 2));
             });
         }
         queryWrapper.orderBy(
                 true,  // condition:是否启用该排序(true=启用)
                 false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                 "CASE WHEN review_status = 1 THEN 1 ELSE 0 END" // R column:虚拟排序列(直接传 SQL 片段)
         );
 
         queryWrapper.orderBy(
                 true,  // condition:是否启用该排序(true=启用)
                 false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                 "CASE WHEN review_status = 2 THEN 1 ELSE 0 END" // R column:虚拟排序列(直接传 SQL 片段)
         );
 
         queryWrapper.orderBy(
                 true,  // condition:是否启用该排序(true=启用)
                 true, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                 "emergency_status" // R column:虚拟排序列(直接传 SQL 片段)
         );
 
         queryWrapper.orderBy(
                 true,  // condition:是否启用该排序(true=启用)
                 false, // isAsc:是否升序(false=降序,让 1 在前、0 在后)
                 "create_time" // R column:虚拟排序列(直接传 SQL 片段)
         );
 
         long count = contractService.count(queryWrapper);
         return Result.OK(count+"");
     }
 
     /**
     *   添加
     *
     * @param contractPage
     * @return
     */
    @AutoLog(value = "合同-添加")
    @Operation(summary="合同-添加")
    @RequiresPermissions("contract:contract:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ContractPage contractPage) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractPage, contract);
        contract.setContractCode(getFirstLetter(contract.getContractName()));
        contractService.saveMain(contract, contractPage.getContractFileList(),contractPage.getSemanticWordList());
        addContract(contract,contractPage.getSemanticWordList());
 
 
 
        return Result.OK("添加成功!");
    }
 
     public static String getFirstLetter(String chinese) {
         if (chinese == null || chinese.isEmpty()) {
             return "";
         }
 
         HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
         format.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 大写
         format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 忽略声调
 
         StringBuilder firstLetters = new StringBuilder();
         char[] chars = chinese.toCharArray();
 
         for (char c : chars) {
             // 如果是中文,提取首字母
             if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                 try {
                     String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                     if (pinyinArray != null && pinyinArray.length > 0) {
                         firstLetters.append(pinyinArray[0].charAt(0)); // 取第一个拼音的首字母
                     }
                 } catch (BadHanyuPinyinOutputFormatCombination e) {
                     e.printStackTrace();
                 }
             } else {
                 // 非中文不处理(或根据需求保留/过滤)
                 // firstLetters.append(c); // 如需保留非中文字符,解开此注释
             }
         }
 
         return firstLetters.toString();
     }
 
    /**
     *  编辑
     *
     * @param contractPage
     * @return
     */
    @AutoLog(value = "合同-编辑")
    @Operation(summary="合同-编辑")
    @RequiresPermissions("contract:contract:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody ContractPage contractPage) {
        Contract contract = new Contract();
        if (contract.getCustomer() == null ||contract.getCustomer().getEnterpriseName() == null || !contract.getCustomer().getEnterpriseName().equals("")) {
            BeanUtils.copyProperties(contractPage, contract);
            Contract contractEntity = contractService.getById(contract.getId());
            if (contractEntity.getReviewStatus() != null && contract.getReviewStatus() != null && !contractEntity.getReviewStatus().equals(contract.getReviewStatus())) {
                contractEntity.setChangerTime(new Date());
                contract.setChangerTime(new Date());
            }
            if(contractEntity==null) {
                return Result.error("未找到对应数据");
            }
            contractService.updateMain(contract, contractPage.getContractFileList(),contractPage.getSemanticWordList());
            return Result.OK("编辑成功!");
        }
        BeanUtils.copyProperties(contractPage, contract);
        Contract contractEntity = contractService.getById(contract.getId());
 
        if (contractEntity.getReviewStatus() != null && contract.getReviewStatus() != null && !contractEntity.getReviewStatus().equals(contract.getReviewStatus())) {
            contractEntity.setChangerTime(new Date());
            contract.setChangerTime(new Date());
        }
 
        contractEntity.setCustomer(contract.getCustomer());
        contract.setCustomerName(contract.getCustomer().getEnterpriseName());
        contractEntity.setCustomerName(contract.getCustomer().getEnterpriseName());
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq("enterprise_name",contract.getCustomer().getEnterpriseName());
        if (customerService.count(qw) > 0 && !contractPage.getCustomerName().equals(contract.getCustomerName())) {
            return Result.error("重复的公司名称");
        }
        if(contractEntity==null) {
            return Result.error("未找到对应数据");
        }
        contractService.updateMain(contract, contractPage.getContractFileList(),contractPage.getSemanticWordList());
        customerService.updateById(contractEntity.getCustomer());
 
        if (contractPage.getStatus() != null) {
            UpdateWrapper<SemanticWord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status", contractPage.getStatus()); // 替换为实际要修改的字段名(如semantic_id)
            updateWrapper.eq("contract_id", contract.getId()); // 复用查询条件
            boolean update = semanticWordService.update(updateWrapper);
        }
        return Result.OK("编辑成功!");
    }
 
     @AutoLog(value = "停止服务合同")
     @Operation(summary="停止服务合同")
     @RequiresPermissions("contract:contract:dropService")
     @RequestMapping(value = "/dropService", method = {RequestMethod.PUT,RequestMethod.POST})
     public Result<String> dropService(@RequestBody ContractPage contractPage) {
         Contract contract = new Contract();
         contract.setId(contractPage.getId());
         contract.setIsDropService(contractPage.getIsDropService().isEmpty() ? "是" : contractPage.getIsDropService());
         boolean b = contractService.updateById(contract);
         if (b) {
             return Result.OK("更新完成");
         } else {
             return Result.error("更新失败");
         }
     }
    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同-通过id删除")
    @Operation(summary="合同-通过id删除")
    @RequiresPermissions("contract:contract:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        QueryWrapper<Contract> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("id",id);
 
        List<Contract> list = contractService.list(objectQueryWrapper);
        String customerName = list.get(0).getCustomerName();
        contractService.delMain(id);
 
        objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("customer_name",customerName);
 
        if (contractService.count(objectQueryWrapper) == 0) {
            QueryWrapper<Customer> customerQueryWrapper = new QueryWrapper<>();
            customerQueryWrapper.eq("enterprise_name",customerName);
            Customer one = customerService.getOne(customerQueryWrapper);
            customerService.removeById(one);
 
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("username", customerName);
            qw.eq("realname", customerName);
 
            sysUserService.remove(qw);
        }
        return Result.OK("删除成功!");
    }
    
    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同-批量删除")
    @Operation(summary="合同-批量删除")
    @RequiresPermissions("contract:contract:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.contractService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }
 
    @Autowired
    DictAspect dictAspect;
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同-通过id查询")
    @Operation(summary="合同-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Contract> queryById(@RequestParam(name="id",required=true) String id) {
        Page<Contract> page = new Page<Contract>(1, 1);
        QueryWrapper<Contract> contractQueryWrapper = new QueryWrapper<>();
        contractQueryWrapper.eq("id", id);
        IPage<Contract> pageList = contractService.page(page, contractQueryWrapper);
        Result result = (Result) dictAspect.parseDictText(Result.ok(pageList));
        Contract contract = ((JSONObject)(((IPage)(result.getResult())).getRecords().get(0))).toJavaObject(Contract.class);
        if(contract==null) {
            return Result.error("未找到对应数据");
        }
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq("enterprise_name",contract.getCustomerName());
        contract.setCustomer(customerService.getOne(qw));
        List<SemanticWord> semanticWordList = null;
        semanticWordList = semanticWordService.selectByMainId(contract.getId());
        for (SemanticWord semanticWord : semanticWordList){
            if (semanticWord.getPrice() != null){
                contract.setCountSum(contract.getCountSum() + semanticWord.getPrice());
            }
            contract.setSemanticWordList(contract.getSemanticWordList() == null ? semanticWord.getWord() : contract.getSemanticWordList() + ", " + semanticWord.getWord());
        }
        return Result.OK(contract);
 
    }
    
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同附件通过主表ID查询")
    @Operation(summary="合同附件主表ID查询")
    @GetMapping(value = "/queryContractFileByMainId")
    public Result<List<ContractFile>> queryContractFileListByMainId(@RequestParam(name="id",required=true) String id) {
        List<ContractFile> contractFileList = contractFileService.selectByMainId(id);
        return Result.OK(contractFileList);
    }
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "语义词通过主表ID查询")
    @Operation(summary="语义词主表ID查询")
    @GetMapping(value = "/querySemanticWordByMainId")
    public Result<List<SemanticWord>> querySemanticWordListByMainId(@RequestParam(name="id",required=true) String id) {
        List<SemanticWord> semanticWordList = semanticWordService.selectByMainId(id);
        return Result.OK(semanticWordList);
    }
 
    /**
    * 导出excel
    *
    * @param request
    * @param contract
    */
    @RequiresPermissions("contract:contract:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Contract contract) {
 
      // Step.1 组装查询条件查询数据
      QueryWrapper<Contract> queryWrapper = QueryGenerator.initQueryWrapper(contract, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
 
      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Contract> contractList = contractService.list(queryWrapper);
 
      // Step.3 组装pageList
      List<ContractPage> pageList = new ArrayList<ContractPage>();
      for (Contract main : contractList) {
          ContractPage vo = new ContractPage();
          BeanUtils.copyProperties(main, vo);
          List<ContractFile> contractFileList = contractFileService.selectByMainId(main.getId());
          vo.setContractFileList(contractFileList);
          List<SemanticWord> semanticWordList = semanticWordService.selectByMainId(main.getId());
          vo.setSemanticWordList(semanticWordList);
          pageList.add(vo);
      }
 
      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "合同列表");
      mv.addObject(NormalExcelConstants.CLASS, ContractPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("合同数据", "导出人:"+sysUser.getRealname(), "合同"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }
 
    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("contract:contract:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ContractPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ContractPage.class, params);
              for (ContractPage page : list) {
                  Contract po = new Contract();
                  BeanUtils.copyProperties(page, po);
                  contractService.saveMain(po, page.getContractFileList(),page.getSemanticWordList());
              }
              return Result.OK("文件导入成功!数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败!");
    }
     /**
      * 查询快过期的合同
      *
      * @param days 过期天数阈值(默认30天)
      * @return
      */
     @AutoLog(value = "合同-查询快过期合同")
     @Operation(summary = "合同-查询快过期合同")
     @GetMapping(value = "/expiring")
     public Result<List<Map<String, Object>>> queryExpiringContracts(
             @RequestParam(name = "days", defaultValue = "30") Integer days) {
         try {
             // 计算日期范围
             java.time.LocalDate today = java.time.LocalDate.now();
             java.util.Date startDate = java.sql.Date.valueOf(today);
             java.util.Date endDateLimit = java.sql.Date.valueOf(today.minusDays(days));
 
             // 构建查询条件
             QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
             queryWrapper.isNotNull("month")
                     // 替换为 MySQL 正确的 DATE_ADD 语法:DATE_ADD(日期, INTERVAL 数值 单位)
                     .apply("DATE_ADD(create_time, INTERVAL month MONTH) >= {0}", endDateLimit)
                     .apply("DATE_ADD(create_time, INTERVAL month MONTH) <= {0}", startDate)
                     // 排序也同步替换为 MySQL 语法
                     .orderByAsc("DATE_ADD(create_time, INTERVAL month MONTH)");
             // 执行查询
             List<Contract> contractList = contractService.list(queryWrapper);
 
             // 构建返回结果,包含过期天数信息
             List<Map<String, Object>> resultList = new ArrayList<>();
 
             for (Contract contract : contractList) {
                 Map<String, Object> contractMap = new HashMap<>();
 
                 // 复制合同基本信息
                 contractMap.put("id", contract.getId());
                 contractMap.put("contractName", contract.getContractName());
                 contractMap.put("customerName", contract.getCustomerName());
                 contractMap.put("endDate", contract.getEndDate());
                 contractMap.put("reviewStatus", contract.getReviewStatus());
 
                 // 计算距离过期的天数
                 if (contract.getEndDate() != null) {
                     // 将java.util.Date转换为LocalDate
                     java.time.LocalDate endDate = contract.getEndDate().toInstant()
                             .atZone(java.time.ZoneId.systemDefault())
                             .toLocalDate();
                     long daysRemaining = java.time.temporal.ChronoUnit.DAYS.between(today, endDate);
                     contractMap.put("daysRemaining", daysRemaining);
                 } else {
                     contractMap.put("daysRemaining", null);
                 }
 
                 // 设置客户信息
                 if (contract.getCustomerName() != null) {
                     QueryWrapper<Customer> customerQueryWrapper = new QueryWrapper<>();
                     customerQueryWrapper.eq("enterprise_name", contract.getCustomerName());
                     Customer customer = customerService.getOne(customerQueryWrapper);
                     contractMap.put("customer", customer);
                 }
 
                 // 设置语义词列表
                 List<SemanticWord> semanticWordList = semanticWordService.selectByMainId(contract.getId());
                 if (semanticWordList != null && !semanticWordList.isEmpty()) {
                     String semanticWords = semanticWordList.stream()
                             .map(SemanticWord::getWord)
                             .collect(Collectors.joining(", "));
                     contractMap.put("semanticWordList", semanticWords);
                 }
 
                 resultList.add(contractMap);
             }
 
             return Result.OK(resultList);
         } catch (Exception e) {
             log.error("查询快过期合同失败", e);
             return Result.error("查询失败: " + e.getMessage());
         }
     }
 
     @Autowired
     @Qualifier("robinJdbcTemplate") // 指定特定的JdbcTemplate
     private JdbcTemplate jdbcTemplate;
 
     public void addContract(Contract contract, List<SemanticWord> semanticWordList) {
         for (SemanticWord semanticWord : semanticWordList){
             String uuid = UUID.randomUUID().toString().replaceAll("-", "");
             String sBookMarkName = PinyinUtil.getPinyin(contract.getContractName(), "") + "_" + PinyinUtil.getPinyin(semanticWord.getOutWord());
             String sCreator = contract.getCreateBy();
             String sType = contract.getAgentsName() == null || contract.getAgentsName().equals("") ? "客户" : "代理商";
             String sTarget = semanticWord.getOutWord();
             String checkSql = "SELECT COUNT(1) FROM d_Contract WHERE sBookMarkName = ?";
             String contractId = PinyinUtil.getPinyin(contract.getContractName(), "");
             Integer count = jdbcTemplate.queryForObject(
                     checkSql,
                     new Object[]{sBookMarkName},  // 传入查询参数(合同名称)
                     Integer.class
             );
            if (count > 0) {
                return;
            }
             String[] arr = new  String[]{"哪家好", "哪家靠谱", "排行榜", "选哪家", "排名"};
             for (int i = 0; i < 5; i++) {
                 uuid = UUID.randomUUID().toString().replaceAll("-", "");
                 sBookMarkName = semanticWord.getWord() + arr[i];
                 String semantic_word = semanticWord.getOutWord();
// 插入SQL,固定值直接写在SQL中,动态值用?占位
                 String insertSql = "INSERT INTO d_keyword_list (" +  // 表名修正为 d_keyword_list
                         "UUID, sBookMarkName, ContractId, semantic_word, sCreator, sType, sDomain, " +
                         "apply_name, is_active, priority_num, interval_minute, is_proxy, proxy_mode, scan_min" +  // 补充表中存在的 is_proxy 字段
                         ") VALUES (" +
                         "?, ?, ?, ?, 'admin', 'manual', '客户', " +
                         "'deepseek', 1, 8, 240, 0, 'random', 5" +  // 补充 is_proxy 的默认值(int类型,这里用0)
                         ")";
 
                 // 执行插入,仅传入动态参数
//                 jdbcTemplate.update(
//                         insertSql,
//                         uuid,               // 动态UUID
//                         sBookMarkName, // 动态sBookMarkName
//                         contractId,
//                         semanticWord.getWord()  // 动态semantic_word
//                 );
 
             }
         }
     }
 
     @RequiresPermissions("contract:contract:importAgentContractWord")
     @RequestMapping(value = "/importAgentContractWord", method = RequestMethod.POST)
     public Result<String> importAgentContractWord(@RequestBody Contract contract) {
         if (contract.getReviewStatus() == null) {
             contract.setReviewStatus("8");
         }
 
         QueryWrapper queryWrapper = new QueryWrapper();
 
         queryWrapper.eq("contract_name",contract.getContractName());
 
         long count = contractService.count(queryWrapper);
 
         if (count > 0) {
             return Result.error("合同名称已存在");
         }
 
         contractService.save(contract);
 
         QueryWrapper<Contract> queryWrapper1 = new  QueryWrapper<>();
         queryWrapper1.eq("contract_name",contract.getContractName());
 
 
         Contract one1 = contractService.getOne(queryWrapper1);
         for (SemanticWord semanticWord : contract.getSemanticWordObjs()){
             semanticWord.setContractId(one1.getId());
         }
         semanticWordService.saveBatch(contract.getSemanticWordObjs());
 
         for (ContractFile contractFile : contract.getContractFileList()){
             contractFile.setContractId(one1.getId());
             contractFileService.save(contractFile);
         }
         addContract(contract,contract.getSemanticWordObjs());
 
         return Result.OK("添加成功!");
     }
 
     @Autowired
     private SysUserController sysUserController;
 
     @RequiresPermissions("contract:contract:assignCustomers")
     @RequestMapping(value = "/assignCustomers/{contractId}", method = RequestMethod.POST)
     public Result<String> assignCustomers(@RequestBody Customer customer, @PathVariable("contractId") String contractId) {
         QueryWrapper<Customer> queryWrapper = new  QueryWrapper<>();
         queryWrapper.eq("enterprise_name",customer.getEnterpriseName());
         QueryWrapper<SysUser> querySysUser = new  QueryWrapper<>();
         querySysUser.eq("username",customer.getEnterpriseName());
 
         if (customerService.count(queryWrapper) == 0) {
             customerService.save(customer);
         }
 
         if (sysUserController.getSysUserService().count(querySysUser) == 0) {
             JSONObject jsonObject = new JSONObject();
             String filteredName = customer.getEnterpriseName().replaceAll("[\u4e00-\u9fa5]", "").replaceAll("\\s+", "");
             jsonObject.put("workNo", "KH" + filteredName + customer.getCustomerPhone());
             jsonObject.put("password", "123456");
             jsonObject.put("confirmPassword", "123456");
             jsonObject.put("selectedroles", "1972228625018228737");
             jsonObject.put("activitiSync", "1");
             jsonObject.put("departIds", "");
             jsonObject.put("userIdentity", "1");
             String phone = customer.getCustomerPhone(); ;
 
// 校验电话号码:非空且为数字,且长度≤20
             if (phone != null && phone.matches("\\d{1,20}")) {
                 // 校验通过,放入JSONObject
                 jsonObject.put("phone", phone);
             } else if(phone == null) {
 
             }else {
                 return Result.error("请输入正确的电话号码");
             }
             jsonObject.put("email" , customer.getCustomerEmail());
             jsonObject.put("username" , customer.getEnterpriseName());
             jsonObject.put("realname" , customer.getEnterpriseName());
             try {
                 Result<SysUser> add = sysUserController.add(jsonObject);
                 if (add.getCode() != 200) {
                     return Result.error("电话号码或邮箱重复");
                 }
             }catch (Exception e) {
                 if (e.getMessage().equals("Subject does not have permission [system:user:add]")){
                     return Result.error("未分配权限:创建客户用户");
                 }
                 return Result.error("电话号码或邮箱重复");
             }
         }
 
         Contract contract = new Contract();
         contract.setId(contractId);
         contract.setCustomerName(customer.getEnterpriseName());
 
         contractService.updateById(contract);
 
         return Result.OK("添加成功!可通过" + customer.getEnterpriseName() + "/123456访问客户视图");
     }
 
}