package com.hzs.member.empty.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.MemberFieldConstants;
import com.hzs.common.core.enums.EOrderPrefix;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.domain.member.empty.CuMemberEmptyCode;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.empty.mapper.CuMemberEmptyCodeMapper;
import com.hzs.member.empty.service.ICuMemberEmptyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员空单编号 服务实现类
 *
 * @author hzs
 * @since 2023-08-29
 */
@Service
public class CuMemberEmptyCodeServiceImpl extends ServiceImpl<CuMemberEmptyCodeMapper, CuMemberEmptyCode> implements ICuMemberEmptyCodeService {

    @Autowired
    private ICuMemberService iCuMemberService;

    @Override
    public List<String> createCodeBatch(Integer quantity, Integer pkCountry, Long userId) {
        // 批量生成会员编号
        List<String> memberCodeList = iCuMemberService.createUserCodeBatch(pkCountry, false, quantity);
        if (CollectionUtil.isEmpty(memberCodeList)) {
            throw new ServiceException("生成会员编号异常");
        }

        // 保存列表
        List<CuMemberEmptyCode> saveList = new ArrayList<>(quantity);

        for (String memberCode : memberCodeList) {
            CuMemberEmptyCode cuMemberEmptyCode = new CuMemberEmptyCode();
            cuMemberEmptyCode.setBatchCode(this.queryLastCode());
            cuMemberEmptyCode.setMemberCode(memberCode);
            cuMemberEmptyCode.setIsUsed(EYesNo.NO.getIntValue());
            cuMemberEmptyCode.setPkCountry(pkCountry);
            cuMemberEmptyCode.setPkCreator(userId);
            saveList.add(cuMemberEmptyCode);
        }
        baseMapper.insertBatch(saveList);

        return memberCodeList;
    }

    @Override
    public List<CuMemberEmptyCode> queryCuMemberEmptyCode(String memberCode) {
        QueryWrapper<CuMemberEmptyCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.MEMBER_CODE, memberCode);
        return baseMapper.selectList(queryWrapper);
    }

    private String queryLastCode() {
        String code = baseMapper.queryLastCode();
        if (null == code) {
            code = EOrderPrefix.HANDLE_BUSINESS.getValue() + "10000";
        } else {
            code = EOrderPrefix.HANDLE_BUSINESS.getValue() + (Integer.parseInt(code.replaceAll(EOrderPrefix.HANDLE_BUSINESS.getValue(), "")) + 1);
        }
        return code;
    }

}
