<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2018/1/29
 * Time: 19:45
 */

namespace App\Http\Controllers\Manage\Activity;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Activity\Transformers\ActivityChargeInfoTransformer;
use App\Http\Controllers\Manage\Activity\Transformers\ActivityTransformer;
use App\Modules\Activity\Services\ActivityService;
use App\Modules\Trade\Services\OrderService;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;
use App\Modules\Product\Services\ProductService;
use Redis;
use DB;
use Storage;
/**
 * 活动
 * Class ActivityController
 * @package App\Http\Controllers\Manage\Activity
 */
class ActivityController extends Controller
{
    /**
     * @apiDefine Activity 活动模块
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/getActivities 获取活动信息
     * @apiGroup Activity
     * @apiName getActivities
     * @apiParam   {Number}  [activity_id] 活动ID
     * @apiParam   {Number}  [distribution_channel_id] 渠道ID
     * @apiParam   {String}  [start_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}  totalOrderCount 总订单数
     * @apiSuccess {Number}  successOrderCount 成功订单数
     * @apiSuccess {Number}  totalChargeAmount 活动的总充值额
     * @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,
     *              "totalOrderCount": 50,
     *              "successOrderCount": 50
     *            }
     *        ]
     *     }
     */
    function getActivities(Request $request)
    {
        $params = [];
        $request->has('end_time') && $request->input('end_time') && $params['end_time'] = trim($request->input('end_time'));
        $request->has('start_time') && $request->input('start_time') && $params['begin_time'] = $request->input('start_time');
        $request->has('activity_id') && $request->input('activity_id') && $params['activity_id'] = $request->input('activity_id');
        $params['distribution_channel_id'] = [0];
        $activities = ActivityService::search($params);
        $distribution_channel_id = 0;
        foreach ($activities as $item) {
            $activity_id = $item->id;
            if ($distribution_channel_id) {
                $item->totalChargeAmount = OrderService::getAmount(['activity_id' => $activity_id, 'distribution_channel_id' => $distribution_channel_id]);
                $item->totalOrderCount = OrderService::getActivityOrderNum(['activity_id' => $activity_id, 'distribution_channel_id' => $distribution_channel_id]);
                $item->successOrderCount = OrderService::getActivityOrderNum(['activity_id' => $activity_id, 'status' => 'PAID', 'distribution_channel_id' => $distribution_channel_id]);
            } else {
                $item->totalChargeAmount = OrderService::getAmount(['activity_id' => $activity_id,'begin_time'=>$item->start_time,'end_time'=>$item->end_time]);
                $item->totalOrderCount = OrderService::getActivityOrderNum(['activity_id' => $activity_id,'begin_time'=>$item->start_time,'end_time'=>$item->end_time]);
                $item->successOrderCount = OrderService::getActivityOrderNum(['activity_id' => $activity_id, 'status' => 'PAID','begin_time'=>$item->start_time,'end_time'=>$item->end_time]);
            }
        }
        return response()->pagination(new ActivityTransformer(), $activities);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} activity/delActivity 删除活动
     * @apiGroup Activity
     * @apiName delActivity
     * @apiParam   {Number}  activity_id 活动ID
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *        ]
     *     }
     */
    function delActivity(Request $request){
        $activity_id = $request->has('activity_id') ? $request->input('activity_id') : '';
        if (empty($activity_id)) {
            return response()->error("PARAM_EMPTY");
        }
        //$activity = ActivityService::getById($activity_id);
        //if($activity)
        DB::table('activity')->where('id',$activity_id)->update(['distribution_channel_id'=>14,'updated_at'=>date('Y-m-d H:i:s')]);
        return response()->success();
    }
    /**
     * @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/ChannelActivityStats 获取明细
     * @apiGroup Activity
     * @apiName ChannelActivityStats
     * @apiParam   {Number}  activity_id 活动ID
     * @apiSuccess {Number}  sum 充值金额.
     * @apiSuccess {Number}  site_id site_id.
     * @apiSuccess {String}  nickname 商户名称.
     * @apiSuccess {String}  allorder 订单比数.
     * @apiSuccess {String}  success 成功顶顶单数
     * @apiSuccess {Number}  rate 成功订单率
     * @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 ChannelActivityStats(Request $request){
        $activity_id = $request->has('activity_id') ? $request->input('activity_id') : '';
        if (empty($activity_id)) {
            return response()->error("PARAM_EMPTY");
        }
        $activity = ActivityService::getById($activity_id);

        $sql_fromat = "SELECT a.*,distribution_channels.nickname from(
SELECT a.sum,a.success,b.allorder,b.distribution_channel_id
from (
SELECT distribution_channel_id,SUM(price) as sum,  COUNT(*) as success
FROM orders WHERE created_at BETWEEN '%s' and '%s' and activity_id = %s and `status` = 'PAID' GROUP BY distribution_channel_id
) a
RIGHT  join (
SELECT distribution_channel_id, COUNT(*) as allorder
FROM orders WHERE created_at BETWEEN '%s' and '%s' and activity_id = %s  GROUP BY distribution_channel_id
) b on a.distribution_channel_id =b.distribution_channel_id
) a join distribution_channels on a.distribution_channel_id=distribution_channels.id";

        $sql = sprintf($sql_fromat,$activity->start_time,$activity->end_time,$activity->id,$activity->start_time,$activity->end_time,$activity->id);
        $res = DB::select($sql);
        foreach ($res as &$v){
            $v->rate = '-';
            if(isset($v->success) && !empty($v->success) && isset($v->allorder) && !empty($v->allorder)){
                $v->rate = sprintf("%.2f", ($v->success/$v->allorder)*100).'%';
            }
        }

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

    /**
     * @apiVersion 1.0.0
     * @api {POST} activity/createdActivity 创捷活动
     * @apiGroup Activity
     * @apiName createdActivity
     * @apiParam   {String} name  活动名称
     * @apiParam   {String} start_time  开始时间
     * @apiParam   {String} end_time  结束时间
     * @apiParam   {String} price  单价
     * @apiParam   {String} page_bd_img  活动页面背景
     * @apiParam   {String} page_btn_pre_img  活动未开始按钮
     * @apiParam   {String} page_btn_doing_img  活动开始按钮
     * @apiParam   {String} page_btn_end_img  活动结束按钮
     * @apiParam   {String} template_name  模板名称
     * @apiParam   {String} template_content  模板内容
     * @apiParam   {String} common_template_id  模板id
     * @apiParam   {String} customer_img  客服消息图片
     * @apiParam   {String} customer_title  客服消息标题
     * @apiParam   {String} wap_bottom_img  章节阅读页底部图片
     * @apiParam   {String} sign_call_back_text  签到回调推广标题
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    public function createdActivity(Request $request)
    {
        $token = str_random(32);
        $param = [];
        $param['name'] = $request->input('name');
        $param['start_time'] = $request->input('start_time');
        $param['end_time'] = $request->input('end_time');
        $param['price'] = $request->input('price');
        $param['page_bd_img'] = $request->input('page_bd_img');
        $param['page_btn_pre_img'] = $request->input('page_btn_pre_img');
        $param['page_btn_doing_img'] = $request->input('page_btn_doing_img');
        $param['page_btn_end_img'] = $request->input('page_btn_end_img');

        $check = checkParam($param, ['name', 'start_time', 'end_time', 'price', 'page_bd_img', 'page_btn_pre_img', 'page_btn_doing_img', 'page_btn_end_img']);
        if ($check) {
            return response()->error("PARAM_EMPTY", ['lack' => $check]);
        }
        $reward = $request->input('reward');
        if ($reward) {
            $reward *= 100;
        }
        $product = ProductService::addProduct([
            'price' => (int)$param['price'],
            'type' => 'TICKET_RECHARGE',
            'given' => $reward,
            'is_default' => 0,
            'is_enabled' => 0,
        ]);
        $activity_settng_key = 'activity:setting';

        $template_name = $request->input('template_name');
        $template_content = $request->has('template_content') ? $request->input('template_content') : '';
        $common_template_id = $request->has('common_template_id') ? $request->input('common_template_id') : '';
        $customer_img = $request->input('customer_img');
        $customer_title = $request->input('customer_title');
        $wap_bottom_img = $request->input('wap_bottom_img');
        $sign_call_back_text = $request->input('sign_call_back_text');
        Redis::del($activity_settng_key);

        $customer_msg = json_encode([
            'pic' => $customer_img,
            'title' => $customer_title
        ]);
        $page_img['page_bd_img'] = $param['page_bd_img'];
        $page_img['page_btn_pre_img'] = $param['page_btn_pre_img'];
        $page_img['page_btn_doing_img'] = $param['page_btn_doing_img'];
        $page_img['page_btn_end_img'] = $param['page_btn_end_img'];

        $activity = ActivityService::createActivity([
            'name' => $param['name'],
            'start_time' => $param['start_time'],
            'end_time' => $param['end_time'],
            'activity_page' => '/sale?token=' . $token,
            'product_id' => $product->id,
            'token' => $token,
            'customer_msg' => $customer_msg,
            'setting' => json_encode($page_img)
        ]);

        if ($template_content && $common_template_id) {
            $wechat_public_templates = DB::table('wechat_public_templates')->select('id')->where('common_template_id',$common_template_id)->first();
            if($wechat_public_templates){
                $id = DB::table('default_template_themes')->insertGetId([
                    'title' => $template_name,
                    'activity_id' => $activity->id,
                    'template_id' => $wechat_public_templates->id,
                    'template_content' => '['.$template_content.']',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);

                DB::table('activity')->where('id',$activity->id)->update([
                    'default_template_id' => $id
                ]);
            }
        }
        $setting = ['activity_id' => $activity->id, 'wap_bottom_img' => $wap_bottom_img, 'sign_call_back_text' => $sign_call_back_text,'activity_title'=>''];
        Redis::set($activity_settng_key, json_encode($setting));
        return response()->success();
    }

    public function uploadImg(Request $request)
    {

        if (!$request->hasFile('photo')) {
            return response()->error('PARAM_EMPTY');
        }
        $file = $request->file('photo');

        $extension = $file->extension();
        $file_name = date('YmdHis') . '.' . $extension;
        $upload_res = $this->ossObject()->uploadFile(env('OSS_BUCKET','zhuishuyun'), 'book/cover/' . $file_name, $file->path());
        $data = ['cover' => $upload_res['oss-request-url']];
        return response()->success($data);
    }

    private 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;
    }

    /**
     * 活动导出
     * @param Request $request
     * @return $this|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportActivity(Request $request){
        set_time_limit(0);
        $id = $request->input('activity_id');
        if (!$id) {
            return response()->error("PARAM_EMPTY");
        }

        $info = ActivityService::ActivityStatsI($id);
        $filename = 'Activit'.date('YmdHis').'.csv';

        Storage::append($filename,mb_convert_encoding("日期,site id,活动页面访问uv,按钮uv,生成订单数,成功支付订单数,首充用户数,点击阅读页面文字链uv,阅读页面文字链订单数,阅读页面文字链成功订单数,阅读页面文字链首充用户数,签到回调文字链uv,签到回调文字链生成订单数,签到回调文字链成功成功订单数,签到回调文字链首充用户数",'gbk'));
        $str = '';
        foreach ($info as $val){
            $str .= "{$val['day']},{$val['siteid']},{$val['uv']},{$val['button_uv']},{$val['order_num']},{$val['success_order_num']},{$val['first_charge_num']},{$val['reader_uv']},{$val['reader_order']},{$val['reader_success_order']},{$val['reader_first_charge']},{$val['signcallback_uv']},{$val['signcallback_order']},{$val['signcallback_success_order']},{$val['signcallback_first_charge']}\r\n";
        }
        Storage::append($filename,mb_convert_encoding($str,'gbk'));
        return response()->download(storage_path('app/'.$filename))->deleteFileAfterSend(true);
    }

    /**
     * 包年活动导出
     * @param Request $request
     * @return $this|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function yearActivityExport(Request $request){
        set_time_limit(0);
        $id = $request->input('activity_id');
        if (!$id) {
            return response()->error("PARAM_EMPTY");
        }

        $info = ActivityService::yearActivityStats($id);
        $filename = 'Activit'.date('YmdHis').'.csv';

        Storage::append($filename,mb_convert_encoding("site id,日期,充值档位,订单数,成功订单数,UV,首充人数,充值总额",'gbk'));
        $str = '';
        foreach ($info as $val){
            $str .= "{$val['siteid']},{$val['day']},{$val['price']},{$val['order_num']},{$val['success']},{$val['uv']},{$val['first_charge']},{$val['sums']}\r\n";
        }
        Storage::append($filename,mb_convert_encoding($str,'gbk'));
        return response()->download(storage_path('app/'.$filename))->deleteFileAfterSend(true);
    }
}