from numpy import empty
import pandas as pd
from pandas.core.frame import DataFrame

import requests
import json
import datetime,time
import numpy as np



def getFeiShuDATA():
    print('飞书数据获取中......')
    Columns=["状态", "发生时间","代理商","电池编码","用户信息","业务分类A","业务分类B","操作","信息来源", "内容描述", "客服处理时间","客服处理结果","记录人","当前处理人","处理部门","跟进记录","问题类型A","问题类型B","事件处理完结时间","运维紧急程度","维修信息","返厂时间"]
    # 获取token

    app_id = 'cli_a1e503bb3d78100c'
    app_secret = 'oZBbGSRYsf9sXy8t8e8kbhVLciekyvMt'
    url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'

    headers = {'Content-Type':"application/json; charset=utf-8"}
    datas = json.dumps({'app_id':app_id, 'app_secret':app_secret})
    response = requests.post(url, data=datas, headers=headers)
    auth_token = json.loads(response.text)['tenant_access_token']

    # 获取数据
    app_token = 'bascnpaW50pJsCNd1AyIRFIc24b'
    table_id = 'tblo3wnR2HFWI6rA'
    sheet_id = 'vewZh94xDC'
    url = 'https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records'.format(app_token, table_id)
    headers = {"Authorization":"Bearer {}".format(auth_token)}


    df_file = pd.DataFrame(columns=Columns)
    timesort=['发生时间','客服处理时间','事件处理完结时间','返厂时间']
    count=0
    GotPageToken=str()

    while True:
        # 筛选条件加载这里
        datas = {'view_id':sheet_id, 'page_size':100, 'text_field_as_array':"true", 'page_token':GotPageToken,'field_names':'["状态", "发生时间","代理商","电池编码","用户信息","业务分类A","业务分类B","操作","信息来源", "内容描述", "客服处理时间","客服处理结果","记录人","当前处理人","处理部门","跟进记录","问题类型A","问题类型B","事件处理完结时间","运维紧急程度","维修信息","返厂时间"]'}
        try:
            response = requests.get(url, params=datas, headers=headers)
            #print(response.text)
            results = json.loads(response.text)['data']['items']
            GotPageToken=json.loads(response.text)['data']['page_token']

            for r in results:
                df_file = df_file.append([r['fields']], ignore_index=True)
        except:
            break

    for i in range(0,len(df_file)):
        for t in range(0,len(timesort)):
            if not df_file.loc[i,timesort[t]] is np.nan and not df_file.loc[i,timesort[t]] is None:
                timeTemp= float(df_file.loc[i,timesort[t]])
                timeTTmp=time.localtime(timeTemp/1000) 
                df_file.loc[i,timesort[t]] = time.strftime('%Y-%m-%d %H:%M:%S',timeTTmp)
    for col in Columns:
        df_file[col]=df_file[col].map(lambda x:str(x).lstrip('[{\'text\': ').rstrip('\', \'type\': \'text\'}]').replace('\\n\', \'type\': \'text\'}, {\'text\': \'',' '))
    df_file.to_excel('df_file.xlsx')
    print('飞书数据获取完成')
    return df_file