from urllib.request import Request, urlopen
import json
import fn
import tdx
import sys
import re
import sqllite_zxg as stock_zxg
import sqllite_gn as stock_gn
import gn

# 实例化 通达信 行业类
tdx_hy = tdx.hy()


class Zxg():
    gn_Sbider = ''

    def __init__(self, param):  # 构造函数带参数

        self.gn_Sbider = gn.Spider()

        #生成概念
        self.gn_Sbider.get_code_from_gn()

        if param != 'n':
            self.add(param)

    def list(self):
        print (1)

    def add(self, stock_code):
        data = {}
        data['code'] = stock_code
        res = stock_zxg.save(data)

        if res == 1:

            self.gn_Sbider.gn_op(stock_code)

    def go(self):

        lists = stock_zxg.list()
        # fn.pt(lists)

        # 获取in的数据id
        code_rows = []
        for row in lists:
            code_rows.append("'" + row['code'] + "'")
        code_ids = ','.join(code_rows)  # '000537','002089'

        # 获取概念列表
        gn_rows = stock_gn.find_all(code_ids)
        stock_key_value = {}
        for row in gn_rows:
            code = row.get('code')
            stock_key_value[code] = row['info']

        # 输出列表
        for row in lists:
            code = row['code']
            info = stock_key_value.get(code)
            hy = fn.fill(tdx_hy.get_hy(code), 8)
            stock_name = fn.fill(tdx_hy.get_hy(code,1), 8)
            lt = fn.fill(tdx_hy.get_hy(code,2), 8)
            print ("%s %s %s %s %s" % (code,stock_name, hy,lt,info))

# 举例
# zxg 000537 //添加自选股
# zxg  //查看

zxg = Zxg(sys.argv[1])
# zxg = Zxg('n')

# zxg = Zxg('000537')
zxg.go()
