<?php

namespace App\Http\Controllers\Channel\Activity;

use App\Http\Controllers\Channel\Activity\Transformers\ActivityChargeInfoTransformer;
use App\Http\Controllers\Channel\Activity\Transformers\ActivityTransformer;
use App\Http\Controllers\Channel\BaseController;
use App\Modules\Activity\Services\ActivityService;
use App\Modules\Activity\Services\ActivitySwitchService;
use App\Modules\Trade\Models\Order;
use App\Modules\Trade\Services\OrderService;
use DB;
use Hashids;
use Illuminate\Http\Request;
use Log;
use Storage;

/**
 * 活动
 * Class ActivityController
 * @package App\Http\Controllers\Channel\Activity
 */
class ActivityController extends BaseController
{

    /**
     * @apiDefine Activity 活动模块
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/getActivities 获取活动信息
     * @apiGroup Activity
     * @apiName getActivities
     * @apiParam   {Number}  [activity_id] 活动ID
     * @apiParam   {String}  [begin_time] 开始时间
     * @apiParam   {String}  [end_time] 结束时间
     * @apiSuccess {Number}  id 活动ID.
     * @apiSuccess {String}  name 活动名称
     * @apiSuccess {String}  activity_page 活动页面
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  start_time 开始时间
     * @apiSuccess {String}  end_time 结束时间
     * @apiSuccess {Number}  price 活动单价
     * @apiSuccess {Number}  totalChargeAmount 活动的总充值额
     * @apiSuccess {Number}  orderCount 订单数
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *            {
     *              "id": 2,
     *              "name": "活动1222",
     *              "activity_page": "http://www.baidu.com",
     *              "created_at": "2017-12-01 10:20:04",
     *              "start_time": "2017-12-01 10:20:04",
     *              "end_time": "2017-12-01 10:20:04",
     *              "price": 30,
     *              "totalChargeAmount": 1000,
     *              "orderCount": 50
     *            }
     *        ]
     *     }
     */
    function getActivities(Request $request)
    {
        $params = [];
        $request->has('end_time') && $request->input('end_time') && $params['end_time'] = trim($request->input('end_time'));
        $request->has('begin_time') && $request->input('begin_time') && $params['begin_time'] = $request->input('begin_time');
        $request->has('activity_id') && $request->input('activity_id') && $params['activity_id'] = $request->input('activity_id');

        $params['distribution_channel_id'] = [0];
        //\Log::info('achor:start_query_activity_info:'.time());
        $activities = ActivityService::search($params);
        //\Log::info('achor:end_query_activity_info:'.time());
        $channel_id = $this->getChannelId();
        //\Log::info('channel_id:'.$channel_id);
        foreach ($activities as $item) {
            $url = $item->activity_page;
            $item->activity_page = env('PROTOCOL') . '://site' . encodeDistributionChannelId($channel_id) . '.' . env('CUSTOM_HOST') . '.com' . $url;
            //select premium
            /*$item->totalChargeAmount = OrderService::getAmount(['activity_id' => $item->id, 'distribution_channel_id' => $channel_id]);
            $item->orderCount = OrderService::getActivityOrderNum(['activity_id' => $item->id, 'status' => 'PAID', 'distribution_channel_id' => $channel_id]);*/
            //\Log::info('achor:start_query_order_info:'.($item->id).':'.time());
            $order_info = Order::select(DB::raw('count(*) as order_count,sum(price) as total_charge_amount'))
                ->where([
                    ['activity_id' ,'=', $item->id],
                    ['status','=', 'PAID'],
                    ['distribution_channel_id','=',$channel_id]
                ])->first();
            //\Log::info('achor:end_query_order_info:'.($item->id).':'.time());
            $item->totalChargeAmount = $order_info?$order_info->total_charge_amount:0;
            $item->orderCount = $order_info?$order_info->order_count:0;
            if ($item->id == 3) {
                $item->price = '50元/108元';
            }
            if ($item->id == 860) {
                $item->price = '17元/30元/58元';
            }
            if($item->id == 1224){
                $item->price = '11元/17元/58元';
            }
            $is_over = 0;
            if($item->end_time < date('Y-m-d H:i:s')){
                $is_over = 1;
            }
            $item->is_over = $is_over;
            //\Log::info('achor:start_query_ActivitySwitch:'.($item->id).':'.time());
            $item->is_reader_page_show = ActivitySwitchService::isShowInPage($item->id, $channel_id, 'reader');
            $item->is_sign_message_show = ActivitySwitchService::isShowInPage($item->id, $channel_id, 'sign');
            //\Log::info('achor:end_query_ActivitySwitch:'.($item->id).':'.time());
        }
        return response()->pagination(new ActivityTransformer(), $activities);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/getActivityRechargeInfo 获取活动的充值明细
     * @apiGroup Activity
     * @apiName getActivityRechargeInfo
     * @apiParam   {Number}  [activity_id] 活动ID
     * @apiSuccess {Number}  uid 用户id.
     * @apiSuccess {Number}  price 充值金额.
     * @apiSuccess {String}  trade_no 平台交易ID.
     * @apiSuccess {String}  pay_end_at 支付完成时间.
     * @apiSuccess {String}  activity_id 活动ID
     * @apiSuccess {Number}  send_order_id 派单id
     * @apiSuccess {String}  send_order_name 派单名称
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *            {
     *              "uid": 1,
     *              "price": "1.00",
     *              "trade_no": "201711301125401585459852216605",
     *              "pay_end_at": "2017-12-01 10:20:04",
     *              "activity_id": 1,
     *              "send_order_id": 0,
     *              "send_order_name": "",
     *              "created_at": 1512094804,
     *            }
     *        ]
     *     }
     */
    function getActivityRechargeInfo(Request $request)
    {
        $activity_id = $request->has('activity_id') ? $request->input('activity_id') : '';
        if (empty($activity_id)) {
            return response()->error("PARAM_EMPTY");
        }
        if (!is_numeric($activity_id)) {
            return response()->error("PARAM_ERROR");
        }
        $activitiesRechargeInfo = ActivityService::getActivityRechargeInfo(['activity_id' => $activity_id, 'status' => 'PAID']);
        return response()->pagination(new ActivityChargeInfoTransformer(), $activitiesRechargeInfo);
    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/pushinfo 快速创建客服消息
     * @apiGroup Activity
     * @apiName getActivityCustomerPushInfo
     * @apiParam   {Number}  activity_id 活动ID
     * @apiSuccess {Number}  data.name 活动名称.
     * @apiSuccess {Number}  data.redirect_url 跳转地址.
     * @apiSuccess {String}  data.pic 图片地址
     * @apiSuccess {String}  data.title 标题
     * @apiSuccessExample {json} Success-Response:
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *           id: 3,
     *           name: "春节活动",
     *           created_at: "2018-02-07 19:41:47",
     *           updated_at: "2018-02-07 19:41:50",
     *           start_time: "2018-02-03 19:41:52",
     *           end_time: "2018-02-07 19:41:54",
     *           activity_page: "http://site2.myzsy.com/sale/springactivity?token=1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d",
     *           product_id: 0,
     *           token: "1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d",
     *           default_template_id: 1,
     *           customer_msg: "{"pic":"https:\/\/yueduyun.oss-cn-hangzhou.aliyuncs.com\/distribution\/activity_pic\/2018020701.jpg","title":"\u3010\u6625\u8282\u7ea2\u5305\u3011\u6625\u8282\u5927\u793c\u5305\uff1a\u514550\u900150 \u3001\u5145108\u9001108\uff01\u4e66\u5e01\u7ffb\u500d\u7b49\u4f60\u6765\u53d6\uff01"} ",
     *           redirect_url: "http://site2.myzsy.com/sale/springactivity?token=1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d",
     *           pic: "https://yueduyun.oss-cn-hangzhou.aliyuncs.com/distribution/activity_pic/2018020701.jpg",
     *           title: "【春节红包】春节大礼包:充50送50 、充108送108!书币翻倍等你来取!"
     *           }
     *       }
     */
    function getActivityCustomerPushInfo(Request $request)
    {
        $activity_id = $request->has('activity_id') ? $request->input('activity_id') : '';
        if (empty($activity_id)) {
            return response()->error("PARAM_EMPTY");
        }
        $channel_id = $this->getChannelId();
        $activity = ActivityService::getById($activity_id);

        $activity->activity_page = env('PROTOCOL') . '://site' . encodeDistributionChannelId($channel_id) . '.' . env('CUSTOM_HOST') . '.com' . $activity->activity_page;
        $activity->redirect_url = $activity->activity_page;
        if ($activity->customer_msg) {
            $push_info = json_decode($activity->customer_msg, 1);
            $activity->pic = $push_info['pic'];
            $activity->title = $push_info['title'];
        } else {
            $activity->pic = '';
            $activity->title = '';
        }

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


    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/quickCreatedTemplateMsg 快速创建模板消息
     * @apiGroup Activity
     * @apiName quickCreatedTemplateMsg
     * @apiParam   {Number}  activity_id 活动ID
     * @apiSuccess {Number}  data.name 活动名称.
     * @apiSuccess {Number}  data.example 模板示例
     * @apiSuccess {String}  data.title 标题
     * @apiSuccess {String}  data.content 内容
     * @apiSuccess {String}  data.redirect_url 跳转链接
     * @apiSuccessExample {json} Success-Response:
     *       {
     *       code: 0,
     *       msg: "",
     *       data: {
     *          name: "春节活动",
     *          activity_page: "http://site2.myzsy.com/sale/springactivity?token=1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d",
     *          example: "尊敬的会员:[微信名称] 恭喜您抽中双节双重大礼包! 会员卡号:充50送50 、充108送108!书币翻倍读不停! 有效期:活动时间2月14日-2月21日 点击【详情】,立即领取限时大礼包>>>",
     *          common_template_id: "TM405959659",
     *          title: "任务到期通知",
     *          content: "{{first.DATA}} 会员卡号:{{keynote1.DATA}} 有效期:{{keynote2.DATA}} {{remark.DATA}}",
     *          redirect_url: "http://site2.myzsy.com/sale/springactivity?token=1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d"
     *       }
     *       }
     */
    function quickCreatedTemplateMsg(Request $request)
    {
        $activity_id = $request->has('activity_id') ? $request->input('activity_id') : '';
        if (empty($activity_id)) {
            return response()->error("PARAM_EMPTY");
        }
        $res = DB::table('activity')
            //->join('default_template_themes', 'activity.id', '=', 'default_template_themes.activity_id')
            ->leftjoin('default_template_themes', 'activity.default_template_id', '=', 'default_template_themes.id')
            ->leftjoin('wechat_public_templates', 'default_template_themes.template_id', '=', 'wechat_public_templates.id')
            ->select('activity.name', 'activity.activity_page', 'default_template_themes.template_content',
                'wechat_public_templates.common_template_id', 'wechat_public_templates.title'
                , 'wechat_public_templates.content', 'wechat_public_templates.example', 'default_template_themes.title')
            ->where('activity.id', $activity_id)
            ->first();
        if ($res) {
            $channel_id = $this->getChannelId();
            $res->activity_page = env('PROTOCOL') . '://site' . encodeDistributionChannelId($channel_id) . '.' . env('CUSTOM_HOST') . '.com' . $res->activity_page;
            $res->redirect_url = $res->activity_page;

        } else {
            $res = [];
        }
        return response()->success((array)$res);

    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/longActivityTemplate 长期活动模板
     * @apiGroup Activity
     * @apiName longActivityTemplate
     * @apiSuccess {Number}  data.name 活动名称.
     * @apiSuccess {Number}  data.price单价
     * @apiSuccess {String}  data.get 获得书币
     * @apiSuccess {String}  data.product_id product_id
     * @apiSuccessExample {json} Success-Response:
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *             [
     *                {
     *                   name: "充68.00元得13600书币",
     *                   price: "68.00",
     *                   get: 13600,
     *                   product_id: 744
     *                   }
     *             ]
     *           }
     *       }
     */
    function longActivityTemplate()
    {
        $product_ids = env('LONG_ACTIVITY_PRODUCT_ID');
        if (!$product_ids)
            return response()->success();

        $product_id_arr = explode(',', $product_ids);
        $product_info = DB::table('products')->whereIn('id', $product_id_arr)->get();
        if (!$product_info)
            return response()->success();

        $activity = [];
        foreach ($product_info as $v) {
            $fee = $v->price * 100 + $v->given;
            $activity[] = ['name' => '充' . $v->price . '元得' . $fee . '书币', 'price' => $v->price, 'get' => $fee, 'product_id' => $v->id];
        }
        return response()->success((array)$activity);
    }

    /**
     * @apiVersion 1.0.0
     * @api {POST} activity/createActivity 创建活动
     * @apiGroup Activity
     * @apiName createActivity
     * @apiParam {String}  name 活动名称.
     * @apiParam {String}  start_time 开始时间
     * @apiParam {String}  end_time   结束时间
     * @apiParam {String}  product_id product_id
     * @apiSuccessExample {json} Success-Response:
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *           }
     *       }
     */
    function createActivity(Request $request)
    {
        $name = $request->input('name');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $product_id = $request->input('product_id');
        $distribution_channel_id = $this->getChannelId();
        $check = checkParam($request->except('_url'), ['name', 'start_time', 'end_time', 'product_id']);
        if ($check) {
            return response()->error("PARAM_EMPTY", ['lack' => $check]);
        }
        $end_time = $end_time . ' 23:59:59';
        $token = str_random(32);
        $product = DB::table('products')->find($product_id);
        if ($product && $product->price == '9.9') {
            $activity_page = '/sale/channelsalenine?token=' . $token;
        } else {
            $activity_page = '/sale/channelsalesixty?token=' . $token;
        }
        $create = ActivityService::createActivity(compact('name', 'start_time', 'end_time', 'product_id', 'distribution_channel_id', 'token', 'activity_page'));
        return response()->success($create);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/channelActivity 活动列表
     * @apiGroup Activity
     * @apiName channelActivity
     * @apiSuccess {Number}  id 活动ID.
     * @apiSuccess {String}  name 活动名称
     * @apiSuccess {String}  activity_page 活动页面
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  start_time 开始时间
     * @apiSuccess {String}  end_time 结束时间
     * @apiSuccess {Number}  price 活动单价
     * @apiSuccess {Number}  totalChargeAmount 活动的总充值额
     * @apiSuccess {Number}  orderCount 订单总数
     * @apiSuccess {Number}  successOrderCount 成功订单总数
     * @apiSuccess {Number}  pageUserNum 访问人数
     * @apiSuccess {Number}  successrate 成功率
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *            {
     *              "id": 2,
     *              "name": "活动1222",
     *              "activity_page": "http://www.baidu.com",
     *              "created_at": "2017-12-01 10:20:04",
     *              "start_time": "2017-12-01 10:20:04",
     *              "end_time": "2017-12-01 10:20:04",
     *              "price": 30,
     *              "totalChargeAmount": 1000,
     *              "orderCount": 50
     *            }
     *        ]
     *     }
     */
    function channelActivity(Request $request)
    {
        $params = [];
        $channel_id = $this->getChannelId();
        $params['distribution_channel_id'] = [$channel_id];
        $activities = ActivityService::search($params);

        foreach ($activities as &$item) {
            $url = $item->activity_page;
            $item->activity_page = env('PROTOCOL') . '://site' . encodeDistributionChannelId($channel_id) . '.' . env('CUSTOM_HOST') . '.com' . $url;
            $stats = ActivityService::getActivityUvPv($item->id, $channel_id);
            //compact('page_pv','page_uv','button_pv','button_uv','order_num','re_order','order_sum');
            $item->totalChargeAmount = $stats['order_sum'];
            $item->orderCount = $stats['button_pv'];
            $item->successOrderCount = $stats['order_num'];
            $item->pageUserNum = $stats['page_uv'];
            $item->successrate = '0%';
            if ($stats['button_pv']) {
                $item->successrate = (string)round(($stats['order_num'] / (int)$stats['button_pv']) * 100, 4) . '%';
            }
            $is_over = 0;
            if($item->end_time < date('Y-m-d H:i:s')){
                $is_over = 1;
            }
            $item->is_over = $is_over;
        }
        return response()->collection(new ActivityTransformer(), $activities);
    }
}