yaozc
2023-02-22 b2ff1a98d52114db45c0ecd2f82b33e4ba25df47
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
/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;
 
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.SysLevel;
import me.zhengjie.modules.system.domain.SysUserLevelInsurance;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysLevelRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.SysUserLevelInsuranceRepository;
import me.zhengjie.modules.system.service.SysUserLevelInsuranceService;
import me.zhengjie.modules.system.service.dto.SysUserLevelInsuranceDto;
import me.zhengjie.modules.system.service.dto.SysUserLevelInsuranceQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.SysUserLevelInsuranceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
 
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.function.Function;
 
/**
* @website https://eladmin.vip
* @description 服务实现
* @author 赵士淞
* @date 2022-12-26
**/
@Service
@RequiredArgsConstructor
public class SysUserLevelInsuranceServiceImpl implements SysUserLevelInsuranceService {
 
    private final SysUserLevelInsuranceRepository sysUserLevelInsuranceRepository;
    private final SysUserLevelInsuranceMapper sysUserLevelInsuranceMapper;
    private final UserRepository userRepository;
    private final SysLevelRepository sysLevelRepository;
 
    @Override
    public Map<String,Object> queryAll(SysUserLevelInsuranceQueryCriteria criteria, Pageable pageable){
        Page<SysUserLevelInsurance> page = sysUserLevelInsuranceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        // 将实体类转换为DTO(重写)
        Function<SysUserLevelInsurance, SysUserLevelInsuranceDto> func = new Function<SysUserLevelInsurance, SysUserLevelInsuranceDto>(){
            @Override
            public SysUserLevelInsuranceDto apply(SysUserLevelInsurance t) {
                // 将实体类转换成DTO
                SysUserLevelInsuranceDto sysUserLevelInsuranceDto = sysUserLevelInsuranceMapper.toDto(t);
                // 根据用户ID查询用户信息
                User user = userRepository.findById(sysUserLevelInsuranceDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(user.getId(),"User","id",sysUserLevelInsuranceDto.getUserId());
                // 用户昵称
                sysUserLevelInsuranceDto.setUserNickName(user.getNickName());
                // 根据级别ID查询级别信息
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelInsuranceDto.getLevelId()).orElseGet(SysLevel::new);
                ValidationUtil.isNull(sysLevel.getId(),"SysLevel","id",sysUserLevelInsuranceDto.getLevelId());
                // 级别名称
                sysUserLevelInsuranceDto.setLevelName(sysLevel.getName());
                // 返回处理好的DTO
                return sysUserLevelInsuranceDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
 
    @Override
    public List<SysUserLevelInsuranceDto> queryAll(SysUserLevelInsuranceQueryCriteria criteria){
        return sysUserLevelInsuranceMapper.toDto(sysUserLevelInsuranceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
 
    @Override
    public SysUserLevelInsuranceDto queryTargetYearMonth(SysUserLevelInsuranceQueryCriteria criteria){
        // 国际时间转中国时间
        String targetYearMonth = DateUtil.internationalTimeToChinaTime(criteria.getTargetYearMonth());
        // 获取某年某月最后一天
        String lastDayOfTargetYearMonth = DateUtil.getLastDayOfMonth(targetYearMonth);
        // 根据用户ID、指定年月查询
        SysUserLevelInsurance sysUserLevelInsurance = sysUserLevelInsuranceRepository.findTargetYearMonth(criteria.getUserId(), lastDayOfTargetYearMonth);
        // 判断查询结果
        if (sysUserLevelInsurance == null) {
            throw new BadRequestException("没有获取到当前员工的级别信息!");
        }
        // 返回
        return sysUserLevelInsuranceMapper.toDto(sysUserLevelInsurance);
    }
 
    @Override
    @Transactional
    public SysUserLevelInsuranceDto findById(Long id) {
        SysUserLevelInsurance sysUserLevelInsurance = sysUserLevelInsuranceRepository.findById(id).orElseGet(SysUserLevelInsurance::new);
        ValidationUtil.isNull(sysUserLevelInsurance.getId(),"SysUserLevelInsurance","id",id);
        return sysUserLevelInsuranceMapper.toDto(sysUserLevelInsurance);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserLevelInsuranceDto create(SysUserLevelInsurance resources) throws Exception {
        // 查询旧用户级别保险
        SysUserLevelInsurance oldSysUserLevelInsurance = selectOldUserLevelInsurance(resources.getUserId());
        // 判断旧用户级别保险是否为空
        if (oldSysUserLevelInsurance != null) {
            // 旧日期字符串
            String oldDateString = oldSysUserLevelInsurance.getStartDate().toString().substring(0,10);
            // 新日期字符串
            String newDateString = resources.getStartDate().toString().substring(0,10);
            // 判断新、旧日期字符串
            if (oldDateString.equals(newDateString)) {
                throw new BadRequestException("每天只能调整一次用户级别保险,请更换日期再试!");
            }
            if (new SimpleDateFormat("yyyy-MM-dd").parse(oldDateString).getTime() >= new SimpleDateFormat("yyyy-MM-dd").parse(newDateString).getTime()) {
                throw new BadRequestException("日期必须大于最新用户级别保险日期,请更换日期再试!");
            }
            // 创建Calendar实例
            Calendar previousCalendar = Calendar.getInstance();
            // 设置新日期时间
            previousCalendar.setTime(resources.getStartDate());
            // 设置前一天时间
            previousCalendar.add(Calendar.DATE, -1);
            // 旧用户级别保险
            oldSysUserLevelInsurance.setEndDate(new Timestamp(previousCalendar.getTime().getTime()));
            // 保存
            sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
        }
        // 保存
        return sysUserLevelInsuranceMapper.toDto(sysUserLevelInsuranceRepository.save(resources));
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserLevelInsurance resources) throws Exception {
        // 查询旧用户级别保险
        SysUserLevelInsurance oldSysUserLevelInsurance = selectOldUserLevelInsurance(resources.getUserId());
        // 判断旧用户级别保险是否为空
        if (oldSysUserLevelInsurance != null) {
            // 判断修改的是否是最新履历
            if (oldSysUserLevelInsurance.getId() != resources.getId()) {
                throw new BadRequestException("旧用户级别保险无法进行修改,请选择最新用户级别保险再试!");
            }
            // 旧日期字符串
            String oldDateString = oldSysUserLevelInsurance.getStartDate().toString().substring(0,10);
            // 获取当前日期
            Date nowDate = new Date();
            // 创建Calendar实例
            Calendar nowCalendar = Calendar.getInstance();
            // 设置当前时间
            nowCalendar.setTime(nowDate);
            // 新日期字符串
            String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0,10);
            // 判断新、旧日期字符串
            if (new SimpleDateFormat("yyyy-MM-dd").parse(oldDateString).getTime() >= new SimpleDateFormat("yyyy-MM-dd").parse(nowDateString).getTime()) {
                // 复制
                oldSysUserLevelInsurance.copy(resources);
                // 保存
                sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
            } else {
                // 新用户级别保险
                resources.setId(null);
                resources.setStartDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelInsuranceRepository.save(resources);
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别保险
                oldSysUserLevelInsurance.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
            }
        } else {
            throw new BadRequestException("未找到最新用户级别保险,请稍后再试!");
        }
    }
 
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            sysUserLevelInsuranceRepository.deleteById(id);
        }
    }
 
    @Override
    public void download(List<SysUserLevelInsuranceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysUserLevelInsuranceDto sysUserLevelInsurance : all) {
            String nickName = sysUserLevelInsurance.getUserId() != null ? userRepository.findById(sysUserLevelInsurance.getUserId()).orElseGet(User::new).getNickName() : "";
            String levelName = sysUserLevelInsurance.getLevelId() != null ? sysLevelRepository.findById(sysUserLevelInsurance.getLevelId()).orElseGet(SysLevel::new).getName() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户昵称", nickName);
            map.put("级别名称", levelName);
            map.put("开始日期", sysUserLevelInsurance.getStartDate());
            map.put("结束日期", sysUserLevelInsurance.getEndDate());
            map.put("公积金基数", sysUserLevelInsurance.getAccumulationRadix());
            map.put("公积金个人缴纳比例", sysUserLevelInsurance.getAccumulationPersonalProportion());
            map.put("公积金公司缴纳比例", sysUserLevelInsurance.getAccumulationCompanyProportion());
            map.put("养老险基数", sysUserLevelInsurance.getPensionRadix());
            map.put("养老险个人缴纳比例", sysUserLevelInsurance.getPensionPersonalProportion());
            map.put("养老险公司缴纳比例", sysUserLevelInsurance.getPensionCompanyProportion());
            map.put("医疗险基数", sysUserLevelInsurance.getMedicalRadix());
            map.put("医疗险个人缴纳比例", sysUserLevelInsurance.getMedicalPersonalProportion());
            map.put("医疗险公司缴纳比例", sysUserLevelInsurance.getMedicalCompanyProportion());
            map.put("失业险基数", sysUserLevelInsurance.getUnemploymentRadix());
            map.put("失业险个人缴纳比例", sysUserLevelInsurance.getUnemploymentPersonalProportion());
            map.put("失业险公司缴纳比例", sysUserLevelInsurance.getUnemploymentCompanyProportion());
            map.put("生育险基数", sysUserLevelInsurance.getMaternityRadix());
            map.put("生育险个人缴纳比例", sysUserLevelInsurance.getMaternityPersonalProportion());
            map.put("生育险公司缴纳比例", sysUserLevelInsurance.getMaternityCompanyProportion());
            map.put("工伤险基数", sysUserLevelInsurance.getIndustrialInjuryRadix());
            map.put("工伤险个人缴纳比例", sysUserLevelInsurance.getIndustrialInjuryPersonalProportion());
            map.put("工伤险公司缴纳比例", sysUserLevelInsurance.getIndustrialInjuryCompanyProportion());
            map.put("备注", sysUserLevelInsurance.getRemarks());
            map.put("创建者", sysUserLevelInsurance.getCreateBy());
            map.put("创建时间", sysUserLevelInsurance.getCreateTime());
            map.put("更新者", sysUserLevelInsurance.getUpdateBy());
            map.put("更新时间", sysUserLevelInsurance.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
 
    /**
     * 查询旧用户级别保险
     * @param userId
     * @return
     */
    private SysUserLevelInsurance selectOldUserLevelInsurance(Long userId) {
        // 旧用户级别保险
        SysUserLevelInsurance oldSysUserLevelInsurance = sysUserLevelInsuranceRepository.findLastByUserId(userId);
        // 判断旧用户级别保险是否为空
        if (oldSysUserLevelInsurance != null && oldSysUserLevelInsurance.getId() != null) {
            return oldSysUserLevelInsurance;
        } else {
            return null;
        }
    }
}