import pymysql
import json
import os

result_json_path = r'E:/yuxin/nuofang-data/weapon/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('weapon_name')
            vals.append(base_info['装备名称'])
        if '分类' in base_info:
            cols.append('category')
            vals.append(base_info['分类'])
        if '类型' in base_info:
            cols.append('weapon_type')
            vals.append(base_info['类型'])
        if '制造商' in base_info:
            cols.append('manufacturer')
            vals.append(base_info['制造商'])
        if '其他名称' in base_info:
            cols.append('other_names')
            vals.append(base_info['其他名称'])
        if 'image_info' in json_body:
            cols.append('images')
            vals.append(json.dumps(json_body['image_info'], ensure_ascii=False))
        if 'janes_info' in json_body:
            cols.append('janes_info')
            vals.append(json.dumps(json_body['janes_info'], ensure_ascii=False).replace("'", "’"))
        if 'website_info' in json_body:
            cols.append('website_info')
            vals.append(json.dumps(json_body['website_info'], ensure_ascii=False).replace("'", "’"))
        SQL_INSERT = "INSERT INTO nfm.m_weapon_page ({}) VALUES ({})".format(
            ", ".join(cols), ", ".join(["'{}'".format(v) for v in vals]))
        cursor.execute(SQL_INSERT)
    db.commit()
    db.close()
