import xlwings as xw
import numpy as np
import pandas as pd
import os
import sys


def main():
    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    # if sheet["A1"].value == "Hello xlwings!":
    #     sheet["A1"].value = ["Bye xlwings!", "22"]
    # else:
    #     sheet["A1"].value = ["Hello xlwings!", "This 2"]
    try:
        sheet_db = wb.sheets["db"]
        # range = sheet_db.range("A1").options(expand='table').value
        # df = sheet_db.range("A1:D"+str(len(range))).options(pd.DataFrame).value
        df = sheet_db.range("A1").options(convert=pd.DataFrame, expand='table').value
        sheet.range("A1").value = df
    except:
        sheet.range("A1").value = "未找到db数据sheet"


@xw.func
def GDRH(机组类型, 负荷率):
    wb = xw.Book.caller()
    df = pd.DataFrame()
    try:
        sheet_db = wb.sheets["db"]
        range = sheet_db.range("A1").options(expand='table').value
        if len(range) < 1:
            return "db数据量为0"
        df = pd.DataFrame(columns=range[0], data=range[1:])
    except:
        return "未找到db数据sheet"
    from yangke.base import interpolate_value_complex
    df1 = df[df["机组类型"] == 机组类型]
    rate = list(df1["负荷率"])
    coal = list(df1["供电煤耗"])
    hr = list(df1["热耗"])
    res = interpolate_value_complex(负荷率, x_list=rate, y_list=hr)

    return res


@xw.func
def 供电热耗(机组类型, 负荷率):
    return GDRH(机组类型, 负荷率)


@xw.func
def xlwings_version():
    """returns the xlwings version"""
    return xw.__version__


@xw.func
def py_version_xw():
    """returns the python version"""
    return ".".join([str(x) for x in sys.version_info])


@xw.func
def win32api_is_installed():
    """returns True if win32api can be imported"""
    try:
        import win32api
        return True
    except ImportError:
        return False


if __name__ == "__main__":
    # xw.Book("myproject.xlsm").set_mock_caller()
    # main()
    xw.serve()
