<?php

namespace app\service;

use app\service\BaseService;
use app\AppCache;
use think\facade\Config;
use AlibabaCloud\SDK\Imageenhan\V20190930\Imageenhan;
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config as DaraConfig;
use AlibabaCloud\SDK\Imageenhan\V20190930\Models\ColorizeImageAdvanceRequest;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentCommonImageAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class ToolService extends BaseService
{

  private $access_key_id = 'LTAI5tE6gkXQqJBbCxFfo4hv';
  private $access_secret = 'pziJRQfXlev3vEIY4dHuB6C7E73Uv6';
  private $sign_name = '';
  private $imgClient = null;
  public function __construct() {
    parent::__construct('ToolService');
    $this->config = new DaraConfig([
      "accessKeyId" => $this->access_key_id,
      "accessKeySecret" => $this->access_secret,
    ]);
  }

  public function tongYongFenGe($imgUrl) {
    $this->config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
    $client = new Imageseg($this->config);
    $file = fopen($imgUrl, 'rb');
    $stream = new Stream($file);
    $segmentCommonImageAdvanceRequest = new SegmentCommonImageAdvanceRequest([
      "imageURLObject" => $stream,
      "returnForm" => "whiteBK"
    ]);
    $runtime = new RuntimeOptions([]);
    try {
      $resp = $client->segmentCommonImageAdvance($segmentCommonImageAdvanceRequest, $runtime);
      # 获取整体结果
      $json_str = Utils::toJSONString($resp->body);
      $json = c_safe_to_json($json_str);
      // return ['code'=>0,$json];
      $this->log_notice($json, '照片上色结果', 'tuPianShangSe');
      return $json['Data']['ImageURL'] ?? '';
    } catch (Exception $exception) {
      # 获取整体报错信息
      $this->log_error(Utils::toJSONString($exception), '照片上色失败', 'tuPianShangSe');
    }
    return '';
  }

  public function tuPianShangSe($imgUrl) {
    $this->config->endpoint = "imageenhan.cn-shanghai.aliyuncs.com";
    $client = new Imageenhan($this->config);
    $file = fopen($imgUrl, 'rb');
    //$stream = new Stream($file);
    // 场景二，使用任意可访问的url
    // $file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageenhan/ColorizeImage/ColorizeImage1.jpg', 'rb');
    $stream = new Stream($file);
    $colorizeImageAdvanceRequest = new ColorizeImageAdvanceRequest([
      "imageURLObject" => $stream
    ]);
    $runtime = new RuntimeOptions([]);
    try {
      $resp = $client->colorizeImageAdvance($colorizeImageAdvanceRequest, $runtime);
      # 获取整体结果
      $json_str = Utils::toJSONString($resp->body);
      $json = c_safe_to_json($json_str);
      // return ['code'=>0,$json];
      $this->log_notice($json, '照片上色结果', 'tuPianShangSe');
      return $json['Data']['ImageURL'] ?? '';
    } catch (Exception $exception) {
      # 获取整体报错信息
      $this->log_error(Utils::toJSONString($exception), '照片上色失败', 'tuPianShangSe');
    }
    return '';
  }

  // private function base($options_query): bool
  // {
  //   $is_prod = false;
  //   if (env('app.envName', 'prod') == 'prod') {
  //     $is_prod = true;
  //   }
  //   if (!$is_prod) {
  //     $this->log_notice($options_query, '', 'base');
  //     if (!isset($options_query['Test'])) {
  //       return true;
  //     }
  //   }
  //   $options_query['RegionId'] = 'cn-hangzhou';
  //   $options_query['SignName'] = $this->sign_name;
  //   try {
  //     $result = AlibabaCloud::rpc()
  //     ->product('Dysmsapi')
  //     // ->scheme('https') // https | http
  //     ->version('2017-05-25')
  //     ->action('SendSms')
  //     ->method('POST')
  //     ->host('dysmsapi.aliyuncs.com')
  //     ->options([
  //       'query' => $options_query
  //     ])
  //     ->request();
  //     $this->log_notice(['发送结果:' => $result->toArray(), "发送内容" => $options_query], '短信发送成功', 'base');
  //     return true;
  //   } catch (ClientException $e) {
  //     $this->log_error(['发送结果:' => $e->getErrorMessage(), "发送内容" => $options_query], '短信发送失败', 'base');
  //   } catch (ServerException $e) {
  //     $this->log_error(['发送结果:' => $e->getErrorMessage(), "发送内容" => $options_query], '短信发送失败', 'base');
  //   }
  //   return false;
  // }

  // public function sendTest() {
  //   return $this->base([
  //     'Test' => 'test',
  //     'TemplateCode' => "SMS_173476256",
  //     'PhoneNumbers' => '13873044202',
  //     'TemplateParam' => c_json_encode([
  //       'OrderNo' => '11111111111111',
  //       'CustomerName' => '测试',
  //       'ProductName' => c_max_len_3dot('裸心堡红宝石水疗送双人下午茶/每天限量抢购'),
  //       'ProductCount' => 2,
  //     ]),
  //   ]);
  // }

  // public function sendSMS($body_arr): bool
  // {
  //   return $this->base($body_arr);
  // }

  // public function sendBindPhoneVcode($user_id, $phone): string
  // {
  //   $vcode = random_vcode(6);
  //   $this->base([
  //     'TemplateCode' => "SMS_307600272",
  //     'PhoneNumbers' => $phone,
  //     'TemplateParam' => c_json_encode(['code' => $vcode]),
  //   ]);
  //   return $vcode;
  // }

  public function sendqywx($text, $phone) {
    $this->log_notice([$text, $phone], 'sendqywx', 'sendqywx');
    return curl_post_https(Config::get('app.order_qywx_webhook'),
      json_encode([
        'msgtype' => 'text',
        'text' => [
          'content' => $text,
          'mentioned_mobile_list' => [$phone],
        ],
      ]),
      ['header' => ['Content-Type:application/json']]);
  }
  public function sendqywx_test($text, $phone) {
    $this->log_notice([$text, $phone], 'sendqywx_test', 'sendqywx_test');
    return curl_post_https(Config::get('app.self_qxwx_alarm_webhook'),
      json_encode([
        'msgtype' => 'text',
        'text' => [
          'content' => $text,
          'mentioned_mobile_list' => [$phone],
        ],
      ]),
      ['header' => ['Content-Type:application/json']]);
  }


}