import os
from urllib.parse import unquote

import redis
from flask import Flask, request, send_file, render_template, jsonify
import json
import pymysql
from pyquery import PyQuery as pq
from flask_cors import cross_origin



'''
手动捕获请求的接口数据，实现解析
使用fiddler将链接对应的页面数据信息发送到后台，后台对数据进行解析

'''

r = redis.Redis(host='127.0.0.1', port='6379', db=0)
def connMysql():
    # 创建MySQL连接
    conx = pymysql.connect(host='114.115.159.144',
                           user='caiji',
                           password='zzsn9988',
                           database='caiji')
    # 创建一个游标对象
    cursorM = conx.cursor()
    return conx,cursorM

def closeSql(conx,cursorM):
    # 关闭游标和连接
    cursorM.close()
    conx.close()

#将列表数据插入到表中 baidu_search_result
def itemInsertToTable(item):
    conx,cursorM=connMysql()
    zKeyNo=item['zKeyNo']
    yKeyNo=item['yKeyNo']
    try:
        select_sql=f'select * from qccholdmsg where yKeyNo="{yKeyNo}" and zKeyNo="{zKeyNo}" '
        cursorM.execute(select_sql)
        existing_record = cursorM.fetchone()
    except Exception as e:
        existing_record=''
    if existing_record:
        print(f'数据已存在！{zKeyNo}')
        return

    insert_param=(item['yKeyNo'],item['yCompanyName'],item['nameCount'],item['zKeyNo'],item['zName'],
          item['registCapi'],item['province'],item['industry'],item['shortStatus'],item['percentTotal'],item['startDateStr'],
          item['h5Url'],item['district'],item['industryDesc'],item['area'],item['industryItem'])
    insert_sql ="INSERT into qccholdmsg (yKeyNo,yCompanyName,nameCount,zKeyNo,zName,registCapi,province," \
         "industry,shortStatus,percentTotal,startDateStr,h5Url,district,industryDesc,area,industryItem) VALUES (%s, %s,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    cursorM.execute(insert_sql,insert_param)
    # 定义插入数据的SQL语句
    # 执行插入操作
    conx.commit()
    print('数据插入成功！')
    closeSql(conx,cursorM)


app = Flask(__name__)

@app.route('/')
@cross_origin()
def index():
    return 'Welcome to the website!'

@app.route('/get_hold', methods=['POST'])
@cross_origin()
def get_news():
    data=request.form

@app.route('/ws/setCookie', methods=['GET','POST'])
# @cross_origin()
def setCookie():
    try:
        # cookie = request.args.get('cookie')
        wscookie = request.form.get('cookie')
        wscookie = unquote(wscookie)
        r.sadd('wscookie',wscookie)
    except Exception as e:
        print('error')
    return 'succes'

@app.route('/ws/getCookieSize', methods=['GET'])
@cross_origin()
def getCookieSize():
    try:
        size=r.scard('wscookie')
        data = {
            "code": 200,
            "msg": "操作成功",
            "data": size
        }
    except Exception as e:
        data={
            "code": 200,
            "msg": "操作失败",
            "data": 0
        }
    return jsonify(data)

@app.route('/ws/getHtml', methods=['POST'])
# @cross_origin()
def getnewMonth():
    try:
        html = request.form.get('html')
        doc=pq(html)
        wsmsg=doc('select[id="endMonth"]>option[selected="selected"]').text()
        r.set('wsmsg',wsmsg)
    except Exception as e:
        print('error')
    return 'success'

if __name__ == '__main__':
    app.run(port=8033)


