#!/usr/bin/python
# coding=utf-8
# 梦幻手游辅助-by 专业 20150215
from __future__ import division
import sys, os
import threading
import win32api, win32gui, win32con
import ImageGrab
import time, datetime, string
import autopy
import urllib2
import hashlib
import wx

salt = '******'
sign = '******'
ver = '1.0'
defPwd = '******'
threads = []
isStart = True


def startTh():
    global isStart
    for t in threads:
        t.setDaemon(True)
        t.start()


def endAllTh(param):
    global isStart
    isStart = False


def md5Val(src):
    myMd5 = hashlib.md5()
    myMd5.update(src)
    myMd5_Digest = myMd5.hexdigest()
    return myMd5_Digest


# 校验密码
def CheckPwd():
    if (valArr[5] != ver):
        win32api.MessageBox(0, u'不是最新版本,请更新')
        exit()

    mdVal = md5Val(serverArr[0]
    salt)
    if (mdVal[6:14] != serverArr[1]):
        win32api.MessageBox(0, u'操作失败,请重试')
        exit()

    if (valArr[3] == '1'):
        nTime = string.atof(valArr[2])  # 字符串转浮点
        nDate = time.strftime('%Y-%m-%d %H:00:00', time.localtime(nTime));
        nDate = datetime.datetime.strptime(nDate, "%Y-%m-%d %H:%M:%S")
        nDate = time.mktime(nDate.timetuple())

        limi = string.atoi(valArr[1])
        diff = int((nTime - nDate) / limi) * limi

        date1 = '%d' % (nDate
        diff)

        pwd1 = md5Val(md5Val(date1)
        valArr[0]
        sign)
        pwd1 = pwd1[4:12]

        date2 = '%d' % (nDate
        diff - limi)
        pwd2 = md5Val(sign)
        pwd2 = pwd2[4:12]
    else:
        pwd1 = md5Val(sign)
        pwd1 = pwd1[5:13];
        pwd2 = pwd1

    if (frame.doPwd.GetValue() == pwd1 or frame.doPwd.GetValue() == pwd2):
        return True
    else:
        win32api.MessageBox(0, u'口令错误')
        exit()


def initWin():
    if (hmw > 0):
        win32gui.SetWindowPos(hmw, win32con.HWND_TOPMOST, 0, 0, 640, 362, win32con.SWP_SHOWWINDOW)
        return True
    else:
        win32api.MessageBox(0, u'没有检测到最新的海马玩模拟器窗口')
        return False


def closeMhxy():
    mhName = u"梦幻手游辅助v"
    ver
    mhwin = win32gui.FindWindow(None, mhName)
    if (mhwin > 0):
        win32api.PostMessage(mhwin, win32con.WM_QUIT, 0, 0)


def closeWin():
    # autopy.mouse.smooth_move(1255, 8)#最大化
    autopy.mouse.smooth_move(610, 10)
    time.sleep(1)
    autopy.mouse.click()
    time.sleep(1)
    # autopy.mouse.smooth_move(580, 450)#最大化
    autopy.mouse.smooth_move(260, 245)
    time.sleep(1)
    autopy.mouse.click()
    return True


def closePC():
    autopy.mouse.smooth_move(27, 783)
    time.sleep(1)
    autopy.mouse.click()
    time.sleep(1)
    autopy.mouse.smooth_move(303, 740)
    time.sleep(1)
    autopy.mouse.click()
    return True


def oneKeyDo(param):
    win32api.MessageBox(0, u'待开发')
    return True


# 打图
def daTu():
    global isStart
    if (isStart == False):
        time.sleep(5)
    while isStart:
        if (frame.setRows.GetValue() == '1'):
            autopy.mouse.smooth_move(540, 125)
        elif (frame.setRows.GetValue() == '2'):
            autopy.mouse.smooth_move(540, 168)
        elif (frame.setRows.GetValue() == '3'):
            autopy.mouse.smooth_move(540, 214)
        else:
            win32api.MessageBox(0, u'行号超出范围')
            return False
        time.sleep(1)
        autopy.mouse.click()  # 单击   `
        time.sleep(3)
    isStart = True
    return True


