package com.copy.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.copy.trade.bean.RedisLock;
import com.copy.trade.constant.RedisKey;
import com.copy.trade.dao.CustomerFollowSymbolMapper;
import com.copy.trade.entity.po.CustomerFollowSymbol;
import com.copy.trade.entity.po.TraderSymbol;
import com.copy.trade.enums.FollowSymbolStatus;
import com.copy.trade.service.ICustomerFollowSymbolService;
import com.copy.trade.util.WebAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 用户跟随交易对 服务实现类
 * </p>
 *
 * @author wz
 * @since 2022-11-08
 */
@Service
public class CustomerFollowSymbolServiceImpl extends ServiceImpl<CustomerFollowSymbolMapper, CustomerFollowSymbol> implements ICustomerFollowSymbolService {

    @Autowired
    private RedisLock redisLock;

    @Override
    public List<CustomerFollowSymbol> listByTraderAndSymbol(Long traderId, String symbol) {
        QueryWrapper<CustomerFollowSymbol> customerFollowSymbolQueryWrapper = new QueryWrapper<>();
        customerFollowSymbolQueryWrapper.eq("trader_id",traderId)
                .eq("symbol",symbol)
                .eq("status", FollowSymbolStatus.ON.getStatus());
        return list(customerFollowSymbolQueryWrapper);
    }

    @Override
    public Boolean offFollowSymbol(Long customerId, Long traderId) {
        QueryWrapper<CustomerFollowSymbol> customerFollowSymbolQueryWrapper = new QueryWrapper<>();
        customerFollowSymbolQueryWrapper.eq("customer_id",customerId)
                .eq("trader_id",traderId)
                .eq("status",FollowSymbolStatus.ON.getStatus());
        List<CustomerFollowSymbol> list = list(customerFollowSymbolQueryWrapper);
        if(list.size() == 0){
            return true;
        }
        list.forEach(customerFollowSymbol -> {
            customerFollowSymbol.setStatus(FollowSymbolStatus.OFF.getStatus());
        });
        //获取锁
        boolean lock = redisLock.lock(RedisKey.LOCK_UNFOLLOW, traderId.toString(), 100);
        WebAssert.isTrue(lock,"5000");
        updateBatchById(list);
        redisLock.unlock(RedisKey.LOCK_UNFOLLOW, traderId.toString());
        return true;
    }

}
