#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import sys
import time
import json
import uuid
import random
import hashlib
import requests
import easygui as EG
from openpyxl import load_workbook

Brooks = 'Commercial Excellence Team - OA'
APP_KEY = '0f64c09da1c48b57'
api_url = 'https://openapi.youdao.com/api'
APP_SECRET = 'uM3mQZOlpKGLPORWhcMdT8nP864JmN7y'
Warning = '请确保表格为XLSX格式且数据位于Sheet1首行首列! API(√)-WEB(×)'
url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36'

def FanYi(xzhou):

    TM13 = str(round(time.time()*1000))
    TM14 = TM13 + str(random.randint(0, 9))
    sign = hashlib.md5(("fanyideskweb" + xzhou + TM14 + "Ygy_4c=r#e#4EX^NUGUc5").encode()).hexdigest()
    bv = hashlib.md5(ua.encode()).hexdigest()

    headers = {
        'user-agent': ua,
        'referer': 'https://fanyi.youdao.com/',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'cookie': 'OUTFOX_SEARCH_USER_ID=-184672967@10.110.96.154;JSESSIONID=aaa6fcXP7Bog_43iUlHcy; ___rl__test__cookies=' + TM13
    }

    data = {
        'i': xzhou,
        'from': 'zh-CHS',
        'to': 'en',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': TM14,
        'sign': sign,
        'lts': TM13,
        'bv': bv,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }

    res = requests.post(url, headers=headers, data=data)

    try:
        x = eval(res.text)['translateResult'][0][0]['tgt']
        return x
    except:
        return 'WEB'

def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()

def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]

def youdao(xzhou):

    TM10 = str(int(time.time()))
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(xzhou) + salt + TM10 + APP_SECRET
    sign = encrypt(signStr)
    
    data = {
        'q': xzhou,
        'from': 'zh-CHS',
        'to': 'en',
        'appKey': APP_KEY,
        'salt': salt,
        'sign': sign,
        'signType': 'v3',
        'curtime': TM10,
        'doctype': 'json',
        'version': '1.1',
    }
    res = requests.post(api_url, data=data).json()
    e = res['errorCode']
    if e == '0':
        x = res['translation'][0]
        return x
    else:
        return 'API'

if __name__ == "__main__":
    GO = EG.buttonbox(msg=Warning, title=Brooks, choices=("运行自动翻译助手", "关闭自动翻译助手"))
    if GO == '运行自动翻译助手':
        ExcelePath = EG.fileopenbox(title=Brooks, default='*.xlsx')
        if (ExcelePath != None):
            excel = load_workbook(ExcelePath)
            sheet = excel['Sheet1']
            max_row = sheet.max_row - 1
            for i in range(2, max_row+2):
                TIME = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                company = sheet.cell(row=i, column=1).value
                if company == None:
                    continue
                else:
                    company = company.strip()
                if company == '':
                    continue
                API = True
                if API:
                    FY = youdao(company)
                    LY = 'API'
                WEB = False
                if WEB:
                    FY = FanYi(company)
                    LY = 'WEB'
                if (FY == 'API'):
                    sheet['B'+str(i)] = '*'
                    sheet['C'+str(i)] = TIME
                    sheet['D'+str(i)] = ''
                    break
                if (FY == 'WEB'):
                    sheet['B'+str(i)] = '*'
                    sheet['C'+str(i)] = TIME
                    sheet['D'+str(i)] = ''
                    break
                else:
                    print(company + ' ≈ ' + FY + ' <' + LY + '> ' + str(i-1) + '/' + str(max_row))
                    sheet['B'+str(i)] = FY
                    sheet['C'+str(i)] = TIME
                    sheet['D'+str(i)] = LY
                    excel.save(ExcelePath)
            sheet['B1'] = '自动翻译'
            sheet['C1'] = '更新时间'
            sheet['D1'] = '获取来源'
            excel.save(ExcelePath)
            os.system("explorer.exe %s" % ExcelePath)
            sys.exit()
        else:
            sys.exit()
    else:
        while True:
            xzhou = EG.msgbox(msg='灵魂拷问:谁是世界上最帅的人???', title=Brooks, ok_button='周晓竞')
            if xzhou:
                sys.exit()
            else:
                continue
    
COURIER ● 豫ICP备2020027789号 ● XZHOU