import pymysql
import os
import sys
from common.confop import confOP
from common.db.sql.sqlByIdb import sqlByIdb
import pymongo
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

class dbOP():
    def __init__(self, path=rootPath):
        self.path = path

    def selectSql(self, schema, param=[], db="bj_db"):
        host = mySql().getConf(db)[0]
        port = mySql().getConf(db)[1]
        user = mySql().getConf(db)[2]
        pwd = mySql().getConf(db)[3]
        value = confOP().getYamlValue("sql")
        if schema not in value:
            value = confOP().getBusiYamlValue(self.path, "sql")
        env = os.environ["ENV"]
        if env == "on" or env == "pre":
            database = value[schema][0]
            sql = value[schema][1]
            param = param
            result = sqlByIdb().selectSql(database, sql, param, env)
        else:
            result = mySql().selectSql(host, port, user, pwd, value[schema][0], value[schema][1], param)
        return result

    def ddlSql(self, schema, param=[], db="bj_db"):
        host = mySql().getConf(db)[0]
        port = mySql().getConf(db)[1]
        user = mySql().getConf(db)[2]
        pwd = mySql().getConf(db)[3]
        value = confOP().getYamlValue("sql")
        if schema not in value:
            value = confOP().getBusiYamlValue(self.path, "sql")
        result = mySql().executeUpdate(host, port, user, pwd, value[schema][0], value[schema][1], param)
        return result


class mySql:
    def __init__(self):
        pass

    def getConf(self, db="bj_db"):
        host = confOP().getConfValue(curPath + "/conf.ini", db, "host")
        port = confOP().getConfValue(curPath + "/conf.ini", db, "port", "int")
        user = confOP().getConfValue(curPath + "/conf.ini", db, "user")
        pwd = confOP().getConfValue(curPath + "/conf.ini", db, "password")
        return host,port,user,pwd

    def connection(self, host, port, user, pwd, database):
        return pymysql.connect(host=host, port=port,user=user,passwd=pwd,db=database)

    def selectSql(self, host, port, user, pwd, database, sql, param=[]):
        conn = self.connection(host, port, user, pwd, database)
        cursor = conn.cursor()
        try:
            cursor.execute(sql, param)
            data = cursor.fetchall()
            cols = cursor.description
            col = []
            for i in cols:
                col.append(i[0])
            data = list(map(list, data))
            return data
        except Exception as e:
            print(e)
            conn.rollback()
        cursor.close()
        conn.close()

    def executeUpdate(self, host, port, user, pwd, database, sql, param=[]):
        conn = self.connection(host, port, user, pwd, database)
        cursor = conn.cursor()
        try:
            ret = cursor.execute(sql, param)
            conn.commit()
            return ret
        except Exception as e:
            print(e)
            conn.rollback()
        cursor.close()
        conn.close()



class mongodb:
    def connection(self,db,collect):
        ip = confOP().getConfValue(curPath + "/conf.ini", "mongo", "ip")
        port = confOP().getConfValue(curPath + "/conf.ini", "mongo", "port")
        path = "mongodb://" + ip + ":" + port + "/"
        myclient = pymongo.MongoClient(path)
        mydb = myclient[db]
        mycol = mydb[collect]
        return mycol

    #查询所有的值
    def findALl(self, db, collect):
        result = []
        mycol = self.connection(db, collect)
        for x in mycol.find():
            result.append(x)
        return result

    #按照条件查询:条件为{}类型
    def findByCon(self, db, collect, condition):
        result = []
        mycol = self.connection(db, collect)
        for x in mycol.find(condition):
            result.append(x)
        return result





if __name__ == '__main__':
    env = 'sit'
    os.environ['ENV'] = env.lower()
    path = "D:\\myCode\\autotest-airtest-local\\data\\月嫂"
    #mysql的例子
    result = dbOP(path).selectSql("local_worker_info")
    print(result[0])
    #monggdb的例子
    #mongodb().findByCon("yapi","user", {"role": "admin"})
    #redis的例子
    #redisClass().connect()



