<?php

namespace App\Http\Controllers\Wechat\OfficialAccount;

use App\Http\Controllers\Channel\BaseController as ChannelBaseController;

use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomMsgControllerTransformer;
use App\Http\Controllers\Wechat\OfficialAccount\Transformers\ForceSubscribeUsersTransformer;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Libs\OSS;
use Redis;
use OSS\Core\OssException;
use OSS\OssClient;

class ForceSubscribeUsersController extends ChannelBaseController
{

    /**
     * @apiDefine OfficialAccount 公众号
     */


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/forceSubscribeUsersByAppidAndOpenId 通过appid和openid获取强关用户
     * @apiGroup OfficialAccount
     * @apiName forceSubscribeUsersByAppidAndOpenId
     * @apiParam   {Number}  appid 微信appID.
     * @apiParam   {Number}  openid 公众号openid.
     * @apiSuccess {Number}  uid 用户id.
     * @apiSuccess {Number}  official_account_id 公众账号id.
     * @apiSuccess {Number}  distribution_channel_id 分配的渠道id.
     * @apiSuccess {Number}  openid 公众号openid.
     * @apiSuccess {Number}  appid 微信appID.
     * @apiSuccess {Number}  is_subscribed 是否强关.
     * @apiSuccess {String}  subscribe_time 强关时间.
     * @apiSuccess {String}  unsubscribe_time 取关时间.
     * @apiSuccess {String}  last_interactive_time 强关用户与公众号最后交互时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "uid": 12121212,
     *               "official_account_id": 11111,
     *               "distribution_channel_id": 2323213,
     *               "appid": 112211,
     *               "openid": 11232,
     *               "is_subscribed": 0,
     *               "subscribe_time": "2017-11-22 21:37:15",
     *               "unsubscribe_time": "2017-11-22 22:36:50",
     *               "last_interactive_time": "2017-11-22 22:36:50"
     *           }
     *       }   
     */

    function forceSubscribeUsersByAppidAndOpenId(Request $request)
    {
        
        $appid = $request->has('appid') ? $request->input('appid') : '';
        
        if(empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }
        
        $openid = $request->has('openid') ? $request->input('openid') : '';

        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }

        $forceSubscribeUsers['appid'] = $appid;
        $forceSubscribeUsers['openid'] = $openid;
        $forceSubscribeUsersService = ForceSubscribeService::forceSubscribeUsersByAppidAndOpenId($forceSubscribeUsers);
        return response()->item(new ForceSubscribeUsersTransformer(), $forceSubscribeUsersService);
    }




    function forceSubscribeUsersByOpenidAndAppidAndChannelId(Request $request)
    {
        
        $appid = $request->has('appid') ? $request->input('appid') : '';
        
        if(empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }
        
        $openid = $request->has('openid') ? $request->input('openid') : '';

        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        if(empty($distribution_channel_id)) {
            return response()->error("PARAM_EMPTY");
        }

        $forceSubscribeUsers['appid'] = $appid;
        $forceSubscribeUsers['openid'] = $openid;
        $forceSubscribeUsers['distribution_channel_id'] = $distribution_channel_id;
        $forceSubscribeUsersService = ForceSubscribeService::forceSubscribeUsersByOpenidAndAppidAndChannelId($forceSubscribeUsers);
        return response()->item(new ForceSubscribeUsersTransformer(), $forceSubscribeUsersService);
    }



    /**
     * @apiDefine OfficialAccount 公众号
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/forceSubscribeUsersByUid 通过uid获取强关用户
     * @apiGroup OfficialAccount
     * @apiName forceSubscribeUsersByUid
     * @apiParam   {Number}  uid 用户id.
     * @apiSuccess {Number}  uid 用户id.
     * @apiSuccess {Number}  official_account_id 公众账号id.
     * @apiSuccess {Number}  distribution_channel_id 分配的渠道id.
     * @apiSuccess {Number}  openid 公众号openid.
     * @apiSuccess {Number}  appid 微信appID.
     * @apiSuccess {Number}  is_subscribed 是否强关.
     * @apiSuccess {String}  subscribe_time 强关时间.
     * @apiSuccess {String}  unsubscribe_time 取关时间.
     * @apiSuccess {String}  last_interactive_time 强关用户与公众号最后交互时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "uid": 12121212,
     *               "official_account_id": 11111,
     *               "distribution_channel_id": 2323213,
     *               "appid": 112211,
     *               "openid": 11232,
     *               "is_subscribed": 0,
     *               "subscribe_time": "2017-11-22 21:37:15",
     *               "unsubscribe_time": "2017-11-22 22:36:50",
     *               "last_interactive_time": "2017-11-22 22:36:50"
     *           }
     *       }   
     */

    function forceSubscribeUsersByUid(Request $request)
    {
        
        $uid = $request->has('uid') ? $request->input('uid') : '';
        
        if(empty($uid)) {
            return response()->error("PARAM_EMPTY");
        }
        $forceSubscribeUsers['uid'] = $uid;
        $forceSubscribeUsersService = ForceSubscribeService::forceSubscribeUsersByUid($forceSubscribeUsers);
        return response()->item(new ForceSubscribeUsersTransformer(), $forceSubscribeUsersService);
    }



    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/addForceSubscribeUsers 增加强关用户
     * @apiGroup OfficialAccount
     * @apiName addForceSubscribeUsers
     * @apiParam {Number}  uid 用户id.
     * @apiParam {Number}  official_account_id 公众账号id.
     * @apiParam {Number}  distribution_channel_id 分配的渠道id.
     * @apiParam {Number}  openid 公众号openid.
     * @apiParam {Number}  appid 微信appID.
     * @apiParam {Number}  is_subscribed 是否强关.
     * @apiParam {String}  subscribe_time 强关时间.
     * @apiParam {String}  unsubscribe_time 取关时间.
     * @apiParam {String}  last_interactive_time 强关用户与公众号最后交互时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }    
     */
    function addForceSubscribeUsers(Request $request) {

        $uid = $request->has('uid') ? $request->input('uid') : '';
        if(empty($uid)) {
            return response()->error("PARAM_EMPTY");
        }
        $appid = $request->has('appid') ? $request->input('appid') : '';
        if(empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }
        $openid = $request->has('openid') ? $request->input('openid') : '';
        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }
        $is_subscribed = $request->has('is_subscribed') ? $request->input('is_subscribed') : '1';

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        $last_interactive_time = date("Y-m-d H:i:s");

        $unionid = $request->has('unionid') ? $request->input('unionid') : '1';

        $province = $request->has('province') ? $request->input('province') : '';

        $city = $request->has('city') ? $request->input('city') : '';

        $country = $request->has('country') ? $request->input('country') : '';

        $nick_name = $request->has('nick_name') ? $request->input('nick_name') : '';

        $sex = $request->has('sex') ? $request->input('sex') : '';

        $headimgurl = $request->has('head_img') ? $request->input('head_img') : '';

        $forceSubscribeUsers['uid'] = $uid;
        $forceSubscribeUsers['appid'] = $appid;
        $forceSubscribeUsers['openid'] = $openid;
        $forceSubscribeUsers['nick_name'] = $nick_name;
        $forceSubscribeUsers['is_subscribed'] = $is_subscribed;
        $forceSubscribeUsers['distribution_channel_id'] = $distribution_channel_id;
        $forceSubscribeUsers['last_interactive_time'] = $last_interactive_time;
        $forceSubscribeUsers['unionid'] = $unionid;
        $forceSubscribeUsers['province'] = $province;
        $forceSubscribeUsers['city'] = $city;
        $forceSubscribeUsers['country'] = $country;
        $forceSubscribeUsers['sex'] = $sex;
        $forceSubscribeUsers['headimgurl'] = $headimgurl;


        $resultStatus = ForceSubscribeService::addForceSubscribeUsers($forceSubscribeUsers);

        // 更新交互中间表
        $tempResultStatus = ForceSubscribeService::tempForceSubscribeUsersLastTimeUpdate($forceSubscribeUsers);
        
        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('ADDFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }elseif ($resultStatus == 0) {
            return response()->error('ADDFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }else{
            return response()->error('ADDFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }

    }



    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/ForceSubscribeUsersLastTimeUpdate 强关用户与公众号最后交互时间更新
     * @apiGroup OfficialAccount
     * @apiName ForceSubscribeUsersLastTimeUpdate
     * @apiParam {Number}  openid 公众号openid.
     * @apiParam {String}  last_interactive_time 强关用户与公众号最后交互时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }    
     */
    function forceSubscribeUsersLastTimeUpdate(Request $request) {

        $openid = $request->has('openid') ? $request->input('openid') : '';
        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }
        $last_interactive_time = $request->has('last_interactive_time') ? $request->input('last_interactive_time') : '';
        if(empty($last_interactive_time)) {
            return response()->error("PARAM_EMPTY");
        }

        $forceSubscribeUsers['openid'] = $openid;
        $forceSubscribeUsers['last_interactive_time'] = $last_interactive_time;
        $resultStatus = ForceSubscribeService::forceSubscribeUsersLastTimeUpdate($forceSubscribeUsers);
        
        // 更新交互中间表
        $tempResultStatus = ForceSubscribeService::tempForceSubscribeUsersLastTimeUpdate($forceSubscribeUsers);
        
        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error("FORCESUBSCRIBEUSER_NOT_FOUND");
        }elseif ($resultStatus == 0) {
            return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }else{
            return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/updateForceSubscribeUsers 强关用户强制更新uid
     * @apiGroup OfficialAccount
     * @apiName updateForceSubscribeUsers
     * @apiParam {Number}  openid 公众号openid.
     * @apiParam {String}  uid 强关用户uid.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function updateForceSubscribeUsers(Request $request) {
    
    	$openid = $request->has('openid') ? $request->input('openid') : '';
    	if(empty($openid)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	$uid = $request->has('uid') ? $request->input('uid') : '';
    	if(empty($uid)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	
    	$forceSubscribeUsers = array();
    	$forceSubscribeUsers['openid'] = $openid;
    	$forceSubscribeUsers['uid'] = $uid;
    	$resultStatus = ForceSubscribeService::updateSubscribeUsersUid($forceSubscribeUsers);
    	if ($resultStatus == 1) {
    		return response()->success();
    	}elseif ($resultStatus == 2) {
    		return response()->error("FORCESUBSCRIBEUSER_NOT_FOUND");
    	}elseif ($resultStatus == 0) {
    		return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
    	}else{
    		return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
    	}
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/cancelForceSubscribeUsers 取消用户强制关注
     * @apiGroup OfficialAccount
     * @apiName cancelForceSubscribeUsers
     * @apiParam {Number}  uid 用户id.
     * @apiParam {Number}  openid 公众号openid.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }    
     */
    function cancelForceSubscribeUsers(Request $request) {

        // $uid = $request->has('uid') ? $request->input('uid') : '';
        $openid = $request->has('openid') ? $request->input('openid') : '';
        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }

        $appid = $request->has('appid') ? $request->input('appid') : '';
        if(empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }

        $forceSubscribeUsers['openid'] = $openid;

        $forceSubscribeUsers['appid'] = $appid;

        $resultStatus = ForceSubscribeService::cancelForceSubscribeUsers($forceSubscribeUsers);
        // 更新交互中间表
        $tempResultStatus = ForceSubscribeService::tempForceSubscribeUsersLastTimeUpdate($forceSubscribeUsers);
        
        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error("FORCESUBSCRIBEUSER_NOT_FOUND");
        }elseif ($resultStatus == 0) {
            return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }else{
            return response()->error('CANCELFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }
        
    }


     /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/subscribeForceSubscribeUsers 更新用户为强制关注
     * @apiGroup OfficialAccount
     * @apiName addForceSubscribeUsers
     * @apiParam {Number}  uid 用户id.
     * @apiParam {Number}  official_account_id 公众账号id.
     * @apiParam {Number}  distribution_channel_id 分配的渠道id.
     * @apiParam {Number}  openid 公众号openid.
     * @apiParam {Number}  appid 微信appID.
     * @apiParam {Number}  is_subscribed 是否强关.
     * @apiParam {String}  subscribe_time 强关时间.
     * @apiParam {String}  unsubscribe_time 取关时间.
     * @apiParam {String}  last_interactive_time 强关用户与公众号最后交互时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }    
     */
    function subscribeForceSubscribeUsers(Request $request) {

        $appid = $request->has('appid') ? $request->input('appid') : '';
        if(empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }
        $openid = $request->has('openid') ? $request->input('openid') : '';
        if(empty($openid)) {
            return response()->error("PARAM_EMPTY");
        }
        

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        $last_interactive_time = date("Y-m-d H:i:s");

        $forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenid($openid);

        $forceSubscribeUsers['appid'] = $appid;
        $forceSubscribeUsers['openid'] = $openid;
        $forceSubscribeUsers['distribution_channel_id'] = $distribution_channel_id;
        $forceSubscribeUsers['last_interactive_time'] = $last_interactive_time;
        $resultStatus = ForceSubscribeService::subscribeForceSubscribeUsers($forceSubscribeUsers);

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error("FORCESUBSCRIBEUSER_NOT_FOUND");
        }elseif ($resultStatus == 0) {
            return response()->error('UPDATEFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }else{
            return response()->error('CANCELFORCESUBSCRIBEUSER_UNSUCCESSFUL');
        }

    }

    //------------------------------------方法测试--


    function  testSendTextOfficialMsg(Request $request) {

        $user['uid'] = 13;
        $user['last_interactive_time'] = '2017-12-19 01:11:12';
        $user['distribution_channel_id'] = 1;
        $user['appid'] = 'wxdbc486f1b4f6a8c3';
        $user['openid'] = 'oAcqg1Lc9cjEPznNcjU_6oi1Wj0s';
        $user['is_subscribed'] = 1;
        $user['id'] = 16;
        $user['bid'] = 3;

        // CustomMsgService::add_news_top_book_test($user);
        CustomMsgService::add_news_top_book();
        
        return response()->success(['success'=>1]);
    }


    function forceSubscribeUserCountByChannelIdAndDate(Request $request) {

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';
        if(empty($distribution_channel_id)) {
            return response()->error("PARAM_EMPTY");
        }

        $startTime = $request->has('startTime') ? $request->input('startTime') : '';
        if(empty($startTime)) {
            return response()->error("PARAM_EMPTY");
        }

        $endTime = $request->has('endTime') ? $request->input('endTime') : '';
        if(empty($startTime)) {
            return response()->error("PARAM_EMPTY");
        }

        $usersCount = ForceSubscribeService::forceSubscribeUserCountByChannelIdAndDate($distribution_channel_id,$startTime,$endTime);

        return response()->success($usersCount);
        
    }


    function  customerImgUrlByChannelId(Request $request) {


        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        if(empty($distribution_channel_id)) {
            return response()->error("PARAM_EMPTY");
        }

        $distributionChannelSetting = CustomMsgService::customerImgUrlByChannelId($distribution_channel_id);
        if (!empty($distributionChannelSetting)) {
            # code...
            return response()->success($distributionChannelSetting['customer_img_url']);
        }else{
            return response()->success(['data'=>0]);
        }
        
    }
    
    /**
     * 得到素材强关的映射关系（distribution_channel_id，openid => uid）
     * @param Request $request
     */
    function getMaterialForceSubscribeMapping(Request $request) {
    
    	$distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';
    	if(empty($distribution_channel_id)) {
    		return response()->error("PARAM_EMPTY");
    	}
    
    	$openid = $request->has('openid') ? $request->input('openid') : '';
    	if(empty($openid)) {
    		return response()->error("PARAM_EMPTY");
    	}
    
    	$material_force_subscribe_mapping = ForceSubscribeService::getMaterialForceSubscribeMapping($distribution_channel_id,$openid);
    
    	return response()->success($material_force_subscribe_mapping);
    
    }


    function  uploadCustomerImgUrl(Request $request) {

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        if(empty($distribution_channel_id)) {
            return response()->error("PARAM_EMPTY");
        }
        // dd($request->hasFile('photo')); 
        if ($request->hasFile('photo')) {
            // dd(11);
            // $imagePath = $path = $request->photo->store('images');
            $file = $request->file('photo'); 

                // array:15 [▼
                //   "server" => "AliyunOSS"
                //   "date" => "Fri, 15 Dec 2017 10:03:12 GMT"
                //   "content-length" => "0"
                //   "connection" => "keep-alive"
                //   "x-oss-request-id" => "5A339DDF12058D9711FE3BDE"
                //   "etag" => ""874C0E0C357FBC3BE12404389D17A742""
                //   "x-oss-hash-crc64ecma" => "12762020141128995984"
                //   "content-md5" => "h0wODDV/vDvhJAQ4nRenQg=="
                //   "x-oss-server-time" => "12"
                //   "info" => array:27 [▶]
                //   "oss-request-url" => "http://yueduyun.oss-cn-hangzhou.aliyuncs.com/service/customimage_1_1513332191.WechatIMG77.jpeg"
                //   "oss-redirects" => 0
                //   "oss-stringtosign" => """
                //     PUT\n
                //     \n
                //     image/jpeg\n
                //     Fri, 15 Dec 2017 10:03:11 GMT\n
                //     /yueduyun/service/customimage_1_1513332191.WechatIMG77.jpeg
                //     """
                //   "oss-requestheaders" => array:5 [▶]
                //   "body" => ""
                // ]

            $ossImgBackData = $this->ossObject()->uploadFile(env('OSS_BUCKET','yueduyun'), 'service/customimage_'.$distribution_channel_id.'_'.time().'.'.$file->getClientOriginalName(), $file->path());
            
            $ossImg = $ossImgBackData['oss-request-url'];

            $customerImgPram['distribution_channel_id'] = $distribution_channel_id;

            $customerImgPram['customer_img_url'] = $ossImg;

            $sustomMsgService = CustomMsgService::updateCustomerImgUrl($customerImgPram);

            return response()->item(new CustomMsgControllerTransformer(), $sustomMsgService);


        }   
 
    }


    function ossObject()
    {
        $accessKeyId = env('OSS_ACCESS_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY');
        $endpoint = env('OSS_END_POINT');
        $ossClient = null;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return null;
        }
        return $ossClient;
    }






    
}