wuzeyu
2024-08-16 6f346cec0b4646bdf750781075e46a4f028cd35b
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
package com.dy.pipIrrProject.divide;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.dy.common.aop.SsoAop;
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.BaseResponseUtils;
import com.dy.common.webUtil.QueryResultVo;
import com.dy.common.webUtil.ResultCodeMsg;
import com.dy.pipIrrGlobal.pojoBa.BaClient;
import com.dy.pipIrrGlobal.pojoPr.PrDivide;
import com.dy.pipIrrGlobal.voPr.VoDivide;
import com.dy.pipIrrGlobal.voSe.VoActiveCard;
import com.dy.pipIrrProject.result.ProjectResultCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
 
/**
 * @author ZhuBaoMin
 * @date 2023/12/20 20:11
 * @LastEditTime 2023/12/20 20:11
 * @Description
 */
 
@Slf4j
@Tag(name = "分水房管理", description = "分水房操作")
@RestController
@RequestMapping(path="divide")
@RequiredArgsConstructor
public class DivideCtrl {
    private final DivideSv divideSv;
 
    /**
     * 分页获取分水房记录
     * @param vo
     * @return
     */
    @Operation(summary = "获得一页分水房记录", description = "返回一页分水房数据")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回一页开卡数据(BaseResponse.content:QueryResultVo[{}])",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = VoActiveCard.class))}
            )
    })
    @GetMapping(path = "/getDivides")
    @SsoAop()
    public BaseResponse<QueryResultVo<List<VoDivide>>> getDivides(QueryVo vo){
        try {
            QueryResultVo<List<VoDivide>> res = divideSv.getDivides(vo);
            if(res.itemTotal != null && res.itemTotal > 0) {
                return BaseResponseUtils.buildSuccess(res);
            }else {
                return BaseResponseUtils.buildSuccess(ProjectResultCode.NO_DIVIDES.getMessage());
            }
        } catch (Exception e) {
            log.error("获取开卡记录异常", e);
            return BaseResponseUtils.buildException(e.getMessage()) ;
        }
    }
 
    /**
     * 根据分水房主键获取分水房对象
     * @param id
     * @return
     */
    @Operation(summary = "获得一个分水房", description = "返回一个分水房数据")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回一页农户数据(BaseResponse.content:QueryResultVo[{}])",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = BaClient.class))}
            )
    })
    @GetMapping(path = "/getone/{id}")
    @SsoAop()
    public BaseResponse<PrDivide> getOneDivide(@PathVariable("id") Long id){
        try {
            PrDivide res = divideSv.getOneDivide(id);
            if(res != null) {
                return BaseResponseUtils.buildSuccess(res);
            }else {
                return BaseResponseUtils.buildFail(ProjectResultCode.NO_DIVIDES.getMessage());
            }
        } catch (Exception e) {
            log.error("查询农户异常", e);
            return BaseResponseUtils.buildException(e.getMessage()) ;
        }
    }
 
    /**
     * 添加分水房记录
     * @param po
     * @param bindingResult
     * @return
     */
    @Operation(summary = "添加分水房记录", description = "添加分水房记录")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @PostMapping(path = "add", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<Boolean> add(@RequestBody @Valid DtoDivide po, BindingResult bindingResult){
        if(bindingResult != null && bindingResult.hasErrors()){
            return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        // 接收村编号(主键)
        Long villageId = po.getVillageId();
 
        PrDivide prDivide = DtoToDividePojo.INSTANCT.po2vo(po);
 
        if (villageId!=null){
            /**
             * 获取5级行政区划信息
             */
            Map map_districts = Optional.ofNullable(divideSv.getDistrictsByVillageId(villageId)).orElse(new HashMap());
            if(map_districts.size() <= 0) {
                return BaseResponseUtils.buildFail("区划信息有误");
            }
            Long countryId = Long.parseLong(map_districts.get("countryId").toString());
            Long townId = Long.parseLong(map_districts.get("townId").toString());
            prDivide.setCountyid(countryId);
            prDivide.setTownid(townId);
        }
 
        Date operateTime = new Date();
        prDivide.setOperatedt(operateTime);
        prDivide.setDeleted((byte)0);
        Integer rec = Optional.ofNullable(divideSv.addDivide(prDivide)).orElse(0);
        if(rec == 0) {
            return BaseResponseUtils.buildFail(ProjectResultCode.DIVIDE_FAIL.getMessage());
        }
        return BaseResponseUtils.buildSuccess(true) ;
    }
 
    /**
     * 根据分水房ID逻辑删除分水房
     * @param map
     * @return
     */
    @Operation(summary = "删除一个分水房", description = "删除一个分水房数据")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回一页农户数据(BaseResponse.content:QueryResultVo[{}])",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = BaClient.class))}
            )
    })
 
    //@GetMapping(path = "/delone/{id}")
    @PostMapping(path = "delete", consumes = MediaType.APPLICATION_JSON_VALUE)
    @SsoAop()
    public BaseResponse<Boolean> deleteDivideById(@RequestBody Map map){
        Long id = Optional.ofNullable(Long.parseLong(map.get("id").toString())).orElse(0L);
        if(id == 0)
            return BaseResponseUtils.buildException(ProjectResultCode.DELETE_DIVIDE_FAIL.getMessage());
 
        try {
            Integer res = Optional.ofNullable(divideSv.deleteDivideById(id)).orElse(0);
            if(res == 0)
                return BaseResponseUtils.buildFail(ProjectResultCode.DELETE_DIVIDE_FAIL.getMessage());
 
            return BaseResponseUtils.buildSuccess(true);
        } catch (Exception e) {
            log.error("删除分水房异常", e);
            return BaseResponseUtils.buildException(e.getMessage()) ;
        }
    }
 
    /**
     * 修改分水房
     * @param po
     * @param bindingResult
     * @return
     */
    @Operation(summary = "修改分水房记录", description = "修改分水房记录")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @PostMapping(path = "update", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<Boolean> update(@RequestBody @Valid DtoDivide po, BindingResult bindingResult){
        if(bindingResult != null && bindingResult.hasErrors()){
            return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
 
        // 接收村编号(主键)
        Long villageId = po.getVillageId();
 
        PrDivide prDivide = DtoToDividePojo.INSTANCT.po2vo(po);
 
        if (villageId!=null){
            /**
             * 获取5级行政区划信息
             */
            Map map_districts = Optional.ofNullable(divideSv.getDistrictsByVillageId(villageId)).orElse(new HashMap());
            if(map_districts.size() <= 0) {
                return BaseResponseUtils.buildFail("区划信息有误");
            }
            Long countryId = Long.parseLong(map_districts.get("countryId").toString());
            Long townId = Long.parseLong(map_districts.get("townId").toString());
            prDivide.setCountyid(countryId);
            prDivide.setTownid(townId);
        }
 
        Date operateTime = new Date();
        prDivide.setOperatedt(operateTime);
 
        Integer rec = Optional.ofNullable(divideSv.updateByPrimaryKey(prDivide)).orElse(0);
        if(rec == 0) {
            return BaseResponseUtils.buildFail("分水房修改失败");
        }
        return BaseResponseUtils.buildSuccess(true) ;
    }
 
    /**
     * 导出分水房列表
     * @param response
     * @param vo
     */
    @SneakyThrows(IOException.class)
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletResponse response, QueryVo vo) {
        setExcelRespProp(response, "分水房列表");
        //List<VoDivide> memberList = LocalJsonUtil.getListFromJson("json/members.json", VoDivide.class);
        List<VoDivide> memberList = divideSv.exportDivides(vo);
 
        EasyExcel.write(response.getOutputStream())
                .head(VoDivide.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("分水房列表")
                .doWrite(memberList);
    }
 
    @SneakyThrows
    @RequestMapping(value = "/importDivides", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse<Boolean> importDivides(@RequestPart("file") MultipartFile file) {
        List<VoDivide> memberList = EasyExcel.read(file.getInputStream())
                .head(VoDivide.class)
                .sheet()
                .doReadSync();
        return BaseResponseUtils.buildSuccess(memberList) ;
    }
 
    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}