import configparser
import datetime
import hashlib
import json
import time
import uuid
from urllib.parse import urlencode
import pandas as pd
import pymysql
import requests
from DBUtils.PooledDB import PooledDB
from apscheduler.schedulers.blocking import BlockingScheduler

import BaseCore

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()

# 接口信息
appkey = '84959d1d-6afa-4c57-9fea-b75d5599f761'
secretKey = '2aebca76-2def-4f8e-961a-436eeb0828fd'
timeStamp = int(time.time()) * 1000

import configparser
import datetime


class ToMysql():
    def __init__(self):
        self.now = datetime.datetime.now().strftime('%Y-%m-%d')
        self.config = configparser.ConfigParser()
        self.config.read('config.ini', encoding='utf-8')
        # 设置请求头信息
        self.headers = {
            'Auth-version': '2.0',  # 指定接口验证版本
            'appkey': appkey,
            'timestamp': str(timeStamp),
            'sign': self.md5Encode(appkey + str(timeStamp) + secretKey),
            'Connection': 'keep-alive'
        }

    def md5Encode(self, srcStr):
        '''计算字符串的md5值'''
        m = hashlib.md5()
        m.update(srcStr.encode('utf-8'))
        return m.hexdigest()

    def mysqlConnection(self):
        self.pool = PooledDB(
            creator=pymysql,
            maxconnections=5,
            mincached=2,
            maxcached=5,
            blocking=True,
            host=self.config.get('mysql', 'host'),
            port=3306,
            user=self.config.get('mysql', 'username'),
            password=self.config.get('mysql', 'password'),
            database=self.config.get('mysql', 'database'),
            charset='utf8mb4'
        )
        self.cnx = self.pool.connection()
        self.cursor = self.cnx.cursor()

    # 数据库断开连接
    def mysqlClose(self):
        self.cursor.close()
        self.cnx.close()
        self.pool.close()

    # 调用接口，获取数据
    def dataRequest(self, url, company):
        # 调用接口
        response = requests.get(url, headers=self.headers)
        dataJson = response.json()
        log.info(dataJson)
        if dataJson['status'] == '201':
            log.info(f'{company}===无结果')
            result = None
        elif dataJson['status'] == '207':
            log.error(f'{company}===查询错误')
            result = None
        elif dataJson['status'] == '208':
            log.error(f'{company}===参数名错误或参数为空')
            result = None
        elif dataJson['status'] == '216':
            log.error(f'{company}===调用次数超过账户额度限制')
            result = None
        elif dataJson['status'] == '102':
            log.error(f'{company}===账户余额不足')
            result = None
        elif dataJson['status'] != '200':
            log.error(f'{company}===出错状态码{dataJson["status"]}')
            result = None
        else:
            result = dataJson['data']
        return result

    def getOrgId(self, company):
        sql = f'select ORG_ID from organization_id where ORG_NAME = "{company}"'
        self.cursor.execute(sql)
        try:
            orgId = self.cursor.fetchone()[0]
            self.cnx.commit()
            return orgId
        except:
            orgId = str(uuid.uuid4())
            sqlInsert = f'insert into organization_id(ORG_ID,ORG_NAME) values (%s,%s)'
            self.cursor.execute(sqlInsert, (orgId, company))
            self.cnx.commit()
            return orgId

    # 工商照面  1.41
    def ORGANIZAION(self):
        errorNameList = []
        log.info('开始采集企业基本信息===接口1.41')
        baseUrl = 'https://api.qixin.com/APIService/enterprise/getBasicInfo'
        df = pd.read_excel('./监管企业名单_.xlsx', sheet_name='Sheet1')
        companyList = df['单位名称']
        for company in companyList:
            company = company.strip()
            sqlSelect = f"select * from organization_ where NAME='{company}' and CREATE_DATE='{self.now}'"
            self.cursor.execute(sqlSelect)
            self.cnx.commit()
            is_insert = self.cursor.fetchone()
            if is_insert:
                log.info(f'{company}===已入库')
                continue
            # 请求参数
            urlParams = {
                'keyword': company
            }
            # 构造url
            url = '{}?{}'.format(baseUrl, urlencode(urlParams))
            companyData = self.dataRequest(url, company)
            if not companyData:
                errorNameList.append(company)
                continue
            _id = self.getOrgId(company)
            url = f"https://www.qixin.com/company/{companyData['id']}"
            name = companyData['name']
            format_name = companyData['format_name']
            econKind = companyData['econKind']
            econKindCode = companyData['econKindCode']
            registCapi = companyData['registCapi']
            currency_unit = companyData['currency_unit']
            type_new = companyData['type_new']
            historyNames = companyData['historyNames']
            historyNames_ = ''
            for historyNames in historyNames:
                historyNames_ += f'{historyNames},'
            historyNames_ = historyNames_.rstrip(',')
            address = companyData['address']
            regNo = companyData['regNo']
            scope = companyData['scope']
            termStart = companyData['termStart']
            termEnd = companyData['termEnd']
            belongOrg = companyData['belongOrg']
            operName = companyData['operName']
            title = companyData['title']
            startDate = companyData['startDate']
            endDate = companyData['endDate']
            checkDate = companyData['checkDate']
            status = companyData['status']
            new_status = companyData['new_status']
            orgNo = companyData['orgNo']
            creditNo = companyData['creditNo']
            districtCode = companyData['districtCode']
            actualCapi = companyData['actualCapi']
            categoryNew = companyData['categoryNew']
            domain = companyData['domain']
            tags = companyData['tags']
            tags_ = ''
            for tag in tags:
                tags_ += f'{tag},'
            tags_ = tags_.rstrip(',')
            revoke_reason = companyData['revoke_reason']
            logout_reason = companyData['logout_reason']
            revoke_date = companyData['revoke_date']
            fenname = companyData['fenname']
            sql = 'insert into organization_(CREDIT_NO,NAME,ECON_KIND,REGIST_CAPI,ID,TAGS,BELONG_ORG,STATUS,TERM_START,FORMAT_NAME,HISTORY_NAMES,REVOKE_DATE,END_DATE,REG_NO,ECON_KIND_CODE,DOMAIN,CATEGORY_NEW,ADDRESS,ORG_NO,DISTRICT_CODE,START_DATE,SCOPE,NEW_STATUS,OPER_NAME,TITLE,CHECK_DATE,ACTUAL_CAPI,TERM_END,CURRENCY_UNIT,REVOKE_REASON,TYEP_NEW,LOGOUT_REASON,FENNAME,URL,CREATE_DATE) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) '
            try:
                self.cursor.execute(sql, (
                    creditNo, name, econKind, registCapi, _id, tags_, belongOrg, status, termStart, format_name, historyNames_,
                    revoke_date, endDate, regNo, econKindCode, domain, categoryNew, address, orgNo, districtCode, startDate,
                    scope,
                    new_status, operName, title, checkDate, actualCapi, termEnd, currency_unit, revoke_reason, type_new,
                    logout_reason, fenname, url, self.now))
                self.cnx.commit()
                log.info(f'{name}===入库成功')
            except:
                log.info(f'{name}==={company}===有重复')
        dfError = pd.DataFrame(errorNameList, columns=['单位名称'])
        dfError.to_excel('./查询失败名单.xlsx', index=False)


if __name__ == '__main__':
    toMysql = ToMysql()
    toMysql.mysqlConnection()
    toMysql.ORGANIZAION()
    toMysql.mysqlClose()
