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

import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.AccCardHis;
import com.bonus.canteen.core.account.domain.AccInfo;
import com.bonus.canteen.core.account.mapper.AccCardHisMapper;
import com.bonus.canteen.core.account.mapper.AccInfoMapper;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.account.mapper.AccCardMapper;
import com.bonus.canteen.core.account.domain.AccCard;
import com.bonus.canteen.core.account.service.IAccCardService;
import org.springframework.util.CollectionUtils;

import static com.bonus.canteen.core.order.constants.OrderStateEnum.CANCEL;

/**
 * 人员卡片资料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 AccCard selectAccCardById(Long id) {
        return accCardMapper.selectAccCardById(id);
    }

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

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

    private void saveAccCardChangeRecord(AccCard accCard) {
        AccCardHis accCardHis = new AccCardHis();
        accCardHis.setCreateBy(SecurityUtils.getUsername());
        accCardHis.setCreateTime(DateUtils.getNowDate());
        accCardHis.setUserId(accCard.getUserId());
        accCardHis.setAccId(accCard.getAccId());
        accCardHis.setCardNum(String.valueOf(accCard.getCardNum()));
        accCardHis.setSerialNum(accCard.getSerialNum());
        accCardHis.setCardType(CardTypeEnum.IC_CARD.getKey());
        accCardHis.setRecordType(accCard.getOperationType());
        accCardHis.setCardFaceNum(accCard.getCardFaceNum());
        accCardHis.setRemark(accCard.getRemark());
        if (CardRecordTypeEnum.APPLY.getKey().equals(accCard.getOperationType())) {
            accCardHis.setDeposit(accCard.getDeposit());
            accCardHis.setProductCost(accCard.getProductCost());
        } else if (CardRecordTypeEnum.CHANGE.getKey().equals(accCard.getOperationType())) {
            accCardHis.setProductCost(accCard.getProductCost());
        }
        accCardHisMapper.insertAccCardHis(accCardHis);
    }

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

    /**
     * 修改人员卡片资料
     * 
     * @param accCard 人员卡片资料
     * @return 结果
     */
    @Override
    public int updateAccCard(AccCard accCard) {
        accCard.setUpdateBy(SecurityUtils.getUsername());
        accCard.setUpdateTime(DateUtils.getNowDate());
        try {
            // 发卡前校验是否卡号已存在, 卡号不能重复
            int cardCountByCardSerialNum= accCardMapper.selectAccCardCountByCardSerialNum(accCard.getSerialNum());
            if (cardCountByCardSerialNum > 0) {
                throw new ServiceException("卡号已存在, 卡号不能重复");
            }
            AccInfo accInfo = accInfoMapper.selectAccInfoById(accCard.getAccId());
            checkAccInfoAndStatus(accInfo);
            int count = accCardMapper.updateAccCard(accCard);
            accCard.setUserId(accInfo.getUserId());
            if (CardRecordTypeEnum.CHANGE.getKey().equals(accCard.getOperationType())) {
                accCard.setCardStatus(CardStatusEnum.NORMAL.getKey());
                saveAccCardChangeRecord(accCard);
            } else if (CardRecordTypeEnum.REFUND.getKey().equals(accCard.getOperationType())) {
                accCard.setCardStatus(CardStatusEnum.REFUND.getKey());
                saveAccCardChangeRecord(accCard);
            }
            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);
    }
}
