<?php

namespace App\Http\Controllers\Channel\OfficialAccount;

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

use App\Http\Controllers\Channel\OfficialAccount\Transformers\WechatTemplatesTransformer;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\WechatTemplatesMsgTransformer;
use App\Modules\Statistic\Services\WapVisitStatService;
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;
use App\Modules\Channel\Services\ChannelService;

class WechatTemplatesController extends ChannelBaseController
{


    /**
     * @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.
     * @apiSuccess {String}  status 模板消息状态.
     * @apiSuccess {String}  remark 备注.
     * @apiSuccess {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");
        }

        $wechatTemplateMsg['id'] = $id;

        $wechatTemplateMsgService = WechatTemplateService::wechatTemplateMsgById($wechatTemplateMsg);

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


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/wechatTemplateMsgBydistributionChannelId 获取推送模板消息列表
     * @apiGroup OfficialAccount
     * @apiName wechatTemplateMsgBydistributionChannelId
     * @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.
     * @apiSuccess {String}  status 模板消息状态.
     * @apiSuccess {String}  remark 备注.
     * @apiSuccess {Number}  distribution_channel_id 分配的渠道Id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *               "appid": "112211",
     *               "common_template_id": "qqqqq",
     *               "template_id": "wqwqwq",
     *           }wechatTemplateMsgBydistributionChannelId
     *       }
     */

    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");
        // }

        $distribution_channel_id = $this->getChannelId();

        $wechatTemplatesMsg['distribution_channel_id'] = $distribution_channel_id;

