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

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.EPlaceDept;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.base.mapper.CuMemberMapper;
import com.hzs.member.base.param.DeleteDeadLockParam;
import com.hzs.member.base.service.DeleteDeadLockService;
import com.hzs.member.base.vo.DeleteDeadLockVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DeleteDeadLockServiceImpl extends ServiceImpl<CuMemberMapper, CuMember> implements DeleteDeadLockService {
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;

    @Override
    public List<DeleteDeadLockVO> queryDeleteDeadLockList(String memberCode) {
        List<DeleteDeadLockVO> deleteDeadLockVOList = baseMapper.queryDeleteDeadLockList(memberCode);
        deleteDeadLockVOList.forEach(deleteDeadLockVO -> {
            deleteDeadLockVO.setPlaceDept(EPlaceDept.getEPlaceDept(Integer.parseInt(deleteDeadLockVO.getPlaceDept())));
        });
        return deleteDeadLockVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteDeadLockMember(DeleteDeadLockParam deleteDeadLockParam) {
        if (deleteDeadLockParam.getMemberCode() == null) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        // 查询安置伞下和推荐伞下未删除会员数量,如果未删除会员数量为0返回true
        Integer isNoDeadNum = baseMapper.queryIsDeadMember(deleteDeadLockParam.getMemberCode());
        log.info("安置伞下和推荐伞下未删除会员数量:{}",isNoDeadNum);
        if(isNoDeadNum == 0){
            // 删除操作
            Long userId = SecurityUtils.getUserId();
            Date date=new Date();//此时date为当前的时间
            // 删除会员
            baseMapper.update(null,new LambdaUpdateWrapper<CuMember>()
                    .eq(CuMember::getMemberCode,deleteDeadLockParam.getMemberCode())
                    .set(CuMember::getPkModified,userId)
                    .set(CuMember::getModifiedTime,date)
                    .set(CuMember::getDelFlag, EDelFlag.DELETE.getValue()));
            // 删除会员账户
            iCuMemberAccountService.deleteCuMemberAccountByMemberCode(userId,date,deleteDeadLockParam.getMemberCode());
        } else {
            return MemberMsgConstants.NOT_DEAD_MEMBER;
        }
        return null;
    }
}
