中扬CRM客户关系管理系统
LSH
2023-08-24 7cced07216f9be95eb6d5c26b74c2e736cda3594
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
package com.zy.crm.manager.controller;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.core.common.DateUtils;
import com.core.annotations.ManagerAuth;
import com.core.common.BaseRes;
import com.core.common.Cools;
import com.core.common.R;
import com.core.domain.KeyValueVo;
import com.zy.crm.common.web.BaseController;
import com.zy.crm.manager.entity.Item;
import com.zy.crm.manager.entity.Plan;
import com.zy.crm.manager.entity.PriOnline;
import com.zy.crm.manager.entity.PriSales;
import com.zy.crm.manager.service.ItemService;
import com.zy.crm.manager.service.PlanService;
import com.zy.crm.manager.service.PriOnlineService;
import com.zy.crm.manager.service.PriSalesService;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
 
@RestController
public class PriSalesController extends BaseController {
 
    @Autowired
    private PriSalesService priSalesService;
 
    @Autowired
    private PriOnlineService priOnlineService;
 
    @Autowired
    private PlanService planService;
 
    @RequestMapping(value = "/priSales/{id}/auth")
    @ManagerAuth
    public R get(@PathVariable("id") String id) {
        return R.ok(priSalesService.selectById(String.valueOf(id)));
    }
 
    @RequestMapping(value = "/priSales/list/auth")
    @ManagerAuth
    public R list(@RequestParam(defaultValue = "1")Integer curr,
                  @RequestParam(defaultValue = "10")Integer limit,
                  @RequestParam(required = false)String orderByField,
                  @RequestParam(required = false)String orderByType,
                  @RequestParam(required = false)String condition,
                  @RequestParam Map<String, Object> param){
        EntityWrapper<PriSales> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,title,create_time as createTime,filepath,item_id as itemId,order_num as orderNum,template_name as templateName,user_id as userId,update_user_id as updateUserId,update_time as updateTime,in_order_num as inOrderNum,member_id as memberId");
        wrapper.in("member_id", getUserRoleBelongsToUserId("allopen"));
        excludeTrash(param);
        convert(param, wrapper);
        allLike(PriSales.class, param.keySet(), wrapper, condition);
        if (!Cools.isEmpty(orderByField)){wrapper.orderBy(humpToLine(orderByField), "asc".equals(orderByType));}
        return R.ok(priSalesService.selectPage(new Page<>(curr, limit), wrapper));
    }
 
    private <T> void convert(Map<String, Object> map, EntityWrapper<T> wrapper){
        boolean signUserId = false;
        boolean signDeptId = false;
        for (Map.Entry<String, Object> entry : map.entrySet()){
            if (entry.getKey().equals("dept_id")){
                signDeptId = true;
            }
        }
        for (Map.Entry<String, Object> entry : map.entrySet()){
            String val = String.valueOf(entry.getValue());
            if (val.contains(RANGE_TIME_LINK)){
                String[] dates = val.split(RANGE_TIME_LINK);
                wrapper.ge(entry.getKey(), DateUtils.convert(dates[0]));
                wrapper.le(entry.getKey(), DateUtils.convert(dates[1]));
            } else if (entry.getKey().equals("dept_id")){
                if (!val.equals("19")){
                    wrapper.eq(entry.getKey(), val);
                }
            } else if (entry.getKey().equals("user_id") && !signDeptId){
                signUserId = true;
                wrapper.eq(entry.getKey(), val);
            } else {
                wrapper.like(entry.getKey(), val);
            }
        }
        if (!signUserId && !signDeptId){
            wrapper.eq("user_id", getUserId());
        }
    }
 
    @RequestMapping(value = "/priSales/add/auth")
    @ManagerAuth
    public R add(@RequestBody Map<String,Object> map) {
        PriOnline priOnline = priOnlineService.selectById(Long.parseLong(map.get("priOnlineId").toString()));
 
        PriSales priSales = new PriSales();
        priSales.setCreateTime(new Date());
        priSales.setTitle(map.get("title").toString());
        priSales.setTemplateName(priOnline.getTemplateName());
        priSales.setSheetData(map.get("sheetData").toString());
        priSales.setItemId(priOnline.getItemId());
        priSales.setOrderNum(priOnline.getOrderNum());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        priSales.setInOrderNum(format.format(new Date()));
 
        //创建人员
        priSales.setUserId(getUserId());
        //更新人员
        priSales.setUpdateUserId(getUserId());
        //更新时间
        priSales.setUpdateTime(new Date());
        priSales.setDeptId(getDeptId());
 
        //业务员
        Plan plan = planService.selectById(priSales.getItemId());
        priSales.setMemberId(plan.getUserId());
 
        //设置项目流程
        plan.setStep(3);
        planService.updateById(plan);
 
        priSalesService.insert(priSales);
        return R.ok();
    }
 
