
import traceback
from BaseDataMaintenance.model.oracle.BaseModel import BaseModel
from datetime import datetime
from BaseDataMaintenance.common.Utils import getCurrent_date,log

dict_oracle2ots = {"WEB_SOURCE_NO":"web_source_no",
                    "AREA":"area",
                    "PROVINCE":"province",
                    "CITY":"city",
                    "WEB_SOURCE_NAME":"web_source_name",
                    "INFO_SOURCE":"info_source",
                    "INFO_TYPE":"info_type",
                    "INDUSTRY":"industry",
                    "ID":"uuid",
                    "PAGE_TITLE":"doctitle",
                    "PAGE_TIME":"page_time",
                    "PAGE_CONTENT":"dochtmlcon",
                    "ATTACHMENT_PATH":"page_attachments",
                    "CREATE_TIME":"crtime",
                    "DISTRICT":"district",
                    "DETAIL_LINK":"detail_link",
                   "docchannel":"docchannel"}

dict_channel_table = {"114":"bxkc.T_CAI_GOU_YI_XIANG_TEMP",
                      "117":"bxkc.T_CHAN_QUAN_JIAO_YI_TEMP",
                      "51":"bxkc.T_GONG_GAO_BIAN_GENG_TEMP",
                      "106":"bxkc.T_KONG_ZHI_JIA_TEMP",
                      "115":"bxkc.T_PAI_MAI_CHU_RANG_TEMP",
                      "116":"bxkc.T_TU_DI_KUANG_CHAN_TEMP",
                      "103":"bxkc.T_ZHAO_BIAO_DA_YI_TEMP",
                      "52":"bxkc.T_ZHAO_BIAO_GONG_GAO_TEMP",
                      "104":"bxkc.T_ZHAO_BIAO_WEN_JIAN_TEMP",
                      "102":"bxkc.T_ZHAO_BIAO_YU_GAO_TEMP",
                      "101":"bxkc.T_ZHONG_BIAO_XIN_XI_TEMP",
                      "105":"bxkc.T_ZI_SHEN_JIE_GUO_TEMP"}

class GongGaoTemp(BaseModel):

    def __init__(self,_dict):
        self.all_columns = []
        for k,v in _dict.items():
            self.setValue(k,v,True)

    def getPrimary_keys(self):
        raise NotImplementedError()

    def getProperties(self):
        return self.__dict__

    def getProperties_ots(self):
        new_dict = {}
        for k,v in self.__dict__.items():
            if k in dict_oracle2ots:
                n_k = dict_oracle2ots[k]
                if v is not None:
                    if isinstance(v,(str,int,float)):
                        pass
                    elif isinstance(v,(datetime)):
                        v = v.strftime("%Y-%m-%d %H:%M:%S")
                    else:
                        v = str(v)
                    new_dict[n_k] = v
        opertime = getCurrent_date(format="%Y-%m-%d %H:%M:%S")
        publishtime = "%s %s"%(new_dict.get("page_time",""),opertime.split(" ")[1])
        new_dict["opertime"] = opertime
        new_dict["publishtime"] = publishtime
        if "docchannel" in new_dict:
            new_dict["original_docchannel"] = new_dict["docchannel"]
        return new_dict

    def setValue(self,k,v,isColumn=False):
        if "all_columns" not in self.__dict__:
            self.all_columns = []
        self.__dict__[k] = v
        if isColumn:
            if k not in (set(self.all_columns)):
                self.all_columns.append(k)

    def delete_row(self,conn):
        try:
            cursor = conn.cursor()
            sql = "delete %s  "%(self.table_name)
            s_where = " where 1=1 "
            _set_keys = set(self.getPrimary_keys())
            has_key = False
            if len(_set_keys)==0:
                return
            for k,v in self.__dict__.items():
                if k in _set_keys:
                    if v is None or str(v)=="":
                        raise RuntimeError("主键%s为空"%k)
                    s_where += " and %s="%k
                    if isinstance(v,str):
                        s_where += "'%s' "%v
                    else:
                        s_where += "%d "%v
                    has_key = True
            log("delete sql:%s-%s %s"%(str(has_key),sql,s_where))
            if has_key:
                sql = "%s %s"%(sql,s_where)
                update_rows = cursor.execute(sql)
                conn.commit()
                return update_rows
        except Exception as e:
            traceback.print_exc()
        return 0

    def insert_row(self,conn):
        try:
            cursor = conn.cursor()
            sql = "insert into %s"%(self.table_name)
            s_columns = "("
            s_values = "values("
            _set_columns = set(self.all_columns)
            for k,v in self.__dict__.items():
                if k in _set_columns:
                    if v is not None and str(v)!="":
                        s_columns += "%s,"%k
                        if isinstance(v,str):
                            s_values += "'%s',"%v
                        else:
                            s_values += "%d,"%v
            s_columns = "%s)"%s_columns[:-1]
            s_values = "%s)"%s_values[:-1]
            sql = "%s%s%s"%(sql,s_columns,s_values)
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            traceback.print_exc()


    def update_row(self,conn,conditions=[]):
        cursor = conn.cursor()
        sql = "update %s set "%(self.table_name)
        s_columns = ""
        s_where = " where 1=1 "
        _set_columns = set(self.all_columns)
        _set_keys = set(self.getPrimary_keys())
        for k,v in self.__dict__.items():
            if k in _set_columns and k not in _set_keys:
                if v is not None and str(v)!="":
                    s_columns += "%s="%k
                    if isinstance(v,str):
                        s_columns += "'%s',"%v
                    else:
                        s_columns += "%d,"%v
            elif k in _set_keys:
                if v is None or str(v)=="":
                    raise RuntimeError("主键%s为空"%k)
                s_where += " and %s="%k
                if isinstance(v,str):
                    s_where += "'%s' "%v
                else:
                    s_where += "%d "%v
        s_columns = "%s"%s_columns[:-1]
        sql = "%s%s%s"%(sql,s_columns,s_where)
        update_rows = cursor.execute(sql)
        conn.commit()
        return update_rows



    def exists(self,conn):
        s_where = " where 1=1 "
        _set_columns = set(self.all_columns)
        _set_keys = set(self.getPrimary_keys())
        for k,v in self.__dict__.items():
            if k in _set_keys:
                if v is None or str(v)=="":
                    raise RuntimeError("主键%s为空"%k)
                s_where += " and %s="%k
                if isinstance(v,str):
                    s_where += "'%s' "%v
                else:
                    s_where += "%d "%v
        cursor = conn.cursor()
        sql = "select count(1) from %s %s"%(self.table_name,s_where)
        cursor.execute(sql)
        rows = cursor.fetchall()
        if rows[0][0]==0:
            return False
        return True

    @staticmethod
    def select_rows(conn,cls,table_name,conditions,rows_to_get="*",limit=None):
        list_result = []
        s_limit = ""
        if limit is not None:
            s_limit = " where rownum<=%d"%limit
        if len(conditions)>0:
            s_where = " where %s"%(" and ".join(conditions))
        else:
            s_where = ""

        cursor = conn.cursor()
        sql = "select %s from %s %s %s"%(rows_to_get,table_name,s_where,s_limit)
        cursor.execute(sql)

        vol = cursor.description
        rows = cursor.fetchall()
        for row in rows:
            _dict = {}
            for _vol,_val in zip(vol,row):
                _name = _vol[0]
                _dict[_name] = _val
            list_result.append(cls(_dict))
        return list_result



