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])
    valuDate = str(sys.argv[2])
    bondCodelist = []
    for index in range(len(sys.argv)):
        if index > 2:
            bondCodelist.append(sys.argv[index])
    res = get_bond_var(bondSource,valuDate,bondCodelist)
    return res

# 确定返回的字段集  SWITCH方法
def get_bond_var(bondSource, valuDate, bondCodeList):
    # 获取当前日期 yyyy-MM-dd
    # tradeDateNow = datetime.now().strftime('%Y-%m-%d')
    if bondSource == "shch":  # shch估值
        return get_shch_val(bondCodeList, valuDate)
    elif bondSource == "cnbd":  # 中债估值
        return get_cnbd_val(bondCodeList, valuDate)
    elif bondSource == "csi1":  # 中证估值
        return get_csi1_val(bondCodeList, valuDate)
    elif bondSource == "cfets":  # CFETS估值
        return get_cfets_val(bondCodeList, valuDate)
    elif bondSource == "latest":  # 最新成交(CFETS)
        return get_latest_cfets_val(bondCodeList)
    elif bondSource == "bestbuy":  # 最优买(CFETS)
        return get_bestbuy_cfets_val(bondCodeList)
    elif bondSource == "bestsell":  # 最优卖(CFETS)
        return get_bestsell_cfets_val(bondCodeList)
    else:
        return None


# SHCH估值:YTM、净价、全价+债券估值日期8条
def get_shch_val(bondCodeList, valuDate):
    reList = [[] for i in range(len(bondCodeList))]
    for i in range(len(bondCodeList)):
        varList = w.wsd(bondCodeList[i], "net_shc,dirty_shc,yield_shc", "ED-7TD", valuDate,
                        "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCodeList[i], "net_shc,dirty_shc,yield_shc", "ED-7TD", valuDate,
                            "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(bondCodeList, valuDate):
    reList = [[] for i in range(len(bondCodeList))]
    for i in range(len(bondCodeList)):
        varList = w.wsd(bondCodeList[i], "net_cnbd,dirty_cnbd,yield_cnbd", "ED-7TD", valuDate,
                        "credibility=1;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCodeList[i], "net_cnbd,dirty_cnbd,yield_cnbd", "ED-7TD", valuDate,
                            "credibility=1;TradingCalendar=NIB;ShowBlank=-1").Times
        reList[i] = get_not1_result_var(varList, valDateList)
    return reList


# 中证估值: YTM、净价、全价 + 债券估值日期8条
def get_csi1_val(bondCodeList, valuDate):
    reList = [[] for i in range(len(bondCodeList))]
    for i in range(len(bondCodeList)):
        varList = w.wsd(bondCodeList[i], "net_csi1,dirty_csi1,yield_csi1", "ED-7TD", valuDate,
                        "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCodeList[i], "net_csi1,dirty_csi1,yield_csi1", "ED-7TD", valuDate,
                            "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Times
        reList[i] = get_not1_result_var(varList, valDateList)
    return reList


# CFETS估值: YTM、净价、全价 + 债券估值日期8条
def get_cfets_val(bondCodeList, valuDate):
    reList = [[] for i in range(len(bondCodeList))]
    for i in range(len(bondCodeList)):
        varList = w.wsd(bondCodeList[i], "net_cfets,dirty_cfets,yield_cfets", "ED-7TD", valuDate,
                        "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Data
        valDateList = w.wsd(bondCodeList[i], "net_cfets,dirty_cfets,yield_cfets", "ED-7TD", valuDate,
                            "credibility=1 ;TradingCalendar=NIB;ShowBlank=-1").Times
        reList[i] = get_not1_result_var(varList, valDateList)
    return reList


# 最新成交(CFETS):YTM+债券估值日期1条
def get_latest_cfets_val(bondCodeList):
    varList = w.wsq(bondCodeList, "rt_last_cp,rt_last_dp,rt_last_ytm,rt_date").Data
    # varList[0][3] = (str(varList[0][3])[0:8])
    for i in range(len(varList[3])):
        varList[3][i] = (str(varList[3][i])[0:8])
        # 统一转换为yyyy-mm-dd格式
        varList[3][i] = str(varList[3][i])[0:4] + "-" + str(varList[3][i])[4:6] + "-" + str(varList[3][i])[6:8]
    return varList


# 最优买(CFETS) YTM:YTM+债券估值日期1条
def get_bestbuy_cfets_val(bondCodeList):
    varList = w.wsq(bondCodeList, "rt_best_bid_ytm,rt_date").Data
    for i in range(len(varList[1])):
        varList[1][i] = (str(varList[1][i])[0:8])
        # 统一转换为yyyy-mm-dd格式
        varList[1][i] = str(varList[1][i])[0:4] + "-" + str(varList[1][i])[4:6] + "-" + str(varList[1][i])[6:8]
    return varList


# 最优卖(CFETS) YTM:YTM+债券估值日期1条
def get_bestsell_cfets_val(bondCodeList):
    varList = w.wsq(bondCodeList, "rt_best_ask_ytm,rt_date").Data
    for i in range(len(varList[1])):
        varList[1][i] = (str(varList[1][i])[0:8])
        # 统一转换为yyyy-mm-dd格式
        varList[1][i] = str(varList[1][i])[0:4] + "-" + str(varList[1][i])[4:6] + "-" + str(varList[1][i])[6:8]
    return varList


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


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


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