        $wechatTemplatesMsgServices = WechatTemplateService::wechatTemplateMsgBydistributionChannelId($wechatTemplatesMsg);
        foreach($wechatTemplatesMsgServices as $key=>$wechatTemplatesMsgService){
        	if($wechatTemplatesMsgService->is_full_send){
        		$wechatTemplatesMsgServices[$key]->user_category = '服务号全量用户';
        	}elseif($wechatTemplatesMsgService->subscribe_time == 'z' &&
        			$wechatTemplatesMsgService->sex == 'z' &&
        			$wechatTemplatesMsgService->balance == 'z' &&
        			$wechatTemplatesMsgService->order_type == 'z' &&
        			$wechatTemplatesMsgService->category_id == 'z' ){
        		$wechatTemplatesMsgServices[$key]->user_category = '追书云全部用户';
        	}else{
        		$wechatTemplatesMsgServices[$key]->user_category = '追书云标签用户';
        	}
        }
        return response()->pagination(new WechatTemplatesMsgTransformer(), $wechatTemplatesMsgServices);
    }

    /**
     * 数据统计，搜索相关
     * @param Request $request
     */
    function searchWechatTemplateMsg(Request $request)
    {
        $start_time = $request->has('start_time') ? $request->input('start_time') : '';
        $end_time = $request->has('end_time') ? $request->input('end_time') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $task_name = $request->has('task_name') ? $request->input('task_name') : '';

        if ($start_time < '2018-11-02') {
            \Log::info('searchWechatTemplateMsg,update_start_time:' . $start_time);
            $start_time = '2018-11-02';
        }

        $distribution_channel_id = $this->getChannelId();
        $param = [
            'distribution_channel_id' => $distribution_channel_id,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'book_name' => $book_name,
            'task_name' => $task_name
        ];
        $wechatTemplatesMsgServices = WechatTemplateService::searchWechatTemplateMsgs($param,false);

        foreach ($wechatTemplatesMsgServices as $key => $customMsgService) {
            $fromtype = 'template_' . $customMsgService->id;
            $statistics = WapVisitStatService::innerCustomerAllStats($fromtype);
            $wechatTemplatesMsgServices[$key]->uv = isset($statistics['uv']) ? $statistics['uv'] : '';
            $wechatTemplatesMsgServices[$key]->pv = isset($statistics['pv']) ? $statistics['pv'] : '';
            $wechatTemplatesMsgServices[$key]->register_user_num = isset($statistics['register_user_num']) ? $statistics['register_user_num'] : '';
            $wechatTemplatesMsgServices[$key]->pay_user_num = isset($statistics['pay_user_num']) ? $statistics['pay_user_num'] : '';
            $wechatTemplatesMsgServices[$key]->charge_amount = isset($statistics['charge_amount']) ? $statistics['charge_amount'] : '';
        }

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

    /**
     * 导出模板消息数据
     * @param Request $request
     */
    function exportWechatTemplateMsg(Request $request)
    {
        $start_time = $request->has('start_time') ? $request->input('start_time') : '';
        $end_time = $request->has('end_time') ? $request->input('end_time') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $task_name = $request->has('task_name') ? $request->input('task_name') : '';

        if ($start_time < '2018-11-02') {
            \Log::info('searchWechatTemplateMsg,update_start_time:' . $start_time);
            $start_time = '2018-11-02';
        }

        $distribution_channel_id = $this->getChannelId();
        $param = [
            'distribution_channel_id' => $distribution_channel_id,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'book_name' => $book_name,
            'task_name' => $task_name
        ];
        $wechatTemplatesMsgServices = WechatTemplateService::searchWechatTemplateMsgs($param,true);

        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "模板消息" . date("YmdHis") . ".csv");
        echo iconv("UTF-8", "GBK", "\"类型\",\"id\",\"任务名称\",\"小说\",\"章节\",\"pv\",\"uv\",\"充值用户\",\"充值总额\"\r\n");
        foreach ($wechatTemplatesMsgServices as $key => $customMsgService) {
            $fromtype = 'template_' . $customMsgService->id;
            $statistics = WapVisitStatService::innerCustomerAllStats($fromtype);
            $uv = empty($statistics['uv']) ? 0 : $statistics['uv'];
            $pv = empty($statistics['pv']) ? 0 : $statistics['pv'];
            $pay_user_num = empty($statistics['pay_user_num']) ? 0 : $statistics['pay_user_num'];
            $charge_amount = empty($statistics['charge_amount']) ? 0 : $statistics['charge_amount'];

            echo("\"" . iconv("UTF-8", "GBK", '模板消息') . "\",");
            echo("\"" . iconv("UTF-8", "GBK", $customMsgService->id) . "\",");
            echo("\"" . iconv("UTF-8", "GBK//IGNORE", $customMsgService->name ? $customMsgService->name : '未填') . "\",");
            echo("\"" . iconv("UTF-8", "GBK//IGNORE", $customMsgService->book_name ? $customMsgService->book_name : '未填') . "\",");
            echo("\"" . iconv("UTF-8", "GBK//IGNORE", $customMsgService->chapter_name ? $customMsgService->chapter_name : '未填') . "\",");
            echo("\"" . iconv("UTF-8", "GBK", $pv) . "\",");
            echo("\"" . iconv("UTF-8", "GBK", $uv) . "\",");
            echo("\"" . iconv("UTF-8", "GBK", $pay_user_num) . "\",");
            echo("\"" . iconv("UTF-8", "GBK", $charge_amount) . "\"\r\n");
        }

        exit();
    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/forceUserCountByTemplatePrams 通过参数获取用户
     * @apiGroup OfficialAccount
     * @apiName wechatTemplateMsgById
     * @apiParam   {String}  subscribe_time 关注时间（a:5天内，b:5-15天，c:15-30天，d:30天以上，z:不限）
     * @apiParam {String}  sex 性别（a:男，b：女，z:不限）
     * @apiParam {String}  order_type 付费情况（a:未付费，b：已付费，c:VIP用户，z:不限）
     * @apiParam {String}  balance 账户余额.（a:低于500，b:500-2000，c:2000-5000，z:不限）
     * @apiParam {String}  category_id 书籍分类.（分类id,z:不限）
     * @apiSuccess {String}  num 用户数量.
     * @apiSuccessExample {json} Success-Response:
     *
     *  {
     *      "code": 0,
     *      "msg": "",
     *      "data": {
     *          "num": 20
     *      }
     *  }
     */

    function forceUserCountByTemplatePrams(Request $request)
    {
        // dd(11);
        $distribution_channel_id = $this->getChannelId();

        $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");
        }

        $appidArray = explode(',', $appids);
        $usernum = 0;
        for ($j = 0; $j < count($appidArray); $j++) {
            $skip = 0;
            $usernum = 0;

            while ($skip <= 2500000) {
                \Log::info('-------------模板消息-----分页取强关用户，目前页数----------' . $skip);
                $users = ForceSubscribeService::forceUserCountByTemplatePrams($appidArray[$j], $distribution_channel_id, $subscribe_time, $sex, $balance, $category_id, $order_type, $skip);
                \Log::info('-----------------实际发送模板消息用户数量-------------' . count($users));
                if (count($users) > 0) {

                    $usernum += count($users);

                } else {

                    break;

                }

                $skip += count($users);
            }
        }


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


    /**
     * @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] 备注.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */

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


        $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 = $this->getChannelId();

        $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';

        $is_activity = $request->has('is_activity') ? $request->input('is_activity') : '0';
        $description = $request->has('description') ? $request->input('description') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $chapter_name = $request->has('chapter_name') ? $request->input('chapter_name') : '';
        if ($is_activity == '0') {
            if (empty($book_name)) {
                return response()->error("PARAM_EMPTY");
            }
            if (empty($chapter_name)) {
                return response()->error("PARAM_EMPTY");
            }
        }
        
        // 判断权限
//         $add_priv = ChannelService::check_channel_company_priv($distribution_channel_id,'add_wechat_template');
//         if(!empty($add_priv)){
//         	\Log::info('wechat_template_is_open:'.$distribution_channel_id);
//         }else{
//         	\Log::info('wechat_template_not_open:'.$distribution_channel_id);
        	 
//         	return response()->error("NOT_ENABLE_TEMPLATE_SEND");
        	
//         	if ($is_full_send) {
//         		return response()->error("NOT_ENABLE_FULL_SEND");
//         	}
//         	if($subscribe_time=='z' && $sex=='z' && $balance=='z' && $order_type=='z' && $category_id=='z' ){
//         		return response()->error("NOT_ENABLE_FULL_SEND");
//         	}
//         }


        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['common_template_id'] = $common_template_id;
        $wechatTemplateMsgs['name'] = $name;
        $wechatTemplateMsgs['send_time'] = $send_time;
        $wechatTemplateMsgs['is_activity'] = $is_activity;
        $wechatTemplateMsgs['template_content'] = $template_content;
        $wechatTemplateMsgs['redirect_url'] = $redirect_url;
        $wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;
        $wechatTemplateMsgs['is_full_send'] = $is_full_send;
        $wechatTemplateMsgs['remark'] = $remark;
        $wechatTemplateMsgs['description'] = $description;
        $wechatTemplateMsgs['book_name'] = $book_name;
        $wechatTemplateMsgs['chapter_name'] = $chapter_name;
        $wechatTemplateMsgs['subscribe_time'] = $subscribe_time;
        $wechatTemplateMsgs['sex'] = $sex;
        $wechatTemplateMsgs['balance'] = $balance;
        $wechatTemplateMsgs['order_type'] = $order_type;
        $wechatTemplateMsgs['category_id'] = $category_id;

        //先判断在发送时间段1小时以内，有没有发起过相同的模板消息，如果有发送过，就提示用户已经创建过相同模板消息，不创建新的模板消息

        // $isSendTemplate = WechatTemplateService::isSendTemplateAtSameTime($wechatTemplateMsgs);
        // if (!empty($isSendTemplate)) {

        //     return response()->error('TEMPLATE_DOUBLE_FAILED');
        // }

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

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

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/delWechatTemplateMsg 删除模板消息
     * @apiGroup OfficialAccount
     * @apiName delWechatTemplateMsg
     * @apiParam   {String}  id 模板消息id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": {
     *           }
     *       }
     */

    function delWechatTemplateMsg(Request $request)
    {

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

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

        $wechatTemplateMsg['id'] = $id;

        $resultStatus = WechatTemplateService::delWechatTemplateMsg($wechatTemplateMsg);

        if ($resultStatus == 1) {
            return response()->success();
        } elseif ($resultStatus == 2) {
            return response()->error('TEMEPATES_NOT_FOUND');
        } elseif ($resultStatus == 4) {
            return response()->error('TEMPLATEMSG_IS_SEDDING');
        } 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}  uid 用户uid.
     * @apiParam {String}  common_template_id 公共模版的ID.
     * @apiParam {String}  name 名称.
     * @apiParam {String}  template_content 模板内容.
     * @apiParam {String}  redirect_url 重定向地址.
     * @apiParam {String}  [remark] 备注.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */

    function testAddWechatTemplateMsg(Request $request)
    {


        \Log::info('channel_testAddWechatTemplateMsg');
        $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");
        }

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

        if (empty($appid)) {
            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 = $this->getChannelId();

        $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");
        // }


        $wechatTemplateMsgs['uid'] = $uid;
        $wechatTemplateMsgs['common_template_id'] = $common_template_id;
        $wechatTemplateMsgs['name'] = $name;
        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['template_content'] = $template_content;
        $wechatTemplateMsgs['redirect_url'] = $redirect_url;
        $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);

        \Log::info('======================add_template_send======================' . "\n");
        $resultStatus = WechatTemplateService::testAddWechatTemplateMsg($wechatTemplateMsgs);

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

        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/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') : '';

        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::wechatTemplateStatusChange($wechatTemplate);

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

    }

    /**
     * @apiVersion 1.0.0
     * @api {POST} OfficialAccount/stopsSendWechatTemplate 停止发送模板消息
     * @apiGroup OfficialAccount
     * @apiName stopsSendWechatTemplate
     * @apiParam {String}  id 模板消息唯一id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */

    function stopsSendWechatTemplate(Request $request)
    {

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

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


        $wechatTemplate['id'] = $id;

        $wechatTemplate['status'] = '4';

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

        if ($resultStatus == 1) {
            return response()->success();
        } elseif ($resultStatus == 2) {
            return response()->error('TEMEPATESMSG_NOT_FOUND');
        } elseif ($resultStatus == 4) {
            return response()->error('TEMPLATEMSG_IS_SEDDING');
        } 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}  appid 标题.
     * @apiParam {String}  common_template_id 标题.
     * @apiParam {String}  name 标题.
     * @apiParam {String}  send_time 发送时间.
     * @apiParam {String}  template_content 内容.
     * @apiParam {String}  redirect_url 重定向地址.
     * @apiParam {String}  [remark] 备注.
     * @apiParam {String}  subscribe_time 关注时间.
     * @apiParam {String}  sex 性别.
     * @apiParam {String}  balance 账户余额.
     * @apiParam {String}  order_type 订单状态.
     * @apiParam {String}  category_id 小说分类.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */

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


        $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");
        }

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

        $distribution_channel_id = $this->getChannelId();

        $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");
        }

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

        if (empty($id)) {
            return response()->error("PARAM_EMPTY");
        }
        $is_activity = $request->has('is_activity') ? $request->input('is_activity') : '0';
        $description = $request->has('description') ? $request->input('description') : '';
        $chapter_name = $request->has('chapter_name') ? $request->input('chapter_name') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        if ($is_activity == '0') {
            if (empty($book_name)) {
                return response()->error("PARAM_EMPTY");
            }
            if (empty($chapter_name)) {
                return response()->error("PARAM_EMPTY");
            }
        }
        
        // 判断权限
