# -*- coding: utf-8 -*-
from wxbot import *
import os
import ConfigParser
import lhz_mysql
import MySQLdb
import sys
import lhzoss
import lhzhttp
import lhzasr
import thread
import lhzconf
import lhzutil
import requests
import lhzimg

class MyWXBot(WXBot):
    def makelove(self):
        print '中华人民共和国'.decode('utf-8').encode('gbk')

def main():
    bot = MyWXBot()
    # bot.DEBUG = True
    # bot.conf['qr'] = 'png'
    bot.continuelogin = True  # 李宏卓改的功能，使微信可持续登录
    bot.loop_proc = False #李宏卓改的功能，使不轮询数据
    bot.run()
    if bot.status == 'makelove':
        # from_user_id = '@@6b2a2f64ce7f0eb592e368b36ac33500847782b48cf055c2452bd13a42e9c78f'
        # sql = "select MsgType,contentdata from wechatdata where from_user_id='%s' group by MsgType" % (from_user_id)
        from_user_name = MySQLdb.escape_string(lhzconf.send_from_groupname)
        sql = "select wid,MsgType,contentdata,content2 from wechatdata where from_user_name='%s' and MsgType in (1,3,34,43) and wid>315 limit 999" % (from_user_name)
        # print sql.decode('utf-8').encode('gbk')
        results = lhz_mysql.query(sql)
        print ('共'+str(len(results))+'条').decode('utf-8').encode('gbk')
        uids = []
        for un in lhzconf.send_to_groupname:
            uid = bot.get_user_id(un)
            uids.append(uid)
        # print from_user_name.decode('utf-8').encode('gbk')
        # print to_user_name.decode('utf-8').encode('gbk')
        # print len(results)
        for row in results:
            wid = row[0]
            MsgType = row[1]
            contentdata = row[2]
            content2 = row[3]
            strtoprint = str(wid) + ' ' + str(MsgType) +' '+ contentdata+ ' ' + (' ' if content2 is None else content2)
            try:
                strtoprint = strtoprint.decode('utf-8')
                strtoprint = strtoprint.encode('gbk')
            except Exception as e:
                pass
            print strtoprint
            if MsgType in (1,43):#文字
                pass                
                for uid in uids:
                    bot.send_msg_by_uid(contentdata,uid)
            else:
                # r = bot.session.get(contentdata)
                r = requests.get(contentdata if content2 is None or MsgType!=3 else content2)
                data = r.content
                lastindexofsep = lhzutil.find_last(contentdata,'/')
                fn = contentdata[lastindexofsep+1:]
                fn = os.path.join(bot.temp_pwd, fn)
                with open(fn, 'wb') as f:
                    f.write(data)
                if MsgType == 3:#图片
                    pass
                    #压缩图片
                    if os.path.getsize(fn)>1000000:
                        lhzimg.JfzBlogImgThumb(fn, fn)
                        lastindex = lhzutil.find_last(fn, os.path.sep)
                        key = fn[lastindex+1:]
                        if '_thumb.' not in fn:
                            key = lhzutil.thumbFilePath(key)
                        content2 = lhzoss.upload(fn, key)
                        #更新数据库
                        sql = "update wechatdata set content2='%s' where wid=%d" % (content2, wid)
                        lhz_mysql.execute(sql)
                    for uid in uids:
                        bot.send_img_msg_by_uid(fn,uid)
                elif MsgType == 34:#语音
                    pass
                    for uid in uids:
                        bot.send_file_msg_by_uid(fn,uid)
                # elif MsgType == 43:#视频
                    # pass
                    # bot.send_file_msg_by_uid(fn,uid)
                os.remove(fn)
            time.sleep(9)
    else:
        print 'login failed'
if __name__ == '__main__':
    main()
