package cn.pluss.platform.merchant.impl;

import cn.pluss.platform.entity.MerchantCashPayCode;
import cn.pluss.platform.entity.MerchantCashPlaceStaff;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantCashPayCodeMapper;
import cn.pluss.platform.merchant.MerchantCashPayCodeService;
import cn.pluss.platform.merchant.MerchantCashPlaceStaffService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 收银点和码牌关联记录表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2021-03-24
 */
@Service
public class MerchantCashPayCodeServiceImpl extends ServiceImpl<MerchantCashPayCodeMapper, MerchantCashPayCode> implements MerchantCashPayCodeService {

    @Autowired
    private MerchantCashPlaceStaffService mcpsService;

    @Override
    public MerchantCashPayCode getByPayCode(String payCode) {
        MerchantCashPayCode cashPayCode = new MerchantCashPayCode();
        cashPayCode.setPayCode(payCode);
        return getOne(new QueryWrapper<>(cashPayCode));
    }

    @Override
    public void bindPayCode(MerchantCashPayCode merchantCashPayCode) {
        MerchantCashPayCode existData = new MerchantCashPayCode();
        existData.setCashPlaceId(merchantCashPayCode.getCashPlaceId());
        existData = getOne(new QueryWrapper<>(existData));

        if (existData != null) {
            throw new MsgException("请先解绑已有收款码");
        }

        save(merchantCashPayCode);
    }

    @Override
    public List<MerchantCashPayCode> getByCashPlaceIdList(List<Integer> cashPlaceIdList) {
        QueryWrapper<MerchantCashPayCode> qWrapper = new QueryWrapper<>();
        qWrapper.in("cashPlaceId", cashPlaceIdList);
        return list(qWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindPayCode(String payCode) {
        QueryWrapper<MerchantCashPayCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("payCode", payCode);

        MerchantCashPayCode connectInfo = new MerchantCashPayCode();
        remove(queryWrapper);

        LambdaUpdateWrapper<MerchantCashPlaceStaff> uWrapper = Wrappers.lambdaUpdate();
        uWrapper.eq(MerchantCashPlaceStaff::getCashPlaceId, connectInfo.getCashPlaceId())
                .set(MerchantCashPlaceStaff::getStatus, MerchantCashPlaceStaff.STATUS_LEAVE)
                .set(MerchantCashPlaceStaff::getRemark, "码牌被解绑，强制下卡");
        mcpsService.update(uWrapper);
    }
}
