<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2019/3/4
 * Time: 15:12
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\AlbumAgentModel;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumPosterModel;
use App\Models\AlbumUserModel;
use App\Models\AlbumWatchRecord;
use App\Services\Base\ErrorCode;
use EasyWeChat\Factory;
use Grafika\Color;
use Grafika\Grafika;
use Validator, Response,Auth;
use Illuminate\Http\Request;

class AlbumPosterController extends Controller
{

    /**
     * @api {post} /api/album_post/info 获取海报数据(info)
     * @apiDescription 获取海报数据(info)
     * @apiGroup Album_Post
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *           'posters':'asdawd',  //海报
     *           'words':'asdawd',    //话术
     *           'introduce':'222',   //介绍
     *           'share':'xxx'        //分享图片
     *           'phone':'xxx'        //电话
     *           'username':'xxx'     //姓名
     *           'title':'xxx'        //分享标题
     *           'qrcode':'xxx'     //二维码
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function posterInfo(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }
        $store_id = $request->input('store_id');
        $info = AlbumPosterModel::where('store_id', $store_id)->get();
        $WeChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();
        if ($userAuth->is_dealer != 1) {
            if ($userAuth->up_agent_id == 0) {
                $name = $WeChatApp->name;
            } else {
                $agent_check = AlbumAgentModel::where([
                    ['store_id',$store_id],
                    ['id',$userAuth->up_agent_id]
                ])->first();
                $name = $agent_check->realname;
            }
        } else {
            $agent_check = AlbumAgentModel::where([
                ['store_id',$store_id],
                ['user_id',$userAuth->id]
            ])->first();
            $name = $agent_check->realname;
        }
        $datas['info'] = $info;
        $datas['username'] = $name;
        $datas['avatar'] = $userAuth->avatar;
        $datas['share'] = $WeChatApp->share_image;
        $datas['title'] = $WeChatApp->share_title;
        $datas['personalQrcode'] = $this->createPosterPersonal($WeChatApp, $store_id);
        $datas['qrcode'] = $this->createPoster($userAuth, $store_id);
        return $this->api(compact('datas'));
    }

    /**
     * @api {post} /api/album_post/download 下载海报(download)
     * @apiDescription 生成海报(download)
     * @apiGroup Album_Post
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [poster_id]  海报id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": []
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function posterDownload(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'poster_id' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
            'poster_id.required' => '缺少图片链接'
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $data = $request->input();

        if ($userAuth->up_agent_id != 0) {
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 9;
            $add_record['store_id'] = $data['store_id'];
            $add_record['detail'] = '保存了图片';
            $user_agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $user_agent->share_times++;
            $user_agent->save();



            AlbumWatchRecord::create($add_record);
        }

        AlbumPosterModel::where([['id', $data['poster_id']],['store_id', $data['store_id']]])->increment('downloadNum');

        return $this->api([]);
    }

    Private function createPosterPersonal($WeChatApp, $store_id)
    {

        $userAuth = Auth('api')->user();
        if (file_exists(public_path() . '/download/' . $userAuth->id . '_personal.png')) {
            unlink(public_path() . '/download/' . $userAuth->id . '_personal.png');
        }
        if ($userAuth->is_dealer == 1) {
            $user_agent = AlbumAgentModel::where([['user_id',$userAuth->id],['status',1]])->first();
            $agent_id = $user_agent['id'];
        } else {
            $agent_id = $userAuth->up_agent_id == 0 ? 0 : $userAuth->up_agent_id;
        }
        if ($userAuth->up_agent_id != 0) {
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 9;
            $add_record['store_id'] = $store_id;
            $add_record['detail'] = '保存了图片';
            $user_agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $user_agent->share_times++;
            $user_agent->save();
            AlbumWatchRecord::create($add_record);
        }
        $editor = Grafika::createEditor();
        $editor->open($image_poster, public_path() . '/base/poster/img/poster_canvas.png');
        $editor->open($image_poduct, str_replace(env('CDN_URL'), public_path(), $WeChatApp->circleOfFriends));
        $editor->resizeExactWidth($image_poduct, 440);
        $editor->resizeExactHeight($image_poduct, 440);
        $editor->blend($image_poster, $image_poduct, 'normal', 1, 'top-left', 10, 10);
        $font_bold = public_path() . '/base/poster/font/msyhbd.ttc';
        $font = public_path() . '/base/poster/font/msyh.ttc';
        for ($i = 0; $i <= 1; $i++) {
            $len = mb_strlen($WeChatApp->introduce);
            if ($len <= 17) {
                $editor->text($image_poster, $WeChatApp->introduce, 19, 10, 460, new Color("#000000"), $font_bold, 0);
                break;
            }
            if ($i == 0) {
                $text = mb_substr($WeChatApp->introduce, $i * 17, 17);
            } else {
                $text = mb_substr($WeChatApp->introduce, $i * 17, ($len - 17) > 10 ? 10 : ($len - 17));
            }
            $editor->text($image_poster, $text, 19, 10, 460 + 50 * $i, new Color("#000000"), $font_bold, 0);
        }
        $editor->open($image_icon, public_path() . '/base/poster/img/phone.png');
        $editor->resizeExactWidth($image_icon, 40);
        $editor->resizeExactHeight($image_icon, 40);
        $editor->blend($image_poster, $image_icon, 'normal', 1, 'top-left', 10, 570);

        if ($userAuth->is_dealer != 1) {
            if ($userAuth->up_agent_id == 0) {
                $name = $WeChatApp->name;
                $phone = $WeChatApp->phone;
            } else {
                $agent_check = AlbumAgentModel::where([
                    ['store_id',$store_id],
                    ['id',$userAuth->up_agent_id]
                ])->first();
                $name = $agent_check->realname;
                $phone = $agent_check->phone;
            }
        } else {
            $agent_check = AlbumAgentModel::where([
                ['store_id',$store_id],
                ['user_id',$userAuth->id]
            ])->first();
            $name = $agent_check->realname;
            $phone = $agent_check->phone;
        }
        $editor->text($image_poster, $phone, 20, 55, 577, new Color("#eb7a48"), $font, 0);
        $editor->text($image_poster, '长按识别二维码 展示家具画册', 16, 10, 650, new Color("#666666"), $font, 0);
        if ($agent_id == 0) {
            $editor->open($image_qrcode, str_replace(env('CDN_URL'), public_path(), $WeChatApp->qrcode));
            $editor->resizeExactWidth($image_qrcode, 140);
            $editor->resizeExactHeight($image_qrcode, 140);
        } else {
            $file = $this->getQrCodeEasy($WeChatApp->xyx_id, $WeChatApp->xyx_secret, $agent_id, $store_id, $userAuth->id);
            if (!$file) {
                return $this->error(0, '参数错误，请检查配置', []);
            }
            $editor->open($image_qrcode, $file);
            $editor->resizeExactWidth($image_qrcode, 140);
            $editor->resizeExactHeight($image_qrcode, 140);
        }

        $editor->blend($image_poster, $image_qrcode, 'normal', 1, 'top-left', 310, 500);
        $editor->open($image_avatar, public_path() . '/base/poster/avatar/' . $store_id . "/$userAuth->id.jpg");
        $editor->resizeExactWidth($image_avatar, 64);
        $editor->resizeExactHeight($image_avatar, 64);
        $editor->blend($image_poster, $image_avatar, 'normal', 1, 'top-left', 348, 538);
        $editor->text($image_poster, $name, 16, 380 - (22 * (mb_strlen($name) / 2)), 650, new Color("#666666"), $font, 0);
        $editor->save($image_poster, public_path() . '/download/' . $userAuth->id . '_personal.png');
        $real_url = env('CDN_URL') . '/download/' . $userAuth->id . '_personal.png';
        return $real_url;
    }


    private function getQrCode($appId, $appSecret, $store_id)
    {
        $access = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
        $res_access = $this->curlGet($access);
        $res_access = json_decode($res_access, true);
        if (isset($res_access['access_token'])) {
            $ACCESS_TOKEN = $res_access['access_token'];
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN;
            $data = array();
            $data['scene'] = "scene";//自定义信息，可以填写诸如识别用户身份的字段，注意用中文时的情况
            $data['page'] = "pages/index/index";//扫描后对应的path
            $data['width'] = 800;//自定义的尺寸
            $data['auto_color'] = false;//是否自定义颜色
            $color = array(
                "r" => "0",
                "g" => "0",
                "b" => "0",
            );
            $data['line_color'] = $color;//自定义的颜色值
            //dd($data,$url);
            $data = json_encode($data);
            $this->getHttpArray($url, $data, $store_id);
            return true;
        } else {
            \Log::error($res_access);
            return false;
        }
    }

    /**
     * 获取小程序码 EasyWeChat
     * @param $appId string
     * @param $appSecret string
     * @param $agent_id int
     * @param $store_id int
     * @param $user_id int
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    private function getQrCodeEasy($appId, $appSecret, $agent_id, $store_id, $user_id)
    {
        $config = [
            'app_id' => $appId,
            'secret' => $appSecret,
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->get('pages/index/index?agentid=' . $agent_id, [
            'width' => 140,
        ]);

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            if (!file_exists(public_path() . '/base/poster/QrCode/' . $store_id)) {
                mkdir(public_path() . '/base/poster/QrCode/' . $store_id, 0755, true);
            }
            $filename = $response->saveAs(public_path() . '/base/poster/QrCode/' . $store_id . "/", "$user_id.png");
            if ($filename) {
                return public_path() . "/base/poster/QrCode/" . $store_id . "/$user_id.png";
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private function createPoster($userAuth, $store_id)
    {
        if ($userAuth->is_dealer == 1) {
            $user_agent = AlbumAgentModel::where([['user_id',$userAuth->id],['status',1]])->first();
            $agent_id = $user_agent['id'];
        } else {
            $agent_id = $userAuth->up_agent_id == 0 ? 0 : $userAuth->up_agent_id;
        }
        if (file_exists(public_path() . '/download/' . $userAuth->id . '.png')) {
            unlink(public_path() . '/download/' . $userAuth->id . '.png');
        }

        if ($userAuth->up_agent_id != 0) {
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 9;
            $add_record['store_id'] = $store_id;
            $add_record['detail'] = '保存了图片';
            $user_agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $user_agent->share_times++;
            $user_agent->save();
            //$album = new AlbumController();
            //$album->sendLogsMessage($data['store_id'], $agent->open_id, 9, $userAuth->username, $agent->g_open_id);

            AlbumWatchRecord::create($add_record);
        }

        $editor = Grafika::createEditor();

        $WeChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();

        if ($agent_id == 0) {
            $editor->open($image_qrcode, str_replace(env('CDN_URL'), public_path(), $WeChatApp->qrcode));
            $editor->resizeExactWidth($image_qrcode, 430);
            $editor->resizeExactHeight($image_qrcode, 430);
        } else {
            $file = $this->getQrCodeEasy($WeChatApp->xyx_id, $WeChatApp->xyx_secret, $agent_id, $store_id, $userAuth->id);
            if (!$file) {
                return $this->error(0, '参数错误，请检查配置', []);
            }
            $editor->open($image_qrcode, $file);
            $editor->resizeExactWidth($image_qrcode, 430);
            $editor->resizeExactHeight($image_qrcode, 430);
        }
        $editor->open($image_avatar, public_path() . '/base/poster/avatar/' . $store_id . "/$userAuth->id.jpg");
        $editor->resizeExactWidth($image_avatar, 190);
        $editor->resizeExactHeight($image_avatar, 190);
        $editor->blend($image_qrcode, $image_avatar, 'normal', 1, 'top-left', 120, 120);
        $editor->save($image_qrcode, public_path() . '/download/' . $userAuth->id . '.png');
        $real_url = env('CDN_URL') . '/download/' . $userAuth->id . '.png';
        return $this->api(compact('real_url'));
    }

    /**
     * @api {post} /api/album_post/del 删除海报(del) 已废弃
     * @apiDescription 删除海报(del)
     * @apiGroup Album_Post
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {string}    [url]  图片
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function posterDel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'url' => 'required',
        ], [
            'url' => '缺少图片链接'
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }
        $url = $request->input('url');
        $real_url = str_replace(env('CDN_URL'), public_path(), $url);
        if (file_exists($real_url)) {
            unlink($real_url);
        }
        return $this->api([], 0);
    }

    private function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    private function getHttpArray($url, $post_data, $store_id)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //没有这个会自动输出，不用print_r()也会在后面多个1
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        file_put_contents(public_path() . '/upload/QrCode/' . $store_id . '.png', $output . PHP_EOL, FILE_APPEND);
        curl_close($ch);
        //$out = json_decode($output);
        return true;
    }
}