import pymysql
import json
import os

result_json_path = r'E:/yuxin/nuofang-data/activity/result'

if __name__ == "__main__":
    db = pymysql.connect(host='39.101.194.63', port=23306,
                         user='root', passwd='passok123A', db='nfm', charset='utf8mb4')
    cursor = db.cursor()

    for file_name in os.listdir(result_json_path):
        cols = []
        vals = []
        cols.append('page_name')
        vals.append(file_name.replace(".json", ""))
        json_file = open('{}/{}'.format(result_json_path, file_name), 'r', encoding='utf-8')
        json_file_content = json_file.read()
        json_file.close()
        json_body = json.loads(json_file_content)
        base_info = json_body['base_info']
        if '内部编号' in base_info:
            cols.append('internal_id')
            vals.append(base_info['内部编号'])
        if '动态分类' in base_info:
            cols.append('act_category')
            vals.append(base_info['动态分类'])
        if '国家/地区' in base_info:
            cols.append('region')
            vals.append(base_info['国家/地区'])
        if '军种/部门' in base_info:
            cols.append('type_or_dept')
            vals.append(base_info['军种/部门'])
        if '更新日期' in base_info:
            cols.append('update_time')
            vals.append(base_info['更新日期'])
        if '日期' in base_info:
            cols.append('act_time')
            vals.append(base_info['日期'])
        if '信息来源' in base_info:
            cols.append('info_source')
            vals.append(base_info['信息来源'])
        if 'images' in json_body:
            cols.append('images')
            vals.append(json.dumps(json_body['images'], ensure_ascii=False))
        if 'videos' in json_body:
            cols.append('videos')
            vals.append(json.dumps(json_body['videos'], ensure_ascii=False))
        if 'info_source_url' in json_body:
            cols.append('info_source_url')
            vals.append(json.dumps(json_body['info_source_url'], ensure_ascii=False))
        if 'main_content' in json_body:
            cols.append('main_content')
            vals.append(json_body['main_content'])
        SQL_INSERT = "INSERT INTO nfm.m_act ({}) VALUES ({})".format(
            ", ".join(cols), ", ".join(["'{}'".format(v) for v in vals]))
        cursor.execute(SQL_INSERT)
    db.commit()
    db.close()
