# -*- coding: UTF-8 -*-
import os

import pandas as pd
from obs import ObsClient

from base import BaseCore

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask, request, jsonify
from gevent import pywsgi

app = Flask(__name__)


# 获取excel表格，解析内容送入redies
@app.route('/enterprise/readExcel', methods=['GET'])
def getExcel():
    baseCore = BaseCore.BaseCore()
    r = baseCore.r
    log = baseCore.getLogger()
    obsClient = ObsClient(
        access_key_id='VEHN7D0TJ9316H8AHCAV',  # 你的华为云的ak码
        secret_access_key='heR353lvSWVPNU8pe2QxDtd8GDsO5L6PGH5eUoQY',  # 你的华为云的sk
        server='https://obs.cn-north-1.myhuaweicloud.com'  # 你的桶的地址
    )
    filePath = request.args.get('filePath')
    data = getDF(filePath, obsClient)
    for i in range(data.shape[0]):
        data_ = ''
        for j in range(len(data.iloc[i])):
            if pd.isna(data.iloc[i][j]):
                data_ += f'|'
            else:
                data_ += f'{data.iloc[i][j]}|'
        if data.iloc[i]['国内外(1-国内;0-国外)'] == 1 or data.iloc[i]['国内外(1-国内;0-国外)'] == '1':
            r.rpush('BaseInfoEnterprise:gnqy_socialCode', data_)
        elif data.iloc[i]['国内外(1-国内;0-国外)'] == 0 or data.iloc[i]['国内外(1-国内;0-国外)'] == '0':
            r.rpush('BaseInfoEnterprise:gwqy_socialCode', data_)
    r.rpush('BaseInfoEnterprise:gnqy_socialCode', 'end')
    r.rpush('BaseInfoEnterprise:gwqy_socialCode', 'end')
    log.info('文件接收成功')
    obsClient.close()
    baseCore.close()
    return jsonify({'success': 'success'})


@app.route('/enterprise/getInfo', methods=['GET'])
def getInfo():
    baseCore = BaseCore.BaseCore()
    cursor = baseCore.cursor
    cnx = baseCore.cnx
    log = baseCore.getLogger()
    gpdm = request.args.get('securitiesCode')
    xydm = request.args.get('socialCode')
    name = request.args.get('name')
    ename = request.args.get('englishName')
    place = request.args.get('place')
    if not xydm and not place :
        baseCore.close()
        return jsonify({'error':'缺少参数'})
    if not name or not ename:
        baseCore.close()
        return jsonify({'error':'缺少参数'})
    sql = f"select * from EnterpriseInfo where SocialCode='{xydm}'"
    cursor.execute(sql)
    data = cursor.fetchone()
    if data:
        if str(place) == '1':
            if gpdm:
                sql_up = f"UPDATE EnterpriseInfo set SecuritiesCode='{gpdm}',CompanyName='{name}',Place={place} WHERE SocialCode='{xydm}'"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'更新企业信息==={xydm}')
            else:
                sql_up = f"UPDATE EnterpriseInfo set CompanyName='{name}',Place={place} WHERE SocialCode='{xydm}'"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'更新企业信息==={xydm}')
        elif str(place) == '0':
            if gpdm:
                sql_up = f"UPDATE EnterpriseInfo set SecuritiesCode='{gpdm}',CompanyName='{ename}',Place={place} WHERE SocialCode='{xydm}'"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'更新企业信息==={xydm}')
        else:
            log.error(f'{xydm}===国内外标志错误')
            baseCore.close()
            return jsonify({'error':f'{xydm}===国内外标志错误'})
    else:
        if str(place) == '1':
            if gpdm:
                sql_up = f"INSERT INTO EnterpriseInfo (SocialCode,SecuritiesCode,CompanyName,Place) VALUE ('{xydm}','{gpdm}','{name}','{place}')"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'新增企业信息==={xydm}')
            else:
                sql_up = f"INSERT INTO EnterpriseInfo (SocialCode,CompanyName,Place) VALUE ('{xydm}','{name}','{place}')"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'新增企业信息==={xydm}')
        elif str(place) == '0':
            if gpdm:
                sql_up = f"INSERT INTO EnterpriseInfo (SocialCode,SecuritiesCode,CompanyName,Place) VALUE ('{xydm}','{gpdm}','{ename}','{place}')"
                cursor.execute(sql_up)
                cnx.commit()
                log.info(f'新增企业信息==={xydm}')
        else:
            log.error(f'{xydm}===国内外标志错误')
            baseCore.close()
            return jsonify({'error':f'{xydm}===国内外标志错误'})
    baseCore.close()
    return jsonify({'success': 'success'})


def getDF(filePath, obsClient):
    response = obsClient.getObject('zzsn', filePath, loadStreamInMemory=True)
    df = pd.read_excel(response['body']['buffer'])
    return df


if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0',5000),app)
    server.serve_forever()