    @RequestMapping(value = "/priSales/addOther/auth")
    @ManagerAuth
    public R addOther(@RequestBody Map<String,Object> map) {
        PriSales online = priSalesService.selectById(Long.parseLong(map.get("id").toString()));
 
        PriSales priSales = new PriSales();
        priSales.setCreateTime(new Date());
        priSales.setTitle(map.get("title").toString());
        priSales.setTemplateName(online.getTemplateName());
        priSales.setSheetData(map.get("sheetData").toString());
        priSales.setItemId(online.getItemId());
        priSales.setOrderNum(online.getOrderNum());
 
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        priSales.setInOrderNum(format.format(new Date()));
 
        //创建人员
        priSales.setUserId(getUserId());
        //更新人员
        priSales.setUpdateUserId(getUserId());
        //更新时间
        priSales.setUpdateTime(new Date());
 
        //业务员
        Plan plan = planService.selectById(priSales.getItemId());
        priSales.setMemberId(plan.getUserId());
 
        priSalesService.insert(priSales);
        return R.ok();
    }
 
    @RequestMapping(value = "/priSales/update/auth")
    @ManagerAuth
    public R update(@RequestBody Map<String,Object> map){
        PriSales priSales = priSalesService.selectById(Long.parseLong(map.get("id").toString()));
        priSales.setTitle(map.get("title").toString());
        priSales.setSheetData(map.get("sheetData").toString());
        //更新时间
        priSales.setUpdateTime(new Date());
        //更新人员
        priSales.setUpdateUserId(getUserId());
        priSalesService.updateById(priSales);
        return R.ok();
    }
 
    @RequestMapping(value = "/priSales/updateForm/auth")
    @ManagerAuth
    public R updateForm(Long id,String templateName,String title){
        PriSales priSales = priSalesService.selectById(id);
        priSales.setTemplateName(templateName);
        priSales.setTitle(title);
        //更新时间
        priSales.setUpdateTime(new Date());
        //更新人员
        priSales.setUpdateUserId(getUserId());
        priSalesService.updateById(priSales);
        return R.ok();
    }
 
