<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);

class MachineTranslation {
    private $requestUrl = "https://itrans.xf-yun.com/v1/its";
    private $APPID = "4d8"; // 你的 APPID
    private $APISecret = "MzOD2"; // 你的 APISecret
    private $APIKey = "f9ee3e"; // 你的 APIKey
    private $RES_ID = "its_en_cn_word"; // 术语资源唯一标识
    private $FROM = "cn"; // 源语种
    private $TO = "en"; // 目标语种
    private $TEXT;

    public function translateText($text) {
        $this->TEXT = $text;
        return $this->main();
    }

    public function main() {
        $startTime = microtime(true);
        try {
            $resp = $this->doRequest();
            $respArray = json_decode($resp, true);
            $textBase64Decode = base64_decode($respArray['payload']['result']['text']);
            $textArray = json_decode($textBase64Decode, true);
            return $textArray['trans_result']['dst']; // 返回翻译后的文本
        } catch (Exception $e) {
            return "Error: " . $e->getMessage();
        }
    }

    private function doRequest() {
        $url = $this->buildRequetUrl();
        $params = $this->buildParam();

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new Exception("Curl error: " . curl_error($ch));
        }

        curl_close($ch);
        return $response;
    }

    private function buildRequetUrl() {
        $url = parse_url($this->requestUrl);
        $date = gmdate("D, d M Y H:i:s T");
        $host = $url['host'];

        $request_line = "POST " . $url['path'] . " HTTP/1.1";
        $string_to_sign = "host: $host\n" . "date: $date\n" . $request_line;

        $signature = base64_encode(hash_hmac('sha256', $string_to_sign, $this->APISecret, true));
        $authorization = sprintf('api_key="%s", algorithm="hmac-sha256", headers="host date request-line", signature="%s"', $this->APIKey, $signature);
        $authBase = base64_encode($authorization);

        return sprintf("%s?authorization=%s&host=%s&date=%s",
            $this->requestUrl,
            urlencode($authBase),
            urlencode($host),
            urlencode($date)
        );
    }

    private function buildParam() {
        $param = array(
            'header' => array(
                'app_id' => $this->APPID,
                'status' => 3,
                'res_id' => $this->RES_ID
            ),
            'parameter' => array(
                'its' => array(
                    'from' => $this->FROM,
                    'to' => $this->TO,
                    'result' => new stdClass() // 空对象
                )
            ),
            'payload' => array(
                'input_data' => array(
                    'encoding' => 'utf8',
                    'status' => 3,
                    'text' => base64_encode($this->TEXT)
                )
            )
        );

        return json_encode($param);
    }
}

// 处理标签内容的代码
if ($LabelArray['PageType'] == "Save") {
    // 新增翻译逻辑
    $translator = new MachineTranslation();

    // 翻译标题
    $translatedTitle = $translator->translateText($LabelArray['标题']);
    $LabelArray['标题'] =  $translatedTitle;

    // 翻译内容
    $maxLength = 10000;
    $content = $LabelArray['内容'];
    
    if (strlen($content) > $maxLength) {
    // 使用正则表达式分割内容，适应多种标点符号
        $segments = preg_split('/(?<=[。！？])/', $content, -1, PREG_SPLIT_NO_EMPTY);
        $translatedSegments = array();  // 使用 array() 替代 []
        $currentSegment = '';
    
        foreach ($segments as $segment) {
            // 如果当前段落加上新段落超过限制，则翻译当前段落
            if (strlen($currentSegment) + strlen($segment) > $maxLength) {
                $translatedSegments[] = $translator->translateText(trim($currentSegment));
                $currentSegment = $segment; // 开始新的段落
            } else {
                $currentSegment .= $segment; // 添加段落内容
            }
        }

    // 翻译最后一个段落
        $trimmedCurrentSegment = trim($currentSegment);
        if (!empty($trimmedCurrentSegment)) {
            $translatedSegments[] = $translator->translateText($trimmedCurrentSegment);
        }

        // 拼接翻译后的段落
        $LabelArray['内容'] = implode(' ', $translatedSegments);
    } else {
        // 内容小于等于10000字，直接翻译
        $LabelArray['内容'] = $translator->translateText($content);
    }

    // 记录时间
    $LabelArray['时间'] = date('Y-m-d H:i:s', time());
}

// 输出序列化的结果
echo serialize($LabelArray);