//         $add_priv = ChannelService::check_channel_company_priv($distribution_channel_id,'add_wechat_template');
//         if(!empty($add_priv)){
//         	\Log::info('wechat_template_is_open:'.$distribution_channel_id);
//         }else{
//         	\Log::info('wechat_template_not_open:'.$distribution_channel_id);
        	 
//         	return response()->error("NOT_ENABLE_TEMPLATE_SEND");
        	 
//         	if ($is_full_send) {
//         		return response()->error("NOT_ENABLE_FULL_SEND");
//         	}
//         	if($subscribe_time=='z' && $sex=='z' && $balance=='z' && $order_type=='z' && $category_id=='z' ){
//         		return response()->error("NOT_ENABLE_FULL_SEND");
//         	}
//         }


        $wechatTemplateMsgs['appid'] = $appid;
        $wechatTemplateMsgs['common_template_id'] = $common_template_id;
        $wechatTemplateMsgs['name'] = $name;
        $wechatTemplateMsgs['send_time'] = $send_time;
        $wechatTemplateMsgs['is_full_send'] = $is_full_send;
        $wechatTemplateMsgs['is_activity'] = $is_activity;
        $wechatTemplateMsgs['template_content'] = $template_content;
        $wechatTemplateMsgs['redirect_url'] = $redirect_url;
        $wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;
        $wechatTemplateMsgs['remark'] = $remark;
        $wechatTemplateMsgs['description'] = $description;
        $wechatTemplateMsgs['book_name'] = $book_name;
        $wechatTemplateMsgs['chapter_name'] = $chapter_name;
        $wechatTemplateMsgs['id'] = $id;

        $wechatTemplateMsgs['subscribe_time'] = $subscribe_time;
        $wechatTemplateMsgs['sex'] = $sex;
        $wechatTemplateMsgs['balance'] = $balance;
        $wechatTemplateMsgs['order_type'] = $order_type;
        $wechatTemplateMsgs['category_id'] = $category_id;

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

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


        // $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') : '';

        // $wechatTemplate['id'] = $id;
        // $wechatTemplate['status'] = $status;
        // $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();
        return response()->success();

    }


    //检查模板状态
    function checkTemplateStatus(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $appid = $request->has('appid') ? $request->input('appid') : '';

        if (empty($appid)) {
            return response()->error("PARAM_EMPTY");
        }
        $appids = explode(',', $appid);
        if (count($appids) > 1) {
            \Log::info('checkTemplateStatus_appid_num_limit:' . $distribution_channel_id);
            return response()->error("CHECK_TEMPLATE_LIMIT_NUM");
        }

        //

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

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

        $result = WechatTemplateService::checkTemplateStatus($appids, $common_template_id);
        return response()->success($result['msg']);

    }


}