    @RequestMapping(value = "/priSales/delete/auth")
    @ManagerAuth
    public R delete(Long[] ids){
        if (Cools.isEmpty(ids)){
            return R.error();
        }
        priSalesService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
 
    @RequestMapping(value = "/priSales/export/auth")
    @ManagerAuth
    public R export(@RequestBody JSONObject param){
        EntityWrapper<PriSales> wrapper = new EntityWrapper<>();
        List<String> fields = JSONObject.parseArray(param.getJSONArray("fields").toJSONString(), String.class);
        Map<String, Object> map = excludeTrash(param.getJSONObject("priOnline"));
        convert(map, wrapper);
        List<PriSales> list = priSalesService.selectList(wrapper);
        return R.ok(exportSupport(list, fields));
    }
 
    @RequestMapping(value = "/priSalesQuery/auth")
    @ManagerAuth
    public R query(String condition) {
        EntityWrapper<PriSales> wrapper = new EntityWrapper<>();
        wrapper.like("id", condition);
        wrapper.in("member_id", getUserRoleBelongsToUserId("allopen"));
        Page<PriSales> page = priSalesService.selectPage(new Page<>(0, 10), wrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (PriSales priSales : page.getRecords()){
            Map<String, Object> map = new HashMap<>();
            map.put("id", priSales.getId());
            map.put("value", priSales.getInOrderNum() + "/" + priSales.getPlanId$() + "/" + priSales.getMemberId$());
            result.add(map);
        }
        return R.ok(result);
    }
 
    @RequestMapping(value = "/priSales/check/column/auth")
    @ManagerAuth
    public R query(@RequestBody JSONObject param) {
        Wrapper<PriSales> wrapper = new EntityWrapper<PriSales>().eq(humpToLine(String.valueOf(param.get("key"))), param.get("val"));
        if (null != priSalesService.selectOne(wrapper)){
            return R.parse(BaseRes.REPEAT).add(getComment(PriSales.class, String.valueOf(param.get("key"))));
        }
        return R.ok();
    }
 
    @RequestMapping("/priSales/all/get/kv")
    @ManagerAuth
    public R getDataKV(@RequestParam(required = false) String condition) {
        List<KeyValueVo> vos = new ArrayList<>();
        Wrapper<PriSales> wrapper = new EntityWrapper<PriSales>().andNew().like("id", condition).orderBy("create_time", false);
        priSalesService.selectPage(new Page<>(1, 30), wrapper).getRecords().forEach(item -> vos.add(new KeyValueVo(String.valueOf(item.getId()), item.getId())));
        return R.ok().add(vos);
    }
 
    @PostMapping("/priSales/excel/downfile")
    @ManagerAuth
    public R downExcelFile(@RequestBody Map<String,Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String path =  ClassUtils.getDefaultClassLoader().getResource("excel").getPath();
        String filename = format.format(new Date()) + ".xlsx";
        String filepath = path + "/" + filename;
        exportLuckySheetXlsx(path,"/" + filename,map.get("exceldata").toString(),Integer.parseInt(map.get("endRow").toString()));
 
        return R.ok("/priSales/excel/" + filename);
    }
 
    @GetMapping("/priSales/excel/{path}")
    public void download(@PathVariable String path,HttpServletResponse response) {
        try {
            ClassPathResource pathResource = new ClassPathResource("excel/" + path);
            File file = pathResource.getFile();
            InputStream inputStream = pathResource.getInputStream();
            //输出文件
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
 
            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public void exportLuckySheetXlsx(String newFileDir,String newFileName, String excelData,int excelDataEndRow) {
        //解析对象,可以参照官方文档:https://mengshukeji.github.io/LuckysheetDocs/zh/guide/#%E6%95%B4%E4%BD%93%E7%BB%93%E6%9E%84
        JSONArray jsonArray = (JSONArray) JSONObject.parse(excelData);
        //如果只有一个sheet那就是get(0),有多个那就对应取下标
        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        JSONArray jsonObjectList = jsonObject.getJSONArray("celldata");
        //excel模板路径
        String filePath =  ClassUtils.getDefaultClassLoader().getResource("excel").getPath() + "/priSalesTemplate.xlsx";
//        String filePath = "/Users/ouyang/Downloads/uploadTestProductFile/生产日报表.xlsx";
        File file = new File(filePath);
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //读取excel模板
        XSSFWorkbook wb = null;
        try {
            wb = new XSSFWorkbook(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读取了模板内所有sheet内容
        XSSFSheet sheet = wb.getSheetAt(0);
        //如果这行没有了,整个公式都不会有自动计算的效果的
        sheet.setForceFormulaRecalculation(true);
 
        //表单数据结束行,默认是11
        int endRow = 11;
 
 
        if (excelDataEndRow != -1) {
            //需要自行寻找数据行index
            //此循环主要目的是为了找到表单数据结束行位置,从而进行下一步精准的数据填充
            for (int index = 0; index < jsonObjectList.size(); index++) {
                com.alibaba.fastjson.JSONObject object = jsonObjectList.getJSONObject(index);
                String str_ = (int) object.get("r") + "_" + object.get("c") + "=" + ((com.alibaba.fastjson.JSONObject) object.get("v")).get("v") + "\n";
                JSONObject jsonObjectValue = ((com.alibaba.fastjson.JSONObject) object.get("v"));
                //判断是否超过4行,4行之后才是真正数据
                if (Integer.parseInt(object.get("r").toString()) < 4) {
                    continue;
                }
 
                //超过4行,开始统计数据
 
                String value = "";
                if (jsonObjectValue != null && jsonObjectValue.get("v") != null){
                    //获取单元格值
                    value = jsonObjectValue.get("v") + "";
                    if (value.equals("合计:")) {
                        //表单结束
                        Object row = jsonObjectValue.getOrDefault("row",null);
                        if (row == null) {
                            System.out.println("未能成功计算到数据行结束");
                            continue;
                        }
                        endRow = Integer.parseInt(jsonObjectValue.get("row").toString()) - 1;
                        break;
                    }
                }
            }
        }else {
            //前端提交数据行结束位置
            endRow = excelDataEndRow;
        }
 
        //此循环主要目的是进行数据的填充
        for (int index = 0; index < jsonObjectList.size(); index++) {
            com.alibaba.fastjson.JSONObject object = jsonObjectList.getJSONObject(index);
            String str_ = (int) object.get("r") + "_" + object.get("c") + "=" + ((com.alibaba.fastjson.JSONObject) object.get("v")).get("v") + "\n";
            JSONObject jsonObjectValue = ((com.alibaba.fastjson.JSONObject) object.get("v"));
 
            //判断是否超过4行,或超过数据最大行
            if (Integer.parseInt(object.get("r").toString()) < 4 || Integer.parseInt(object.get("r").toString()) > endRow) {
                continue;
            }
 
            //开始统计数据
 
            String value = "";
            switch (Integer.parseInt(object.get("c").toString())) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                    if (jsonObjectValue != null && jsonObjectValue.get("v") != null){
                        //获取单元格值
                        value = jsonObjectValue.get("v").toString();
                    }
                    if (sheet.getRow((int) object.get("r")) !=null && sheet.getRow((int) object.get("r")).getCell((int) object.get("c")) != null){
                        if (!value.equals("")) {
                            sheet.getRow((int) object.get("r")).getCell((int) object.get("c")).setCellValue(value);
                        }
                    }else{
                        System.out.println("错误的=" + index + ">>>" + str_);
                    }
                    break;
                default:
                    continue;
            }
        }
 
        // 判断路径是否存在
        File dir = new File(newFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //修改模板内容导出新模板
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(newFileDir + newFileName);
            wb.write(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}