<?php

namespace App\Http\Controllers\Wechat\Material;

use App\Http\Requests;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Article;
use GuzzleHttp\Client;

/**
 * 素材类,包括图片,图文
 *
 */
class MaterialsController
{
    private $_errorMsg = [];

    public function __construct($_param)
    {
        $this->param = $_param;
        $this->app   = $_param['app'];
        // 永久素材
        $this->material = $this->app->material;
        // 临时素材
        $this->temporary = $this->app->material_temporary;
        // 客服消息
        $this->staff = $this->app->staff;
    }

    /**
     * 上传客服二维码永久素材
     */
    public function upload_contact_cusomer_img($group_nick, $path)
    {
        v('upload_contact_cusomer_img:' . $group_nick . ' path:' . $path);

        $result = $this->upload_materials($path);
        v('upload_contact_cusomer_img_result');
        v($result);
        return $result;
    }

    /**
     * 上传永久素材
     */
    public function upload_material_img($group_nick, $path)
    {
        v('upload_material_img:' . $group_nick . ' path:' . $path);

        $result = $this->upload_materials($path);
        v('upload_material_img_result');
        v($result);
        return $result;
    }

    /**
     * 上传永久缩略图素材
     */
    public function upload_thumb_material_img($group_nick, $path)
    {
        v('upload_thumb_material_img:' . $group_nick . ' path:' . $path);

        $result = $this->upload_thumb_materials($path);
        v('upload_thumb_material_img_result');
        v($result);
        return $result;
    }

    /**
     * 上传永久素材
     * 可能有网络问题,最多尝试3次
     */
    public function upload_materials($path, $try_time = 0)
    {
        v('upload_materials:path:' . $path . ' try_time:' . $try_time);
        $result = '';
        if ($try_time > 2) {
            return false;
        }

        try {
            return $this->material->uploadImage($path);
        } catch (\Exception $e) {
            $this->_errorMsg['upload_materials'] = $e->getMessage();
            v('upload_material_img_except:' . $e->getMessage());
            return $this->upload_materials($path, $try_time + 1);
        }

    }

    /**
     * 上传永久缩量图素材
     * 可能有网络问题,最多尝试3次
     */
    public function upload_thumb_materials($path, $try_time = 0)
    {
        v('upload_thumb_materials:path:' . $path . ' try_time:' . $try_time);
        $result = '';
        if ($try_time > 2) {
            return false;
        }

        try {
            return $this->material->uploadThumb($path);
        } catch (\Exception $e) {
            v('upload_material_img_except:' . $e->getMessage());
            return $this->upload_thumb_materials($path, $try_time + 1);
        }

    }

    /**
     * 获取永久素材
     */
    public function get_materials(Request $request)
    {
        $result = $this->material->lists('image', $offset = 0, $count = 5);
        v($result);
    }

    /**
     * 获取永久素材列表
     */
    public function get_material_img_list()
    {
        $result = $this->material->lists('image', 0, 10);
        v($result);
        return $result;
    }

    /**
     * 获取永久图文素材
     */
    public function get_material_resource($media_id)
    {
        $result = $this->material->get($media_id);
        v($result);
        return $result;
    }

    /**
     * 检查素材是否存在了,如果存在则返回素材实体,不存在则上传
     */
    public function check_material_img_exist($name)
    {
        v('origin_name:' . $name);
        $img_list = $this->material->lists('image', 0, 100);
        foreach ($img_list->item as $img) {
            v($img);
            v('material_name:' . $img['name']);
            if ($img['name'] == $name) {
                return $img;
            }
        }
        return false;
    }

    /**
     * 得到素材实体
     */
    public function get_material_img($name)
    {
        $mateial_img = $this->check_material_img_exist($name);
        if (empty($mateial_img)) {
            // 可能会网络问题
            try {
                $update_img = $this->upload_materials($path);
            } catch (\Exception $e) {
                v('upload_material_img_except:' . $e->getMessage());
            }

            return $update_img;
        } else {
            return $mateial_img;
        }
    }

    /**
     * 推送图片消息
     * 48小时外:response out of time limit or subscription is canceled hint: [kSi1ga0292ge30]
     */
    public function send_image($media_id, $openid)
    {
        v('send_image_media_id:' . $media_id . ' openid:' . $openid);
        try {
            $message = new Image(['media_id' => $media_id]);
            $result  = $this->staff->message($message)->to($openid)->send();
            v('send_image_result:');
            v($result);
        } catch (\Exception $e) {
            v('send_image_except:' . $openid . ' info:' . $e->getMessage());
        }
    }

    /**
     * 上传临时素材
     */
    public function upload_temporary_materials($path)
    {
        v('upload_temporary_materials:' . $path);
//     	$path = "/imgs/common/luqu_notice.png";
        $upload_result = $this->temporary->uploadImage($path);
        v('upload_temporary_materials_result:');
        v($upload_result);
        $media_id = isset($upload_result->media_id) ? $upload_result->media_id : '';
        v('media_id:' . $media_id);
        return $media_id;
    }