# 抓鬼
def zhuaGui():
    global isStart
    if (isStart == False):
        time.sleep(20)
    width = 20
    height = 20
    t = 0
    while isStart:
        # box = (605, 435, 605 50, 435 50)
        box = (310, 215, 310
        width, 215
        height)
        img = ImageGrab.grab(box)
        cont = 0
        for h in range(0, height):
            for w in range(0, width):
                pix = img.getpixel((w, h))

                if ((abs(237 - pix[0]) <= 30) and (abs(224 - pix[1]) <= 30) and (abs(207 - pix[2]) <= 30)):
                    cont = cont
                    1
        del img
        if ((cont / (height * width)) > 0.6):
            t = 0
            # autopy.mouse.move(730, 460)
            autopy.mouse.smooth_move(372, 222)
            time.sleep(1)
            autopy.mouse.click()
            time.sleep(5)
            # autopy.mouse.toggle(True) # 按下左键
            # autopy.mouse.toggle(False) # 松开左键
            autopy.mouse.smooth_move(512, 222)

            time.sleep(1)
            autopy.mouse.click()
            time.sleep(1)
            # autopy.mouse.smooth_move(1090, 260)
            if (frame.setRows.GetValue() == '1'):
                autopy.mouse.smooth_move(550, 126)
            elif (frame.setRows.GetValue() == '2'):
                autopy.mouse.smooth_move(540, 170)
            else:
                win32api.MessageBox(0, u'行号超出范围')
                return False

            time.sleep(1)
            autopy.mouse.click()
            time.sleep(1)
            if (frame.setRows.GetValue() == '1'):
                autopy.mouse.smooth_move(550, 126)
            elif (frame.setRows.GetValue() == '2'):
                autopy.mouse.smooth_move(540, 170)
            else:
                win32api.MessageBox(0, u'行号超出范围')
                return False

            time.sleep(1)
            autopy.mouse.click()
            time.sleep(1)
        else:
            box = (500, 285, 544, 304)
            img = ImageGrab.grab(box)
            cont = 0
            for h in range(0, 19):
                for w in range(0, 44):
                    pix = img.getpixel((w, h))

                    if ((abs(240 - pix[0]) <= 30) and (abs(200 - pix[1]) <= 30) and (abs(100 - pix[2]) <= 30)):
                        cont = cont
                        1
            del img
            if (cont / 836 > 0.5):
                autopy.mouse.move(520, 295)
                autopy.mouse.click()
                time.sleep(1)
                autopy.mouse.click()
        t = t
        1

        if (t > 1000):
            break
        else:
            # autopy.mouse.move(1134, 146)#桌面空白
            # autopy.mouse.click()
            time.sleep(5)
    isStart = True
    return True
    # closeWin()
    # closePC()


# 打图线程
def daTuTh(param):
    allThs(param, daTu)


# 抓鬼线程
def zhuaGuiTh(param):
    allThs(param, zhuaGui)


# 线程管理
def allThs(param, someDo):
    endAllTh(param)
    if (CheckPwd() != True):
        return False
    # if(initWin() == False):
    #   return False
    # frame.OnIconfiy(param)#最小化
    t = threading.Thread(target=someDo)
    threads.append(t)
    startTh()


