zhujie
2025-04-11 c6bb4daa335c7615610ca0f7e404ca7aa2825dce
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.mzl.flower.service.customer;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.config.security.SecurityUtils;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.customer.BindPartnerDTO;
import com.mzl.flower.dto.request.customer.ChangePartnerDTO;
import com.mzl.flower.dto.request.customer.QueryCustomerDTO;
import com.mzl.flower.dto.request.customer.UpdateCustomerDTO;
import com.mzl.flower.dto.request.menber.UserGrowthRecordDTO;
import com.mzl.flower.dto.response.customer.CustomerDTO;
import com.mzl.flower.dto.response.partner.PartnerDTO;
import com.mzl.flower.dto.response.supplier.SupplierDTO;
import com.mzl.flower.entity.customer.Customer;
import com.mzl.flower.entity.partner.Partner;
import com.mzl.flower.enums.TrueOrFalseEnum;
import com.mzl.flower.mapper.customer.CustomerMapper;
import com.mzl.flower.mapper.partner.PartnerMapper;
import com.mzl.flower.service.menber.MemberGrowthRecordService;
import lombok.extern.slf4j.Slf4j;
import com.mzl.flower.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
 
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
 
@Service
@Transactional
@Slf4j
public class CustomerService {
 
 
    private final CustomerMapper customerMapper;
 
    private final PartnerMapper partnerMapper;
    @Resource
    private MemberGrowthRecordService memberGrowthRecordService;
 
    @Resource
    private BaseService baseService;
 
    private static final String CHARACTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
 
    private final Random random = new Random();
 
    public CustomerService(CustomerMapper customerMapper, PartnerMapper partnerMapper) {
        this.customerMapper = customerMapper;
        this.partnerMapper = partnerMapper;
    }
 
    public CustomerDTO getCurrentCustomer() {
        CustomerDTO currentCustomer = customerMapper.getCurrentCustomer(SecurityUtils.getUserId());
        UserGrowthRecordDTO userGrowthRecordDTO = memberGrowthRecordService.getInfoByUserId(SecurityUtils.getUserId());
        if(!ObjectUtils.isEmpty(userGrowthRecordDTO)){
            currentCustomer.setUserGrowthRecord(userGrowthRecordDTO);
        }
        return currentCustomer;
    }
 
    public PartnerDTO getCurrentBindPartner() {
        CustomerDTO cus = customerMapper.getCurrentCustomer(SecurityUtils.getUserId());
        if (cus != null && StringUtils.isNotBlank(cus.getPartnerId())) {
            return partnerMapper.getCurrentPartner(cus.getPartnerUserId());
        }
        return null;
    }
 
    public void addOrUpdateCustomer(UpdateCustomerDTO dto) {
 
        Customer customer;
        if (dto.getId() == null) { //注册
            if (checkExist(dto.getUserId())) {
                throw new ValidationException("商户信息已注册");
            }
            customer = new Customer();
            BeanUtils.copyProperties(dto, customer, "id");
            Partner byPartnerId = getByPartnerId(dto.getPartnerUserId());
            if (byPartnerId != null) {
                customer.setPartnerUserId(byPartnerId.getUserId());
                customer.setPartnerId(byPartnerId.getId());
            }
 
            customer.create(SecurityUtils.getUserId());
            customer.setIsEnabled(true);
            customer.setIntervialcode(generateCode());
            customer.setReintervialcode(dto.getRegesterCode());
            customer.setLevelId(Long.valueOf(Constants.DEFAULT_MEMBER_ID));
            customerMapper.insert(customer);
        } else {//重新修改
            customer = customerMapper.selectById(dto.getId());
            if (customer == null) {
                throw new ValidationException("商户信息不存在");
            }
            BeanUtils.copyProperties(dto, customer, "id");
//            customer.setPartnerUserId(getByPartnerId(dto.getPartnerUserId()));
            Partner byPartnerId = getByPartnerId(dto.getPartnerUserId());
            if (byPartnerId != null) {
                customer.setPartnerUserId(byPartnerId.getUserId());
                customer.setPartnerId(byPartnerId.getId());
            }
            customer.update(SecurityUtils.getUserId());
            customerMapper.updateById(customer);
        }
 
 
    }
 
    private Partner getByPartnerId(String partnerId) {
        if (StringUtils.isNotBlank(partnerId)) {
            Partner partnerByUserId = partnerMapper.selectOne(new QueryWrapper<Partner>().eq("user_id", partnerId));
            if (partnerByUserId != null) {
                return partnerByUserId;
            }
            Partner partner = partnerMapper.selectById(partnerId);
            if (partner == null) {
                throw new ValidationException("合伙人不存在");
            } else {
                //判断id和userid是否相同,避免string被转为int
                if (!partner.getUserId().equals(partnerId) && !partner.getId().toString().equals(partnerId)) {
                    throw new ValidationException("合伙人不存在");
                }
            }
//            return partner.getUserId();
            return partner;
        }
        return null;
 
    }
 
    private boolean checkExist(String userId) {
        return customerMapper.selectCount(new LambdaQueryWrapper<Customer>().eq(Customer::getUserId, userId)) > 0;
    }
 
    //验证邀请码是否有效
    public boolean checkCode(String code) {
        return customerMapper.findCustomerByInvitationCode(code) == null;
    }
 
