package link.at17.mid.tushare.data.models;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

import link.at17.mid.tushare.data.models.interfaces.ITsStockInfo;
import link.at17.mid.tushare.enums.ListStatus;
import link.at17.mid.tushare.enums.StockMarket;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain=true)
@TableName("stock_info")
public class StockInfo implements ITsStockInfo {

    private static final Pattern EM_CODE_PATTERN = Pattern.compile("^(0|1|90)\\.(.*?)$");
    private static final Pattern STANDARD_CODE_PATTERN = Pattern.compile("^(\\d{6})\\.(SZ|SH|BJ)$");
    
    private String name;
    @TableField(exist=false)
    private String nudeCode;
    private ListStatus listStatus;
    private String tsCode;
    private LocalDateTime listDate;
    private LocalDateTime delistDate;
    @TableField(exist=false)
    private StockMarket exchange;
    @TableField(exist=false)
    private String thsBelongings;
    
    public String getEMCode() {
        return exchange.getEMCode() + "." + nudeCode;
    }
    
    public StockInfo setTsCode(String tsCode) {
        this.tsCode = tsCode;
        setStockCode(tsCode);
        return this;
    }
    
    public String getStockCode() {
        return nudeCode + "." + exchange.getStandardCode();
    }
    
    public StockInfo setStockCode(String stockCode) {
        if (StringUtils.isEmpty(stockCode)) {
            return this;
        }
        Matcher m = EM_CODE_PATTERN.matcher(stockCode);
        if (m.matches()) {
            String sec = m.group(1);
            nudeCode = m.group(2);
            
            if ("1".equals(sec)) {
                exchange = StockMarket.SH;
            }
            else if ("0".equals(sec)) {
                exchange = StockMarket.SZ;
            }
            else if ("BJ".equals(sec)) {
                exchange = StockMarket.BJ;
            }
            else {
                exchange = StockMarket.BK;
            }
            return this;
        }
        m = STANDARD_CODE_PATTERN.matcher(stockCode);
        if (m.matches()) {
            String sec = m.group(2);
            nudeCode = m.group(1);
            
            switch (sec) {
            case "SH":
                exchange = StockMarket.SH;
                break;
            case "SZ":
                exchange = StockMarket.SZ;
                break;
            case "BJ":
            default:
                exchange = StockMarket.BJ;
                break;
            }
            return this;
        }
        return this;
    }
    
    /**
     * 是否主板
     * @return
     */
    public boolean isMainBoard() {
        return exchange != null && (exchange == StockMarket.SH || exchange == StockMarket.SZ);
    }
}