class TaskBarIcon(wx.TaskBarIcon):
    ID_About = wx.NewId()
    ID_Minshow = wx.NewId()
    ID_Maxshow = wx.NewId()
    ID_Closeshow = wx.NewId()

    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        self.SetIcon(wx.Icon(name='mhxy.ico', type=wx.BITMAP_TYPE_ICO), u'梦幻手游辅助工具')  # wx.ico为ico图标文件
        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarLeftDClick)  # 定义左键双击
        self.Bind(wx.EVT_MENU, self.OnAbout, id=self.ID_About)
        self.Bind(wx.EVT_MENU, self.OnMinshow, id=self.ID_Minshow)
        self.Bind(wx.EVT_MENU, self.OnMaxshow, id=self.ID_Maxshow)
        self.Bind(wx.EVT_MENU, self.OnCloseshow, id=self.ID_Closeshow)

    def OnTaskBarLeftDClick(self, event):
        if self.frame.IsIconized():
            self.frame.Iconize(False)
        if not self.frame.IsShown():
            self.frame.Show(True)
        self.frame.Raise()

    def OnAbout(self, event):
        wx.MessageBox(u'梦幻手游辅助工具v'
        ver
        u'-"梦幻"群内部使用', u'关于工具')

        def OnMinshow(self, event):
            self.frame.Iconize(True)

        def OnMaxshow(self, event):
            if self.frame.IsIconized():
                self.frame.Iconize(False)
            if not self.frame.IsShown():
                self.frame.Show(True)
            self.frame.Raise()
            # self.frame.Maximize(True) #最大化显示

        def OnCloseshow(self, event):
            self.frame.Close(True)

        # 右键菜单
        def CreatePopupMenu(self):
            menu = wx.Menu()
            # menu.Append(self.ID_Minshow, u'最小化')
            menu.Append(self.ID_Maxshow, u'显示窗口')
            menu.Append(self.ID_About, u'关于工具')
            menu.Append(self.ID_Closeshow, u'退出')
            return menu

    class Frame(wx.Frame):
        def __init__(self, parent=None, id=wx.ID_ANY, title=u"梦幻手游辅助v" ver, pos = None, size = (400,
                                                                                                300), style = wx.SYSTEM_MENU | wx.MINIMIZE_BOX | wx.CLOSE_BOX | wx.CAPTION

        ):
        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self.SetIcon(wx.Icon('mhxy.ico', wx.BITMAP_TYPE_ICO))
        panel = wx.Panel(self, wx.ID_ANY)

        self.taskBarIcon = TaskBarIcon(self)

        # 绑定事件
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_ICONIZE,
                  self.OnIconfiy)  # 窗口最小化时，调用OnIconfiy,注意Wx窗体上的最小化按钮，触发的事件是 wx.EVT_ICONIZE,而根本就没有定义什么wx.EVT_MINIMIZE,但是最大化，有个wx.EVT_MAXIMIZE。

        self.tripText3 = wx.StaticText(panel, wx.ID_ANY, label=u'辅助的操作在任务栏第几行？:', pos=(0, 10))
        self.tripText3.SetFont(wx.Font(16, wx.SWISS, wx.NORMAL, wx.NORMAL))

        self.setRows = wx.TextCtrl(panel, wx.ID_ANY, pos=(290, 10), size=(90, 25))
        self.setRows.SetValue('1');

        self.tripText2 = wx.StaticText(panel, wx.ID_ANY, label=u'在点下任务之前,先确定此处的任务栏行正确与否', pos=(25, 30))

        self.oneKeyAutoDo = wx.Button(panel, wx.ID_ANY, label=u"一键自动任务", pos=(10, 60), size=(80, 25))
        self.autoZhuaGui = wx.Button(panel, wx.ID_ANY, label=u"自动带队抓鬼", pos=(95, 60), size=(80, 25))
        self.autoDaTu = wx.Button(panel, wx.ID_ANY, label=u"自动打图", pos=(180, 60), size=(80, 25))
        self.endDo = wx.Button(panel, wx.ID_ANY, label=u"停止操作", pos=(265, 60), size=(80, 25))

        self.Bind(wx.EVT_BUTTON, oneKeyDo, self.oneKeyAutoDo)
        self.Bind(wx.EVT_BUTTON, zhuaGuiTh, self.autoZhuaGui)
        self.Bind(wx.EVT_BUTTON, daTuTh, self.autoDaTu)
        self.Bind(wx.EVT_BUTTON, endAllTh, self.endDo)

        self.tripText1 = wx.StaticText(panel, wx.ID_ANY, label=u'请在此输入框内输入操作口令:', pos=(0, 160))
        self.tripText1.SetFont(wx.Font(16, wx.SWISS, wx.NORMAL, wx.NORMAL))

        self.doPwd = wx.TextCtrl(panel, wx.ID_ANY, pos=(290, 160), size=(90, 25))
        self.doPwd.SetValue(defPwd);

        if (valArr[3] == '1'):
            pwTrip = u'令牌模式'
        else:
            pwTrip = u'密码模式'

        self.tripText2 = wx.StaticText(panel, wx.ID_ANY, label=u'当前口令模式：'
        pwTrip
        u'——一般此处一般勿动', pos = (25, 180))

        self.tripText5 = wx.StaticText(panel, wx.ID_ANY,
                                       label=u'注:\n口令分为:密码模式和令牌模式\n密码模式:一般不用改,如果提示错误，群内公告有最新口令,\n令牌模式:每几分钟自动变换口令,需要群内吼一声',
                                       pos=(25, 200))

    def OnHide(self, event):
        self.Hide()

    def OnIconfiy(self, event):
        self.Hide()
        event.Skip()

    def OnClose(self, event):
        self.taskBarIcon.Destroy()
        self.Destroy()

    def OnCloseMe(self, event):
        self.SetBackgroundColour('Red')
        self.Refresh()


if __name__ == '__main__':
    closeMhxy()
    try:
        servetStr = urllib2.urlopen("http://www.baidu.com/").read()
    except:
        win32api.MessageBox(0, u'启动失败,请检查游戏网络')
        exit()

    # 校验通讯
    serverArr = servetStr.split(',')
    valArr = serverArr[0].split('|')

    # winName = u'海马玩模拟器(Droid4X) 0.7.3 Beta'
    winName = valArr[4].decode("UTF-8", 'ignore');
    hmw = win32gui.FindWindow(None, winName)

    app = wx.App()
    frame = Frame(size=(400, 300))
    frame.Centre()
    frame.Show()
    app.MainLoop()