import math
import sys
import numpy as np
import pandas as pd
import re
from datetime import datetime

# Wind API
from WindPy import *


def get_wind_data():
    # 启动Wind
    w.start()
    bondSource = str(sys.argv[1])
    bondCode = str(sys.argv[2])
    dateList = []
    for index in range(len(sys.argv)):
        if index > 2:
            dateList.append(sys.argv[index])
    res = get_bond_var(bondSource,dateList,bondCode)
    return res

# 确定返回的字段集  SWITCH方法
def get_bond_var(bondSource, dateList, bondCode):
    # 获取当前日期 yyyy-MM-dd
    if bondSource == "shch":  # shch估值
        return get_shch_val(dateList, bondCode)
    elif bondSource == "cnbd":  # 中债估值
        return get_cnbd_val(dateList, bondCode)
    else:
        return None

# SHCH估值:YTM、净价、全价+债券估值日期8条
def get_shch_val(dateList, bondCode):
    reList = [[] for i in range(len(dateList))]
    for i in range(len(dateList)):
        varList = w.wsd(bondCode, "net_shc,dirty_shc,yield_shc", "ED-10TD", dateList[i],
                        "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCode, "net_shc,dirty_shc,yield_shc", "ED-10TD", dateList[i],
                            "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Times
        reList[i] = get_not1_result_var(varList, valDateList)
    # 得到8条数据，取从右往左3组非空最近的一条
    return reList


# 中债估值: YTM、净价、全价 + 债券估值日期8条  无值则取-1
def get_cnbd_val(dateList, bondCode):
    reList = [[] for i in range(len(dateList))]
    for i in range(len(dateList)):
        varList = w.wsd(bondCode, "net_cnbd,dirty_cnbd,yield_cnbd", "ED-10TD", dateList[i],
                        "credibility=1;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCode, "net_cnbd,dirty_cnbd,yield_cnbd", "ED-10TD", dateList[i],
                            "credibility=1;TradingCalendar=NIB;ShowBlank=-1").Times
        reList[i] = get_not1_result_var(varList, valDateList)
    return reList

def get_not1_result_var(var8List, valDateList):
    list = []
    iPos = 0
    # 如果第一个值都为-1，直接返回
    #if var8List[0][0] < 0 and var8List[1][0] < 0 and var8List[2][0] < 0:  # 不为-1的判断
    #    list.append(var8List[0][0])
    #    list.append(var8List[1][0])
    #    list.append(var8List[2][0])
    #    list.append(date_format(valDateList[iPos]))
    #    return list
    # 取到最后一个数字值的位置
    tmp_pos = len(var8List[0]) - 1
    while tmp_pos != 0:
        if var8List[0][tmp_pos] > 0 and var8List[1][tmp_pos] > 0 and var8List[2][tmp_pos] > 0:  # 不为-1的判断
            iPos = tmp_pos
            break
        tmp_pos = tmp_pos - 1
    # 因为数字值的位置都一样，所以遍历循环内的list后append
    for tmpList in var8List:
        list.append(tmpList[iPos])
    list.append(date_format(valDateList[iPos]))
    return list


def date_format(data):
    return data.strftime('%Y-%m-%d')


def deci_format(data):
    if data is None:
        return ''
    else:
        return '%.4f' % data


def is_none2(data):
    if data is None:
        return ''
    else:
        return data


def is_none(data):
    if data is None:
        return True
    else:
        return False

def get_last_ele(x):
    if x.last_valid_index() is None:  # 一行中全为NaN
        return pd.nan
    else:
        return x[x.last_valid_index()]

if __name__ == '__main__':
    result = get_wind_data()
    print(result)
