<?php

namespace App\Http\Controllers\Wechat\OfficialAccount;

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

use App\Http\Controllers\Wechat\OfficialAccount\Transformers\WechatTemplatesTransformer;
use App\Http\Controllers\Wechat\OfficialAccount\Transformers\WechatTemplatesMsgTransformer;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomSendMsgsTransformers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Libs\OSS;
use App\Jobs\SendTemplate;
use App\Modules\OfficialAccount\Services\WechatTemplateService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\OfficialAccount\Services\CustomMsgService;

class WechatTemplatesController extends ChannelBaseController
{

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

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/wechatTemplateByAppidAndTemplateId 通过Appid和common_template_id获取模板
     * @apiGroup OfficialAccount
     * @apiName wechatTemplateByAppidAndCommonTemplateId
     * @apiParam   {String}  appid 公众号的appid.
     * @apiParam   {String}  common_template_id 公共模版的ID.
     * @apiSuccess {String}  appid 公众号的appid.
     * @apiSuccess {String}  common_template_id 公共模版的ID.
     * @apiSuccess {String}  template_id 公众号对应模版ID.
     * @apiSuccess {String}  name 名称.
     * @apiSuccess {String}  send_time 发送时间.
     * @apiSuccess {String}  template_content 模板内容.
     * @apiSuccess {String}  redirect_url 重定向地址.
     * @apiSuccess {String}  send_appid 公众号appid.
     * @apiParam {String}  status 模板消息状态.
     * @apiParam {String}  remark 备注.
     * @apiParam {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "appid": "112211",
     *               "common_template_id": "qqqqq",
     *               "template_id": "wqwqwq",
     *           }
     *       }
     */

    function wechatTemplateByAppidAndCommonTemplateId(Request $request)
    {

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

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

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

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

        $wechatTemplate['appid'] = $appid;
        $wechatTemplate['common_template_id'] = $common_template_id;

        $wechatTemplateService = WechatTemplateService::wechatTemplateByAppidAndCommonTemplateId($wechatTemplate);

        return response()->item(new WechatTemplatesTransformer(), $wechatTemplateService);
    }


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

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/wechatTemplateMsgById 通过id获取模板
     * @apiGroup OfficialAccount
     * @apiName wechatTemplateMsgById
     * @apiParam   {String}  id 模板消息id.
     * @apiSuccess {String}  template_id 公众号对应模版ID.
     * @apiSuccess {String}  name 名称.
     * @apiSuccess {String}  send_time 发送时间.
     * @apiSuccess {String}  template_content 模板内容.
     * @apiSuccess {String}  redirect_url 重定向地址.
     * @apiSuccess {String}  send_appid 公众号appid.
     * @apiParam {String}  status 模板消息状态.
     * @apiParam {String}  remark 备注.
     * @apiParam {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "appid": "112211",
     *               "common_template_id": "qqqqq",
     *               "template_id": "wqwqwq",
     *           }
     *       }
     */

    function wechatTemplateMsgById(Request $request)
    {

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

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

        \Log::info('==========================获取 模板消息/客服消息推送状态 ID STATUS');
        \Log::info($id);

        $taskidArray  = explode('_', $id);
        if (count($taskidArray)>1) {
            if ($taskidArray[0] == 'custom') {

                \Log::info('==========================客服消息推送  TASK_ID STATUS');
                \Log::info($id);
                $customSendMsgsService = CustomMsgService::customSendMsgsByTaskid($id);

                if ($customSendMsgsService) {
                    \Log::info($customSendMsgsService['status']);
                }else{
                    \Log::info('未找到这条客服消息');
                }

                return response()->item(new CustomSendMsgsTransformers(), $customSendMsgsService);
            }
            
        }else{

            \Log::info('==========================模板消息推送 ID STATUS');
            \Log::info($id);
            $wechatTemplateMsg['id'] = $id;

            $wechatTemplateMsgService = WechatTemplateService::wechatTemplateMsgById($wechatTemplateMsg);
            if ($wechatTemplateMsgService) {
                \Log::info($wechatTemplateMsgService['status']);
            }else{
                \Log::info('未找到这条模板消息');
            }
            

            return response()->item(new WechatTemplatesMsgTransformer(), $wechatTemplateMsgService);
        }

        
    }



    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/wechatTemplateMsgBydistributionChannelId 获取推送模板消息列表
     * @apiGroup OfficialAccount
     * @apiName wechatTemplateMsgBydistributionChannelId
     * @apiParam   {Number}  distribution_channel_id 分销渠道id.
     * @apiSuccess {String}  id 模板消息唯一ID
     * @apiSuccess {String}  template_id 公众号对应模版ID.
     * @apiSuccess {String}  name 名称.
     * @apiSuccess {String}  send_time 发送时间.
     * @apiSuccess {String}  template_content 模板内容.
     * @apiSuccess {String}  redirect_url 重定向地址.
     * @apiSuccess {String}  send_appid 公众号appid.
     * @apiParam {String}  status 模板消息状态.
     * @apiParam {String}  remark 备注.
     * @apiParam {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "appid": "112211",
     *               "common_template_id": "qqqqq",
     *               "template_id": "wqwqwq",
     *           }
     *       }
     */

    function wechatTemplateMsgBydistributionChannelId(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");
        }

        $wechatTemplatesMsg['distribution_channel_id'] = $distribution_channel_id;

        $wechatTemplatesMsgService = WechatTemplateService::wechatTemplateMsgBydistributionChannelId($wechatTemplatesMsg);

        return response()->pagination(new WechatTemplatesMsgTransformer(), $wechatTemplatesMsgService);
    }



    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/addWechatTemplateMsg 发送模板消息
     * @apiGroup OfficialAccount
     * @apiName addWechatTemplateMsg
     * @apiParam {String}  appid 公众号的appid.
     * @apiParam {String}  common_template_id 公共模版的ID.
     * @apiParam {String}  name 名称.
     * @apiParam {String}  send_time 发送时间.
     * @apiParam {String}  template_content 模板内容.
     * @apiParam {String}  redirect_url 重定向地址.
     * @apiParam {String}  remark 备注.
     * @apiParam {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }  
     */

    function addWechatTemplateMsg(Request $request)
    {

    	\Log::info('addWechatTemplateMsg_start:'.json_encode($request->all()));
        $appid = $request->has('appid') ? $request->input('appid') : '';

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

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

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


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

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

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

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

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

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

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

        if(empty($redirect_url)) {
            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");
        }

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

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

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

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

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

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

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

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

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

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

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

        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['common_template_id'] = $common_template_id;
        $wechatTemplateMsgs['name'] = $name;
        $wechatTemplateMsgs['send_time'] = $send_time;
        $wechatTemplateMsgs['template_content'] = $template_content;
        $wechatTemplateMsgs['redirect_url'] = $redirect_url;
        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['is_full_send'] = $is_full_send;
        $wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;
        $wechatTemplateMsgs['remark'] = $remark;

        $wechatTemplateMsgs['subscribe_time'] = $subscribe_time;
        $wechatTemplateMsgs['sex'] = $sex;
        $wechatTemplateMsgs['balance'] = $balance;
        $wechatTemplateMsgs['order_type'] = $order_type;
        $wechatTemplateMsgs['category_id'] = $category_id;
        \Log::info($wechatTemplateMsgs);

        $resultStatus = WechatTemplateService::addWechatTemplateMsg($wechatTemplateMsgs);

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('TEMEPATES_NOT_FOUND');
        }elseif ($resultStatus == 0) {
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }else{
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/testAddWechatTemplateMsg 单个用户测试发送模板消息
     * @apiGroup OfficialAccount
     * @apiName testAddWechatTemplateMsg
     * @apiParam {String}  appid 公众号的appid.
     * @apiParam {String}  uid 用户uid.
     * @apiParam {String}  common_template_id 公共模版的ID.
     * @apiParam {String}  name 名称.
     * @apiParam {String}  send_time 发送时间.
     * @apiParam {String}  template_content 模板内容.
     * @apiParam {String}  redirect_url 重定向地址.
     * @apiParam {String}  remark 备注.
     * @apiParam {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }  
     */

    function testAddWechatTemplateMsg(Request $request)
    {

    	\Log::info('testAddWechatTemplateMsg_start');
    	\Log::info($request->all());
        $appid = $request->has('appid') ? $request->input('appid') : '';

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

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

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

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

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

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

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

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

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

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

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

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

        if(empty($redirect_url)) {
            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");
        }

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

        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['uid'] = $uid;
        $wechatTemplateMsgs['common_template_id'] = $common_template_id;
        $wechatTemplateMsgs['name'] = $name;
        $wechatTemplateMsgs['send_time'] = $send_time;
        $wechatTemplateMsgs['template_content'] = $template_content;
        $wechatTemplateMsgs['redirect_url'] = $redirect_url;
        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;
        $wechatTemplateMsgs['remark'] = $remark;
        $wechatTemplateMsgs['uid'] = $uid;
        \Log::info($wechatTemplateMsgs);
    
        \Log::info('======================add_template_send======================'."\n");
        $resultStatus = WechatTemplateService::testAddWechatTemplateMsg($wechatTemplateMsgs);

        \Log::info('======================add_news_send======================'."\n");
       

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('TEMEPATES_NOT_FOUND');
        }elseif ($resultStatus == 0) {
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }else{
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/addWechatTemplate 保存模板
     * @apiGroup OfficialAccount
     * @apiName addWechatTemplate
     * @apiParam {String}  appid 公众号的appid.
     * @apiParam {String}  common_template_id 公共模版的ID.
     * @apiParam {String}  template_id 公众号对应模版ID.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }  
     */

    function addWechatTemplate(Request $request)
    {

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

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

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

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

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

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



        $wechatTemplate['appid'] = $appid;
        $wechatTemplate['common_template_id'] = $common_template_id;
        $wechatTemplate['template_id'] = $template_id;

        $resultStatus = WechatTemplateService::addWechatTemplate($wechatTemplate);

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('TEMEPATES_IS_EXIST');
        }elseif ($resultStatus == 0) {
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }else{
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }

        

    }

    
    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/updateWechatTemplateStatus 更新模板消息任务状态
     * @apiGroup OfficialAccount
     * @apiName updateWechatTemplateStatus
     * @apiParam {String}  id 模板消息唯一id.
     * @apiParam {String}  status 模板消息状态.1待发送、2发送中、3已发送、4已停止、0失败
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    
    function updateWechatTemplateStatus(Request $request)
    {
    
    
    	$id = $request->has('id') ? $request->input('id') : '';
    
    	\Log::info('==========================更新模板消息或者客服消息状态'.$id);
    
    	if(empty($id)) {
    		return response()->error("PARAM_EMPTY");
    	}
    
    	$status = $request->has('status') ? $request->input('status') : '';
    
    	if(empty($status)) {
    		return response()->error("PARAM_EMPTY");
    	}
    
    	$wechatTemplate['id'] = $id;
    
    	$wechatTemplate['status'] = $status;
    
    	$resultStatus = WechatTemplateService::updateWechatTemplateStatus($wechatTemplate);
    
    	if ($resultStatus == 1) {
    		return response()->success();
    	}elseif ($resultStatus == 2) {
    		return response()->error('TEMEPATES_NOT_FOUND');
    	}elseif ($resultStatus == 0) {
    		return response()->error('TEMEPATES_UNSUCCESSFUL');
    	}else{
    		return response()->error('TEMEPATES_UNSUCCESSFUL');
    	}
    
    }
    
     /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/updateWechatTemplateId 更新模板消息模板ID
     * @apiGroup OfficialAccount
     * @apiName updateWechatTemplate
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }  
     */

    function updateWechatTemplateId(Request $request)
    {
        $appid = $request->has('appid') ? $request->input('appid') : '';
        $template_id = $request->has('template_id') ? $request->input('template_id') : '';
        $common_template_id = $request->has('common_template_id') ? $request->input('common_template_id') : '';

        \Log::info('updateWechatTemplateId:appid:'.$appid.' template_id:'.$template_id.' common_template_id:'.$common_template_id);
        if(empty($appid) || empty($template_id) || empty($common_template_id) ) {
            return response()->error("PARAM_EMPTY");
        }
        
        $wechatTemplate = array();
        $wechatTemplate['appid'] = $appid;
        $wechatTemplate['template_id'] = $template_id;
        $wechatTemplate['common_template_id'] = $common_template_id;

        $resultStatus = WechatTemplateService::updateWechatTemplateId($wechatTemplate);

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('TEMEPATES_NOT_FOUND');
        }elseif ($resultStatus == 0) {
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }else{
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/updateWechatTemplateMsgById 更新模板消息内容
     * @apiGroup OfficialAccount
     * @apiName updateWechatTemplateMsgById
     * @apiParam {String}  id 模板消息唯一id.
     * @apiParam {String}  name 标题.
     * @apiParam {String}  send_time 发送时间.
     * @apiParam {String}  template_content 内容.
     * @apiParam {String}  redirect_url 重定向地址.
     * @apiParam {String}  remark 备注.
     * @apiParam {String}  status 模板消息状态.1待发送、2发送中、3已发送、4已停止、0失败
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }  
     */

    function updateWechatTemplateMsgById(Request $request)
    {


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

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

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

        $redirect_url = $request->has('redirect_url') ? $request->input('redirect_url') : '';
        
        $remark = $request->has('remark') ? $request->input('remark') : '';
        $is_full_send = $request->has('is_full_send') ? $request->input('is_full_send') : '0';
        
        $wechatTemplate['id'] = $id;
        $wechatTemplate['status'] = $status;
        $wechatTemplate['is_full_send'] = $is_full_send;
        $wechatTemplate['name'] = $name;
        $wechatTemplate['send_time'] = $send_time;
        $wechatTemplate['template_content'] = $template_content;
        $wechatTemplate['redirect_url'] = $redirect_url;
        $wechatTemplate['remark'] = $remark;

        $resultStatus = WechatTemplateService::updateWechatTemplateMsgById($wechatTemplate);

        if ($resultStatus == 1) {
            return response()->success();
        }elseif ($resultStatus == 2) {
            return response()->error('TEMEPATESMSG_NOT_FOUND');
        }elseif ($resultStatus == 0) {
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }else{
            return response()->error('TEMEPATES_UNSUCCESSFUL');
        }
    }

    //内部测试RebitMQ用
    function testRebitMQ(Request $request)
    {
        
        WechatTemplateService::test_add_template_task();

    }

    //---------------测试接口方法
    function forceUserCountByTemplatePrams(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");
        }

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

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

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

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

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

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

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

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

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

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

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

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


        $forceSubscribes = ForceSubscribeService::forceUserCountByTemplatePrams($appids,$distribution_channel_id,$subscribe_time,$sex,$balance,$category_id,$order_type);


        return response()->success(['num'=>count($forceSubscribes)]);
    }



}