package com.bonus.canteen.core.account.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.account.constants.AccStatusEnum;
import com.bonus.canteen.core.account.constants.CardRecordTypeEnum;
import com.bonus.canteen.core.account.constants.CardStatusEnum;
import com.bonus.canteen.core.account.constants.CardTypeEnum;
import com.bonus.canteen.core.account.domain.AccountCard;
import com.bonus.canteen.core.account.domain.AccCardHis;
import com.bonus.canteen.core.account.domain.AccountInfo;
import com.bonus.canteen.core.account.mapper.AccCardHisMapper;
import com.bonus.canteen.core.account.mapper.AccCardMapper;
import com.bonus.canteen.core.account.mapper.AccInfoMapper;
import com.bonus.canteen.core.account.service.IAccCardService;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 人员卡片资料Service业务层处理
 * 
 * @author xsheng
 * @date 2025-04-20
 */
@Service
public class AccCardServiceImpl implements IAccCardService {
    @Autowired
    private AccCardMapper accCardMapper;
    @Autowired
    private AccInfoMapper accInfoMapper;
    @Autowired
    private AccCardHisMapper accCardHisMapper;

    /**
     * 查询人员卡片资料
     * 
     * @param id 人员卡片资料主键
     * @return 人员卡片资料
     */
    @Override
    public AccountCard selectAccCardById(Long id) {
        return accCardMapper.selectAccCardById(id);
    }

    /**
     * 查询人员卡片资料列表
     * 
     * @param accountCard 人员卡片资料
     * @return 人员卡片资料
     */
    @Override
    public List<AccountCard> selectAccCardList(AccountCard accountCard) {
        return accCardMapper.selectAccCardList(accountCard);
    }

    /**
     * 新增人员卡片资料
     * 
     * @param accountCard 人员卡片资料
     * @return 结果
     */
    @Override
    public int insertAccCard(AccountCard accountCard) {
        accountCard.setCreateBy(SecurityUtils.getUsername());
        accountCard.setCreateTime(DateUtils.getNowDate());
        try {
            AccountInfo accountInfo = accInfoMapper.selectAccInfoById(accountCard.getAccountId());
            checkAccInfoAndStatus(accountInfo);
            accountCard.setUserId(accountInfo.getUserId());
            accountCard.setCardStatus(CardStatusEnum.NORMAL.getKey());
            accountCard.setCardType(CardTypeEnum.IC_CARD.getKey());
            // 发卡前校验是否此用户已有卡, 已退卡、已过期的可以再发放
            int cardCountByUserId= accCardMapper.selectAccCardCountByUserId(accountInfo.getUserId());
            if (cardCountByUserId > 0) {
                throw new ServiceException("此用户已有卡, 不能再次发放");
            }
            // 发卡前校验是否卡号已存在, 卡号不能重复
            int cardCountByCardSerialNum= accCardMapper.selectAccCardCountByCardSerialNum(accountCard.getSerialNum());
            if (cardCountByCardSerialNum > 0) {
                throw new ServiceException("卡号已存在, 卡号不能重复");
            }
            int count = accCardMapper.insertAccCard(accountCard);
            saveAccCardChangeRecord(accountCard);
            return count;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    private void saveAccCardChangeRecord(AccountCard accountCard) {
        AccCardHis accCardHis = new AccCardHis();
        accCardHis.setCreateBy(SecurityUtils.getUsername());
        accCardHis.setCreateTime(DateUtils.getNowDate());
        accCardHis.setUserId(accountCard.getUserId());
        accCardHis.setAccountId(accountCard.getAccountId());
        accCardHis.setSerialNum(accountCard.getSerialNum());
        accCardHis.setCardType(CardTypeEnum.IC_CARD.getKey());
        accCardHis.setRecordType(accountCard.getOperationType());
        accCardHis.setRemark(accountCard.getRemark());
        if (CardRecordTypeEnum.APPLY.getKey().equals(accountCard.getOperationType())) {
            accCardHis.setDeposit(accountCard.getDeposit());
            accCardHis.setProductCost(accountCard.getProductCost());
        } else if (CardRecordTypeEnum.CHANGE.getKey().equals(accountCard.getOperationType())) {
            accCardHis.setProductCost(accountCard.getProductCost());
        }
        accCardHisMapper.insertAccCardHis(accCardHis);
    }

    public void checkAccInfoAndStatus(AccountInfo accountInfoVO) {
        if (ObjectUtil.isNull(accountInfoVO)) {
            throw new ServiceException("账户不存在");
        } else if (AccStatusEnum.DEACTIVATE.getKey().equals(accountInfoVO.getAccountStatus())) {
            throw new ServiceException("账户已停用");
        }
    }

    /**
     * 修改人员卡片资料
     * 
     * @param accountCard 人员卡片资料
     * @return 结果
     */
    @Override
    public int updateAccCard(AccountCard accountCard) {
        accountCard.setUpdateBy(SecurityUtils.getUsername());
        accountCard.setUpdateTime(DateUtils.getNowDate());
        try {
            // 发卡前校验是否卡号已存在, 卡号不能重复
            int cardCountByCardSerialNum= accCardMapper.selectAccCardCountByCardSerialNum(accountCard.getSerialNum());
            if (cardCountByCardSerialNum > 0) {
                throw new ServiceException("卡号已存在, 卡号不能重复");
            }
            AccountInfo accountInfo = accInfoMapper.selectAccInfoById(accountCard.getAccountId());
            checkAccInfoAndStatus(accountInfo);
            int count = accCardMapper.updateAccCard(accountCard);
            accountCard.setUserId(accountInfo.getUserId());
            if (CardRecordTypeEnum.CHANGE.getKey().equals(accountCard.getOperationType())) {
                accountCard.setCardStatus(CardStatusEnum.NORMAL.getKey());
                saveAccCardChangeRecord(accountCard);
            } else if (CardRecordTypeEnum.REFUND.getKey().equals(accountCard.getOperationType())) {
                accountCard.setCardStatus(CardStatusEnum.REFUND.getKey());
                saveAccCardChangeRecord(accountCard);
            }
            return count;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 批量删除人员卡片资料
     * 
     * @param ids 需要删除的人员卡片资料主键
     * @return 结果
     */
    @Override
    public int deleteAccCardByIds(Long[] ids) {
        return accCardMapper.deleteAccCardByIds(ids);
    }

    /**
     * 删除人员卡片资料信息
     * 
     * @param id 人员卡片资料主键
     * @return 结果
     */
    @Override
    public int deleteAccCardById(Long id) {
        return accCardMapper.deleteAccCardById(id);
    }
}