    public Page<CustomerDTO> queryCustomer(QueryCustomerDTO dto, Page page) {
        List<CustomerDTO> list = customerMapper.queryCustomer(dto, page);
        page.setRecords(list);
        return page;
    }
 
    public CustomerDTO findDetail(Long id) {
        Customer customer = customerMapper.selectById(id);
        if (customer == null) {
            return null;
        }
        if (Constants.USER_TYPE.admin.name().equals(SecurityUtils.getUserType())) {
            CustomerDTO customerDTO = new CustomerDTO();
            BeanUtils.copyProperties(customer, customerDTO);
            return customerDTO;
        } else if (Constants.USER_TYPE.partner.name().equals(SecurityUtils.getUserType())) {
            if (customer.getPartnerUserId().equals(SecurityUtils.getUserId())) {
                CustomerDTO customerDTO = new CustomerDTO();
                BeanUtils.copyProperties(customer, customerDTO);
                return customerDTO;
            }
        }
        return null;
    }
 
    public void changeCustomerPartner(ChangePartnerDTO dto) {
        Customer customer = customerMapper.selectById(dto.getId());
        if (customer == null) {
            throw new ValidationException("商户信息不存在");
        }
        if (dto.getPartnerId() == null || dto.getPartnerId() <= 0) {
            customer.setPartnerUserId(null);
            customer.setPartnerId(null);
        } else {
            Partner partner = partnerMapper.selectById(dto.getPartnerId());
            if (partner == null) {
                throw new ValidationException("合伙人不存在");
            }
            if (!"P".equals(partner.getStatus())) {
                throw new ValidationException("合伙人信息未审核通过");
            }
            customer.setPartnerUserId(partner.getUserId());
            customer.setPartnerId(partner.getId());
        }
        customerMapper.updateById(customer);
    }
 
    public void bindPartner(BindPartnerDTO dto) {
        CustomerDTO c = getCurrentCustomer();
        if (c == null) {
            throw new ValidationException("商户信息不存在");
        }
 
        if (StringUtils.isNotBlank(c.getPartnerId()) || StringUtils.isNotBlank(c.getPartnerUserId())) {
            throw new ValidationException("商户已绑定合伙人,请联系客服人员进行解绑后再进行绑定");
        }
        Partner partner;
        try {
            long id = Long.parseLong(dto.getPartnerUserId());
            partner = partnerMapper.selectById(id);
        } catch (Exception e) {
            partner =partnerMapper.selectOne(new QueryWrapper<Partner>().eq("user_id", dto.getPartnerUserId()));
        }
        if (partner == null) {
            throw new ValidationException("合伙人不存在");
        }
        if (!"P".equals(partner.getStatus())) {
            throw new ValidationException("合伙人信息未审核通过,请联系客服人员");
        }
 
        customerMapper.bindPartner(c.getId(), partner.getId(), partner.getUserId());
    }
 
    public String getPartnerName(String partnerUserId) {
        if (StringUtils.isNotBlank(partnerUserId)) {
            Partner partner;
            try {
                long id = Long.parseLong(partnerUserId);
                partner = partnerMapper.selectById(id);
            } catch (Exception e) {
                partner =partnerMapper.selectOne(new QueryWrapper<Partner>().eq("user_id", partnerUserId));
            }
            if (partner == null) {
                throw new ValidationException("合伙人不存在");
            }
            return partner.getName();
        }
        return null;
    }
    public void isEnable(Long id) {
        Customer customer = customerMapper.selectById(id);
        if (customer == null) {
            throw new ValidationException("商户信息不存在");
        }
        if (customer.getIsEnabled()) {
            customer.setIsEnabled(false);
            //强制下线
            baseService.removeToken(customer.getUserId());
        } else {
            customer.setIsEnabled(true);
        }
        customer.update(SecurityUtils.getUserId());
        customerMapper.updateById(customer);
    }
 
    /**
     * 根据会员等级获取等级下的customer信息
     * @param levelId
     * @return
     */
    public List<Customer> getCustomerListByLevelId(Integer levelId){
        if(null != levelId){
            QueryWrapper<Customer> customerQueryWrapper=new QueryWrapper<>();
            customerQueryWrapper.lambda()
                    .eq(Customer::getDeleted, TrueOrFalseEnum.FALSE.isFlag())
                    .eq(Customer::getLevelId,levelId);
            return customerMapper.selectList(customerQueryWrapper);
        }
        return null;
    }
 
    public CustomerDTO findCustomerByPhone(String phone) {
        CustomerDTO customerByPhone = customerMapper.findCustomerByPhone(phone);
        if (customerByPhone != null && customerByPhone.getMemberOvertime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            customerByPhone.setMemberOverDate(customerByPhone.getMemberOvertime().format(formatter));
        }
        customerByPhone.setContactTel(phone);
        return customerByPhone;
    }
    public Customer getByUserId(String userId) {
        List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>().eq(Customer::getUserId, userId).eq(Customer::getDeleted, TrueOrFalseEnum.FALSE.isFlag()));
        if(!CollectionUtils.isEmpty(customers)){
            return customers.get(0);
        }
        return null;
    }
 
    public void updateMemberInfo(Customer customer) {
        customerMapper.updateById(customer);
    }
 
    public void checkVipExpireTime() {
        // 获取当天日期之前,且is_member=1的用户,设置为is_member=0并且将member_overtime设置为null
        customerMapper.checkVipExpireTime();
    }
 
    //生成邀请码
    private String generateCode() {
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return sb.toString();
    }
}