<?php

namespace App\Http\Controllers\Channel\OfficialAccount;

use App\Http\Controllers\Channel\BaseController as ChannelBaseController;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomMsgControllerTransformer;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomMsgSwitchMultyTransformer;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomMsgSwitchTransformer;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\CustomSendMsgsTransformers;
use App\Http\Controllers\Channel\OfficialAccount\Transformers\OfficialImgtextUrlsTransformer;
use App\Http\Controllers\Channel\Promotion\Transformers\DocumentCoversTransformer;
use App\Http\Controllers\Channel\Promotion\Transformers\HeadlinelTransformer;
use App\Modules\Statistic\Services\WapVisitStatService;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Promotion\Services\PromotionService;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;

class CustomMsgController extends ChannelBaseController
{

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


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customerImgUrlByChannelId 渠道下获取客服图片
     * @apiGroup OfficialAccount
     * @apiName customerImgUrlByChannelId
     * @apiSuccess {String}  customer_img_url 客服图片.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function customerImgUrlByChannelId(Request $request)
    {


        $distribution_channel_id = $this->getChannelId();

        $distributionChannelSetting = CustomMsgService::customerImgUrlByChannelId($distribution_channel_id);
        if (!empty($distributionChannelSetting)) {
            # code...
            return response()->item(new CustomMsgControllerTransformer(), $distributionChannelSetting);
        } else {
            return response()->success(['data' => 0]);
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/uploadCustomerImgUrl 上传客服图片至OSS
     * @apiGroup OfficialAccount
     * @apiName uploadCustomerImgUrl
     * @apiParam   {String}  customer_img_url 事件类型.
     * @apiSuccess {String}  customer_img_url 客服图片.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function uploadCustomerImgUrl(Request $request)
    {


        $distribution_channel_id = $this->getChannelId();

        if ($request->hasFile('photo')) {

            $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', 'zhuishuyun'), '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);


        }

    }

    /**
     * OSS文件操作
     */
    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;
    }


//-------------------------------------------------客服消息配置开关Start---------------------------CustomMsgSwitchs

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customMsgSwitchSetting 客服消息开关设置
     * @apiGroup OfficialAccount
     * @apiName customMsgSwitchSetting
     * @apiParam {String}  custom_category 客服消息类别.
     * @apiParam {String}  status 客服消息状态 1:开,2:关.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function customMsgSwitchSetting(Request $request)
    {

        $distribution_channel_id = $this->getChannelId();

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

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

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

        $customMsgService = CustomMsgService::customMsgSwitchSetting($distribution_channel_id, $custom_category, $status, $is_self_content);

        if ($customMsgService == 1) {
            return response()->success();
        } elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SETTING_FAILED');
        } elseif ($customMsgService == 0) {
            return response()->error('HAS_NO_CUSTOMS');
        } else {
            return response()->error('CUSTOMS_SETTING_FAILED');
        }


    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customMsgSwitchsByChannelId 客服消息开关列表获取
     * @apiGroup OfficialAccount
     * @apiName customMsgSwitchsByChannelId
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": [
     *              {
     *                  "title": "未支付提醒",
     *                  "custom_category": "not_pay",
     *                  "status": "1",
     *                  "distribution_channel_id": 1,
     *                  "id": 1
     *              },
     *              {
     *                  "title": "定制书籍推送",
     *                  "custom_category": "point_push",
     *                  "status": "0",
     *                  "distribution_channel_id": 1,
     *                  "id": 2
     *              },
     *              {
     *                  "title": "热门书籍推送",
     *                  "custom_category": "hot_push",
     *                  "status": "1",
     *                  "distribution_channel_id": 1,
     *                  "id": 3
     *              }
     *          ]
     *      }
     */
    function customMsgSwitchsByChannelId(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();

        $customMsgService = CustomMsgService::customMsgSwitchsByChannelId($distribution_channel_id);
        if (!empty($customMsgService)) {

            return response()->collection(new CustomMsgSwitchMultyTransformer(), $customMsgService);
        } else {

            return response()->success(['data' => 0]);
        }

    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customMsgSwitchsByChannelCate 获取指定客服消息开关
     * @apiGroup OfficialAccount
     * @apiParam {String}  custom_category 客服消息类别.
     * @apiName customMsgSwitchsByChannelCate
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *              "title": "热门书籍推送",
     *              "custom_category": "hot_push",
     *              "status": "1",
     *              "distribution_channel_id": 1,
     *              "id": 3
     *          }
     *      }
     */
    function customMsgSwitchsByChannelCate(Request $request)
    {


        $distribution_channel_id = $this->getChannelId();

        $custom_category = $request->has('custom_category') ? $request->input('custom_category') : '';
        if (empty($custom_category)) {

            return response()->error("PARAM_EMPTY");
        }

        $customMsgService = CustomMsgService::customMsgSwitchsByChannelCate($distribution_channel_id, $custom_category);

        if (!empty($customMsgService)) {

            return response()->item(new CustomMsgSwitchTransformer(), $customMsgService);
        } else {

            return response()->success(['data' => 0]);
        }

    }

