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.dao.TraderSymbolMapper;
import com.copy.trade.entity.dto.Symbol;
import com.copy.trade.entity.po.TraderSymbol;
import com.copy.trade.enums.TraderEnum;
import com.copy.trade.service.IFollowService;
import com.copy.trade.service.ITraderSymbolService;
import com.copy.trade.util.DogeContractUtils;
import com.copy.trade.util.WebAssert;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 交易员带单合约 服务实现类
 * </p>
 *
 * @author wz
 * @since 2022-11-08
 */
@Service
public class TraderSymbolServiceImpl extends ServiceImpl<TraderSymbolMapper, TraderSymbol> implements ITraderSymbolService {

    @Value("${doge.host}")
    private String dogeHost;


    @Autowired
    private ITraderSymbolService traderSymbolServiceImpl;

    @Autowired
    private IFollowService followServiceImpl;

    @Override
    public List<TraderSymbol> listByTrader(Long traderId) {
        QueryWrapper<TraderSymbol> traderSymbolQueryWrapper = new QueryWrapper<>();
        traderSymbolQueryWrapper.eq("trader_id",traderId);
        return list(traderSymbolQueryWrapper);
    }

    @Override
    @Transactional
    public Boolean update(Long traderId, List<String> symbolList) {
    	
        //验证交易员下是否有跟随人员
        Integer followTotal = followServiceImpl.countByTrader(traderId);
        WebAssert.isTrue(followTotal == 0,"chk.trader.symbol.update.remove");
        //1.验证交易对是否合法
        List<Symbol> symbolListDB = DogeContractUtils.symbolList(dogeHost);
        WebAssert.isNotNull(symbolListDB, "chk.trader.symbol.query.fail");
        Map<String, Symbol> symbolHashMap = new HashMap<>();
        symbolListDB.forEach(symbol -> {
            symbolHashMap.put(symbol.getSymbol(),symbol);
        });
        Boolean deleteflag = true;
        if(deleteflag) {
        	Map<String, Object> map = new HashMap();
        	map.put("trader_id", traderId);
        	removeByMap(map);
        	//删除只执行一次
        	deleteflag = false;
        }
        for (String symbolStr : symbolList) {
            Symbol symbol = symbolHashMap.get(symbolStr);
            if (symbol == null) {
                continue;
            }
            //删除原有的交易员带单合约
            
            try {
                TraderSymbol traderSymbol = new TraderSymbol();
                traderSymbol.setSymbol(symbolStr);
                traderSymbol.setTraderId(traderId);
                traderSymbol.setContractSymbolId(symbol.getId());
                traderSymbolServiceImpl.save(traderSymbol);
            } catch (Exception e) {
                Throwable cause = e.getCause();
                if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                    String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
                    //根据约束名称定位是那个字段 如果是交易hash违反唯一索引 说明该交易已经被同步过
                    if (StringUtil.isNotEmpty(errMsg) && errMsg.indexOf("trader_symbol_unique") == -1) {
                        continue;
                    }
                }
            }
        }
        return true;
    }

}