    /**
     * 上传临时素材
     */
    public function upload_temporary_thumb_materials($path)
    {
        v('upload_temporary_materials:' . $path);
        //     	$path = "/imgs/common/luqu_notice.png";
        $upload_result = $this->temporary->uploadThumb($path);
        v('upload_temporary_materials_result:');
        v($upload_result);
        $media_id = isset($upload_result->media_id) ? $upload_result->media_id : '';
        v('media_id:' . $media_id);
        return $media_id;
    }

    /**
     * 获取临时素材
     */
    public function get_temporary_single_material($mediaId)
    {
        v('get_temporary_single_material:' . $mediaId);
        $content = $this->temporary->getStream($mediaId);
        v('get_temporary_single_material_content:' . $content);
        file_put_contents(public_path("/admin/imgs/download/luqu_notice.png"));
        return empty($content) ? false : true;
    }

    /**
     * 上传单篇图文
     */
    public function upload_article($data)
    {
        // 上传单篇图文
        $article = new Article([
            'title'              => $data['title'],
            'thumb_media_id'     => $data['thumb_media_id'],
            "show_cover_pic"     => $data['show_cover_pic'],
            "author"             => $data['author'],
            "digest"             => $data['digest'],
            "content"            => $data['content'],
            "content_source_url" => $data['content_source_url'],
            //...
        ]);
        v('$article');
        v($article);
        $result = $this->material->uploadArticle($article);
        v('upload_article_result:' . json_encode($result));

        return $result;
    }


    /**
     * 上传临时素材
     */
    public function upload_test($appid, $path)
    {
        v('upload_test');
        $upload_result = $this->material->uploadArticalMediaImage($path);
        v('upload_article_result:' . json_encode($upload_result));
        die();

        $component_access_token = app('wechat_op')->access_token->getToken();
        v('$component_access_token:' . $component_access_token);
        // 先上传缩量图
        try {
            $client      = new Client();
            $form_params = [
                "media" => 'https://cdn-novel.iycdm.com/document_covers/2018111201/1383.jpg?x-oss-process=image/resize,w_900/format,jpg',
//     		   "media"=>$path
            ];
            v($form_params);
            $upload_res = $client->request("post", "https://api.weixin.qq.com/cgi-bin/media/add_material?type=thumb&access_token=" . $component_access_token,
                ['json' => $form_params, 'connect_timeout' => 3]
            )->getBody()->getContents();
            $upload_res = json_decode($upload_res, true);
            v('$upload_res:' . $appid);
            v($upload_res);

        } catch (\Exception $e) {
            v('upload_test_ept_appid:' . $appid . ' ept:' . $e->getMessage());
        }

        return $upload_res;
    }

    /**
     * 上传多篇图文,框架没方法自己写。
     */
    public function upload_articles($appid, $articles)
    {
        $articles = objectToArray(json_decode($articles));
        v('articles');
        v($articles);

        $component_access_token = app('wechat_op')->access_token->getToken();
        v('$component_access_token:' . $component_access_token);
        $last_articles = [];
        $result        = [];
        try {
            foreach ($articles as $article) {
                $last_articles[] = new Article([
                    'title'              => $article['title'],
                    'thumb_media_id'     => $article['thumb_media_id'],
                    "show_cover_pic"     => $article['show_cover_pic'],
                    "author"             => $article['author'],
                    "digest"             => $article['digest'],
                    "content"            => $article['content'],
                    "content_source_url" => $article['content_source_url'],
                    //...
                ]);

                // 测试是否只有1本书可以上传?
//     			$last_articles = new Article([
//     					'title' => $article['title'],
//     					'thumb_media_id' => $article['thumb_media_id'],
//     					"show_cover_pic" => $article['show_cover_pic'],
//     					"author" => $article['author'],
//     					"digest" => $article['digest'],
//     					"content" => $article['content'],
//     					"content_source_url" =>$article['content_source_url'],
//     					//...
//     			]);break;
            }
            v('upload_article_before:' . json_encode($last_articles));
            $result = $this->material->uploadArticle($last_articles);
            v('upload_article_result:' . json_encode($result));
            $media_id = isset($result->media_id) ? $result->media_id : '';
            v('upload_article_media_id:' . $media_id);
        } catch (\Exception $e) {
            $this->_errorMsg['upload_articles'] = $e->getMessage();
            v('upload_articles_ept:' . $e->getMessage());
        }

        return $result;

//     	$upload_res = '';
//     	try{
//     			$client = new Client();
//     			$form_params = [
// 	    			"touser"=>'oAcqg1LRHNKN2jaEkJ5v56HOwPEQ',
// 	    			"mpnews"=>json_encode(['media_id'=>$media_id]),
// 	    			"msgtype"=>"mpnews",
// 	    			"send_ignore_reprint"=>0
//     			];
//     			v($form_params);
//     			$upload_res = $client->request("post","https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$component_access_token,
//     					['json'=>$form_params,'connect_timeout' => 3]
//     			)->getBody()->getContents();
//     			$upload_res = json_decode($upload_res,true);
//     			v('$upload_res:'.$appid);v($upload_res);

//     	}catch(\Exception $e){
//     			v('upload_articles_ept_appid:'.$appid.' ept:'.$e->getMessage());
//     	}

//     	v('upload_articles_result:'.json_encode($upload_res));
//     	return $upload_res;
    }


    public function getErrorMsg($type, $msg = '')
    {
        return getProp($this->_errorMsg, $type, $msg);
    }
}