//-------------------------------------------------客服消息配置开关End---------------------------CustomMsgSwitchs


//-------------------------------------------------编辑发送客服消息Start---------------------------CustomSendMsg
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customSendMsgsByChannelId 发送客服消息列表获取
     * @apiGroup OfficialAccount
     * @apiName customSendMsgsByChannelId
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": [
     *              {
     *                  "id": 2,
     *                  "name": "测试222",
     *                  "send_time": "2017-12-26 11:11:11",
     *                  "content": "横眉冷对千夫指,俯首甘为孺子牛",
     *                  "redirect_url": "http:\/\/www.baidu.com\/what?am=1",
     *                  "status": null,
     *                  "distribution_channel_id": 1,
     *                  "subscribe_time": "z",
     *                  "sex": "z",
     *                  "balance": "z",
     *                  "order_type": "z",
     *                  "category_id": "z"
     *              },
     *              {
     *                  "id": 1,
     *                  "name": "测试111",
     *                  "send_time": "2017-12-26 11:11:11",
     *                  "content": "横眉冷对千夫指,俯首甘为孺子牛",
     *                  "redirect_url": "http:\/\/www.baidu.com\/yes?en",
     *                  "status": null,
     *                  "distribution_channel_id": 1,
     *                  "subscribe_time": "z",
     *                  "sex": "z",
     *                  "balance": "z",
     *                  "order_type": "z",
     *                  "category_id": "z"
     *              }
     *          ]
     *      }
     */
    function customSendMsgsByChannelId(Request $request)
    {


        $distribution_channel_id = $this->getChannelId();

        $customMsgServices = CustomMsgService::customSendMsgsByChannelId($distribution_channel_id);

        if (!empty($customMsgServices)) {
        	foreach($customMsgServices as $key=>$customMsgService){
        		if($customMsgService->is_full_send){
        			$customMsgServices[$key]->user_category = '服务号全量用户';
        		}elseif($customMsgService->subscribe_time == 'z' &&
        				$customMsgService->sex == 'z' &&
        				$customMsgService->balance == 'z' &&
        				$customMsgService->order_type == 'z' &&
        				$customMsgService->category_id == 'z' ){
        			$customMsgServices[$key]->user_category = '追书云全部用户';
        		}else{
        			$customMsgServices[$key]->user_category = '追书云标签用户';
        		}
        	}
            return response()->pagination(new CustomSendMsgsTransformers(), $customMsgServices);
        } else {

            return response()->success(['data' => 0]);
        }

    }

    function searchCustomSendMsgs(Request $request)
    {
    	\Log::info('searchCustomSendMsgs_start');
        $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('searchCustomSendMsgs,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
        ];
        $customMsgServices = CustomMsgService::searchCustomSendMsgs($param, false);

        if (!empty($customMsgServices)) {
            foreach ($customMsgServices as $key => $customMsgService) {
                $fromtype = 'custom_' . $customMsgService->id;
                $statistics = WapVisitStatService::innerCustomerAllStats($fromtype);
                $customMsgServices[$key]->uv = isset($statistics['uv']) ? $statistics['uv'] : '';
                $customMsgServices[$key]->pv = isset($statistics['pv']) ? $statistics['pv'] : '';
                $customMsgServices[$key]->register_user_num = isset($statistics['register_user_num']) ? $statistics['register_user_num'] : '';
                $customMsgServices[$key]->pay_user_num = isset($statistics['pay_user_num']) ? $statistics['pay_user_num'] : '';
                $customMsgServices[$key]->charge_amount = isset($statistics['charge_amount']) ? $statistics['charge_amount'] : '';

            }

            return response()->pagination(new CustomSendMsgsTransformers(), $customMsgServices);
        } else {

            return response()->success(['data' => 0]);
        }

    }

    function exportCustomSendMsgs(Request $request)
    {
    	\Log::info('exportCustomSendMsgs_start');
        $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('searchCustomSendMsgs,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
        ];
        $customMsgServices = CustomMsgService::searchCustomSendMsgs($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");
        if (!empty($customMsgServices)) {
            foreach ($customMsgServices as $key => $customMsgService) {
                $fromtype = 'custom_' . $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/customSendMsgsById 通过ID获取指定客服消息
     * @apiGroup OfficialAccount
     * @apiName customSendMsgsById
     * @apiParam {String}  id 客服消息id.
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *              "id": 1,
     *              "name": "测试111",
     *              "send_time": "2017-12-26 11:11:11",
     *              "content": "横眉冷对千夫指,俯首甘为孺子牛",
     *              "redirect_url": "http:\/\/www.baidu.com\/yes?en",
     *              "status": null,
     *              "distribution_channel_id": 1,
     *              "subscribe_time": "z",
     *              "sex": "z",
     *              "balance": "z",
     *              "order_type": "z",
     *              "category_id": "z"
     *          }
     *      }
     */
    function customSendMsgsById(Request $request)
    {


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

        if (empty($id)) {

            return response()->error("PARAM_EMPTY");
        }

        $customMsgService = CustomMsgService::customSendMsgsById($id);

        if (!empty($customMsgService)) {
            if ($customMsgService->description) {
                $customMsgService->description = json_decode($customMsgService->description);
            }
            return response()->item(new CustomSendMsgsTransformers(), $customMsgService);
        } else {

            return response()->success(['data' => 0]);
        }

    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/stopCustomSendMsgsById 停止发送客服消息
     * @apiGroup OfficialAccount
     * @apiName stopCustomSendMsgsById
     * @apiParam {String}  id 客服消息id.
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *          }
     *      }
     */
    function stopCustomSendMsgsById(Request $request)
    {


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

        $customMsgService = CustomMsgService::updateCustomSendMsgsStatus($id);
        if ($customMsgService == 1) {
            return response()->success();
        } elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } elseif ($customMsgService == 4) {
            return response()->error('CUSTOMMSG_IS_SEDDING');
        } elseif ($customMsgService == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } else {
            return response()->error('CUSTOMS_SEND_FAILED');
        }

    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/forceUserCountByCustomPrams 通过参数获取用户
     * @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 forceUserCountByCustomPrams(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;

            while ($skip <= 2500000) {
                \Log::info('-----------客服消息-------分页取强关用户,目前页数----------' . $skip);
                //5,获取所选条件下筛选出的用户
                $sign_time = 'z';
                $force_user = ForceSubscribeService::forceUserCountByCustomPrams($appidArray[$j], $distribution_channel_id, $subscribe_time, $sex, $balance, $category_id, $order_type, $sign_time, $skip);

                if (count($force_user) > 0) {

                    $usernum += count($force_user);

                } else {
                    break;
                }

                $skip += count($force_user);

            }

        }


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

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/addCustomSendMsgs 发送客服消息
     * @apiGroup OfficialAccount
     * @apiName addCustomSendMsgs
     * @apiParam {String}  appid 服务号.
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  send_time 客服消息发送时间.
     * @apiParam {String}  content 客服消息内容. 格式:[[{"title":"横眉冷对千夫指,俯首甘为孺子牛"},{"description":"横眉冷对千夫指,俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年,结果天天被男主人这样!"},{"description":"来他家做佣人半年,结果天天被男主人这样!"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @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 addCustomSendMsgs(Request $request)
    {

        $distribution_channel_id = $this->getChannelId();
        \Log::info('addCustomSendMsgs_start:'.$distribution_channel_id);
        \Log::info($request->all());

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

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

        $content = $request->has('content') ? $request->input('content') : '';
        if (empty($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");
        }

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

        $user_condition = $request->has('user_condition') ? $request->input('user_condition') : '';
        $is_full_send = $request->has('is_full_send') ? $request->input('is_full_send') : '0';
        \Log::info('addCustomSendMsgs_after_check:'.$distribution_channel_id);
        
        $customMsgPrams['appid'] = $appid;
        $customMsgPrams['name'] = $name;
        $customMsgPrams['send_time'] = $send_time;
        $customMsgPrams['is_activity'] = $is_activity;
        $customMsgPrams['content'] = json_encode($content);
        $customMsgPrams['description'] = json_encode($description);
        $customMsgPrams['book_name'] = $book_name;
        $customMsgPrams['chapter_name'] = $chapter_name;
        $customMsgPrams['redirect_url'] = $redirect_url;
        $customMsgPrams['subscribe_time'] = $subscribe_time;
        $customMsgPrams['sex'] = $sex;
        $customMsgPrams['balance'] = $balance;
        $customMsgPrams['order_type'] = $order_type;
        $customMsgPrams['category_id'] = $category_id;
        $customMsgPrams['is_full_send'] = $is_full_send;
        $customMsgPrams['distribution_channel_id'] = $distribution_channel_id;
        $customMsgPrams['status'] = '1';
        $customMsgPrams['user_condition'] = $user_condition;

        //先判断在发送时间段1小时以内,有没有发起过相同的模板消息,如果有发送过,就提示用户已经创建过相同模板消息,不创建新的模板消息
        $isSendCustomer = CustomMsgService::isSendCustomerAtSameTime($customMsgPrams);
        if (!empty($isSendCustomer)) {
            \Log::info('已经发送过该客服消息');
            \Log::info($isSendCustomer['id']);
            \Log::info($isSendCustomer['status']);
            \Log::info($isSendCustomer['del_flag']);
            return response()->error('CUSTOMS_DOUBLE_FAILED');
        }

        $customMsgService = CustomMsgService::addCustomSendMsgs($customMsgPrams);

        if ($customMsgService == 1) {
            return response()->success();
        } elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } elseif ($customMsgService == 3) {
            return response()->error('CUSTOMS_DOUBLE_FAILED');
        } elseif ($customMsgService == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } else {
            return response()->error('CUSTOMS_SEND_FAILED');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/editCustomSendMsgs 发送客服消息
     * @apiGroup OfficialAccount
     * @apiName editCustomSendMsgs
     * @apiParam {String}  appid 服务号.
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  send_time 客服消息发送时间.
     * @apiParam {String}  content 客服消息内容. 格式:[[{"title":"横眉冷对千夫指,俯首甘为孺子牛"},{"description":"横眉冷对千夫指,俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年,结果天天被男主人这样!"},{"description":"来他家做佣人半年,结果天天被男主人这样!"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @apiParam {String}  subscribe_time 用户强关时间段.
     * @apiParam {String}  sex 用户性别.
     * @apiParam {String}  balance 用户账户余额.
     * @apiParam {String}  order_type 用户订单状态.
     * @apiParam {String}  category_id 读书分类.
     * @apiParam {String}  id id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function editCustomSendMsgs(Request $request)
    {

        $distribution_channel_id = $this->getChannelId();

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

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

        $content = $request->has('content') ? $request->input('content') : '';
        if (empty($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");
        }

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

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


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

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


        $customMsgPrams['appid'] = $appid;
        $customMsgPrams['name'] = $name;
        $customMsgPrams['send_time'] = $send_time;
        $customMsgPrams['is_activity'] = $is_activity;
        $customMsgPrams['content'] = json_encode($content);
        $customMsgPrams['description'] = json_encode($description);
        $customMsgPrams['book_name'] = $book_name;
        $customMsgPrams['chapter_name'] = $chapter_name;
        $customMsgPrams['redirect_url'] = $redirect_url;
        $customMsgPrams['subscribe_time'] = $subscribe_time;
        $customMsgPrams['sex'] = $sex;
        $customMsgPrams['balance'] = $balance;
        $customMsgPrams['order_type'] = $order_type;
        $customMsgPrams['category_id'] = $category_id;
        $customMsgPrams['is_full_send'] = $is_full_send;
        $customMsgPrams['distribution_channel_id'] = $distribution_channel_id;
        $customMsgPrams['status'] = '1';
        $customMsgPrams['user_condition'] = $user_condition;

        $customMsgPrams['id'] = $id;


        $customMsgService = CustomMsgService::editCustomSendMsgs($customMsgPrams);

        if ($customMsgService == 1) {
            return response()->success();
        } elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } elseif ($customMsgService == 4) {
            return response()->error('CUSTOMMSG_IS_SEDDING');
        } elseif ($customMsgService == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } else {
            return response()->error('CUSTOMS_SEND_FAILED');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/delCustomSendMsgs 删除客服消息
     * @apiGroup OfficialAccount
     * @apiName delCustomSendMsgs
     * @apiParam {String}  id 客服消息id.
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *          }
     *      }
     */
    function delCustomSendMsgs(Request $request)
    {

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

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

        \Log::info('》》》》》》》》》》》》》》获取删除客服消息时所传的ID');
        \Log::info($id);

        $customSendMsgsPrams['id'] = $id;
        $customMsgService = CustomMsgService::delCustomSendMsgs($customSendMsgsPrams);
        \Log::info('》》》》》》》》》》》》》》获取删除客服消息 返回结果');
        \Log::info($customMsgService);
        if ($customMsgService == 1) {
            return response()->success();
        } elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } elseif ($customMsgService == 4) {
            return response()->error('CUSTOMMSG_IS_SEDDING');
        } elseif ($customMsgService == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        } else {
            return response()->error('CUSTOMS_SEND_FAILED');
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/getAllDocumentCovers 获取所有图库素材
     * @apiGroup OfficialAccount
     * @apiName getAllDocumentCovers
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": [
     *                  {
     *                      "id": 1,
     *                      "origin_cover": "https:\/\/yueduyun.oss-cn-hangzhou.aliyuncs.com\/document_covers\/1.jpg"
     *                  },
     *                  {
     *                      "id": 2,
     *                      "origin_cover": "https:\/\/yueduyun.oss-cn-hangzhou.aliyuncs.com\/document_covers\/2.jpg"
     *                  },
     *                  {
     *                      "id": 3,
     *                      "origin_cover": "https:\/\/yueduyun.oss-cn-hangzhou.aliyuncs.com\/document_covers\/3.jpg"
     *                  }
     *               ]
     *       }
     */
    function getAllDocumentCovers(Request $request)
    {

        $distribution_channel_id = $this->getChannelId();
        $promotionService = PromotionService::getAllMessageDocumentCovers($distribution_channel_id);

        if (!empty($promotionService)) {
            return response()->collection(new DocumentCoversTransformer(), $promotionService);
        } else {

            return response()->success(['data' => 0]);
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/getAllHeadlinesNoType 获取所有标签文案
     * @apiGroup OfficialAccount
     * @apiName getAllHeadlinesNoType
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": [
     *                  {
     *                      "id": 1,
     *                      "title": "三姐妹怀孕,孩子的父亲竟是同一人,婆婆竟然这样说..."
     *                  },
     *                  {
     *                      "id": 2,
     *                      "title": "看哭5000万人,一对32岁夫妻离婚后的聊天记录..."
     *                  }
     *               ]
     *       }
     */
    function getAllHeadlinesNoType(Request $request)
    {

        $promotionService = PromotionService::getHeadlines();

        if (!empty($promotionService)) {

            return response()->collection(new HeadlinelTransformer(), $promotionService);
        } else {

            return response()->success(['data' => 0]);
        }

    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/testAddCustomSendMsgs 测试向单个用户发送客服消息
     * @apiGroup OfficialAccount
     * @apiName testAddCustomSendMsgs
     * @apiParam {String}  appid 服务号.
     * @apiParam {String}  uid 服务号.
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  content 客服消息内容. 格式:[[{"title":"横眉冷对千夫指,俯首甘为孺子牛"},{"description":"横眉冷对千夫指,俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年,结果天天被男主人这样!"},{"description":"来他家做佣人半年,结果天天被男主人这样!"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       }
     */
    function testAddCustomSendMsgs(Request $request)
    {

        $distribution_channel_id = $this->getChannelId();

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

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

        $content = $request->has('content') ? $request->input('content') : '';
        if (empty($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");
        }

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

        $customMsgPrams['appid'] = $appid;
        $customMsgPrams['name'] = $name;
        $customMsgPrams['content'] = json_encode($content);
        $customMsgPrams['redirect_url'] = $redirect_url;
        $customMsgPrams['distribution_channel_id'] = $distribution_channel_id;
        $customMsgPrams['uid'] = $uid;

        $customMsgService = CustomMsgService::testAddCustomSendMsgs($customMsgPrams);

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

    }

//-------------------------------------------------编辑发送客服消息End---------------------------CustomSendMsg


//-------------------------------------------------生成图文链接Start---------------------------

    /**
     * 生成图文链接
     */
    function createOfficialImgTxtUrl(Request $request)
    {


    	\Log::info('createOfficialImgTxtUrl_start');
//     	\Log::info($request->all());
    	
        //图片链接
        $img_url = $request->has('img_url') ? $request->input('img_url') : '';
        if (empty($img_url)) {
            return response()->error("PARAM_EMPTY");
        }
        
        //文章内容
        $content = $request->has('content') ? $request->input('content') : '';
        if (empty($content)) {
            return response()->error("PARAM_EMPTY");
        }

        //推广标题
        $title = $request->has('title') ? $request->input('title') : '';
        if (empty($title)) {
            return response()->error("PARAM_EMPTY");
        }


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


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

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


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


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


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


        $distribution_channel_id = $this->getChannelId();
        
        \Log::info('createOfficialImgTxtUrl_start2:'.$distribution_channel_id.' book_name:'.$book_name.' chapter_sequence:'.$chapter_sequence);
        

        $officialImgTxtUrlPrams['distribution_channel_id'] = $distribution_channel_id;
        $officialImgTxtUrlPrams['img_url'] = $img_url;
        $officialImgTxtUrlPrams['content'] = $content;
        $officialImgTxtUrlPrams['title'] = $title;
        $officialImgTxtUrlPrams['book_name'] = $book_name;
        $officialImgTxtUrlPrams['chapter_sequence'] = $chapter_sequence;
        $officialImgTxtUrlPrams['send_orders_id'] = $send_orders_id;
        $officialImgTxtUrlPrams['send_orders_name'] = $send_orders_name;
        $officialImgTxtUrlPrams['send_orders_url'] = $send_orders_url;
        $customMsgService = CustomMsgService::createOfficialImgTxtUrl($officialImgTxtUrlPrams);

        if (!empty($customMsgService)) {
            # code...
            return response()->success(['img_url' => $customMsgService]);
        } else {
            return response()->error('OFFICIAL_IMGTXT_FAILED');
        }

    }


    /**
     * 获取图文列表
     */
    function getOfficialImgTxtUrl(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();

        $customMsgService = CustomMsgService::getOfficialImgTxtUrl($distribution_channel_id);
        if (!empty($customMsgService)) {
            # code...
            return response()->pagination(new OfficialImgtextUrlsTransformer(), $customMsgService);
        } else {
            return response()->success(['data' => 0]);
        }
    }


    /**
     * 根据标题获取图文列表
     */
    function getOfficialImgTxtUrlByBookName(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();

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

        $customMsgService = CustomMsgService::getOfficialImgTxtUrlByBookName($distribution_channel_id, $book_name);
        if (!empty($customMsgService)) {
            # code...
            return response()->pagination(new OfficialImgtextUrlsTransformer(), $customMsgService);
        } else {
            return response()->success(['data' => 0]);
        }
    }

    /**
     * 上传二维码图片
     */
    function uploadQrcodeImgToWechat(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();

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

        $officialImgTxtUrlPrams['distribution_channel_id'] = $distribution_channel_id;
        $officialImgTxtUrlPrams['qrcode_Img'] = $qrcode_Img;

        $result = CustomMsgService::uploadQrcodeImgToWechat($officialImgTxtUrlPrams);

        if ($result) {
            # code...
            return response()->success(['media_id' => $result['media_id'], 'url' => $result['url']]);

        } else {
            return response()->success();
        }


    }


    function uploadQrcodeImgToOss(Request $request)
    {

        \Log::info('-----------------OSS上传二维码图片');
        $distribution_channel_id = $this->getChannelId();

        if ($request->hasFile('photo')) {

            $file = $request->file('photo');

            $ossImgBackData = $this->ossObject()->uploadFile(env('OSS_BUCKET', 'zhuishuyun'), 'service/qrcodeimg_' . $distribution_channel_id . '_' . time() . '.' . $file->getClientOriginalName(), $file->path());

            $ossImg = $ossImgBackData['oss-request-url'];

            \Log::info('-----------------OSS上传二维码图片成功');
            \Log::info($ossImg);

            return response()->success(['qrcode_img' => $ossImg]);
        } else {
            \Log::info('-----------------没获取到传过来的图片');
        }

    }

    /**
     * 删除图文素材
     */
    function delOfficialImgTxtUrl(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : '';

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

        $customMsgServiceStatus = CustomMsgService::delOfficialImgTxtUrl($id);

        if ($customMsgServiceStatus == 1) {
            return response()->success();
        } elseif ($customMsgServiceStatus == 2) {
            return response()->error('OFFICIAL_IMGTXT_FOUNDFAILED');
        } elseif ($customMsgServiceStatus == 0) {
            return response()->error('OFFICIAL_IMGTXT_DELFAILED');
        } else {
            return response()->error('OFFICIAL_IMGTXT_DELFAILED');
        }
    }

//-------------------------------------------------生成图文链接End---------------------------

}