<?php

namespace App\Http\Controllers\Wap\Order;

use App\Http\Controllers\Wap\BaseController;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Cpa\Services\AdvertiseUserQueueService;
use App\Modules\Cpa\Services\AdvertiseUsersService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Statistic\Services\AdVisitStatService;
use App\Modules\Statistic\Services\DataAnalysisSelectUserService;
use App\Modules\User\Services\ForceSubscribeUserIService;
use App\Modules\User\Services\UserService;
use App\Modules\Book\Services\BookService;
use App\Modules\Channel\Services\PayTemplateService;
use Illuminate\Http\Request;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Subscribe\Services\OrderService;
use App\Http\Controllers\Wap\Order\Transformers\BookOrderTransformer;
use App\Http\Controllers\Wap\Order\Transformers\ChapterOrderTransformer;
use App\Http\Controllers\Wap\Order\Transformers\ChargeListTransformer;
use Redis;
use App\Modules\Product\Services\ProductService;
use App\Modules\Subscribe\Services\SubstituteOrderService;
use Hashids;
use DB;

class OrdersController extends BaseController
{
    /**
     * @apiDefine Order 订单
     */

    private $force_subscribe_info;
    /**
     * @apiVersion 1.0.0
     * @apiDescription 充值列表
     * @api {get} order/chargeList 充值列表
     * @apiGroup Order
     * @apiName chargeList
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: [
     *               {
     *                   product_id: 1,
     *                   price: "30.00元",
     *                   vip: 0,
     *                   intro: [
     *                       {
     *                           label: 3000,
     *                           important: false
     *                       },
     *                       {
     *                           label: "书币",
     *                           important: true
     *                       }
     *                   ]
     *               },
     *               {
     *                   product_id: 2,
     *                   price: "50.00元",
     *                   vip: 1,
     *                   intro: [
     *                       {
     *                           label: 5000,
     *                           important: false
     *                       },
     *                       {
     *                           label: "1000+",
     *                           important: true
     *                       },
     *                       {
     *                           label: "书币",
     *                           important: false
     *                       }
     *                       ]
     *               },
     *               {
     *                   product_id: 5,
     *                   price: "365.00元",
     *                   vip: 0,
     *                   intro: [
     *                       {
     *                       label: "年费VIP会员",
     *                       important: true
     *                       }
     *                   ]
     *               }
     *               ]
     *       }
     */
    public function chargeList_(Request $request)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $res = ProductService::getChargeProduct();
        if (!$res->isEmpty()) {
            $data = [];

            /*if ($this->send_order_id) {
                try {
                    Redis::sadd('pay_page_uv' . $this->send_order_id, $this->uid);
                    Redis::sadd('pay_page_uv_send_order_ids', $this->send_order_id);
                } catch (\Exception $e) {
                }

            }*/


            foreach ($res as $v) {
                $intro = [];
                if ($v->given > 0 && $v->type == 'TICKET_RECHARGE') {
                    $intro = [
                        [
                            'label' => ($v->price * 100) . "+",
                            'important' => false,
                        ],
                        [
                            'label' => $v->given,
                            'important' => true,
                        ],
                        [
                            'label' => '书币',
                            'important' => false,
                        ]

                    ];
                    $intro2 = [
                        ['label' => '多送', 'important' => false],
                        ['label' => (int)($v->given / 100), 'important' => true],
                        ['label' => '元', 'important' => false],
                    ];
                    $v->vip = 0;
                }
                if ($v->given == 0 && $v->type == 'TICKET_RECHARGE') {
                    $intro = [
                        [
                            'label' => $v->price * 100,
                            'important' => false,
                        ],
                        [
                            'label' => '书币',
                            'important' => false,
                        ]
                    ];
                    $v->vip = 0;
                    $intro2 = [];
                }
                if ($v->given == 0 && $v->type == 'YEAR_ORDER') {
                    $intro = [
                        [
                            'label' => '年费VIP会员',
                            'important' => true,
                        ]
                    ];
                    $v->vip = 1;
                    $intro2 = [
                        ['label' => '每天1元,全年免费看', 'important' => false],
                    ];
                }
                $data[] = [
                    'product_id' => $v->id,
                    'price' => (int)$v->price . '元',
                    'vip' => $v->vip,
                    'intro' => $intro,
                    'intro2' => $intro2,
                    'is_default' => $v->is_default,

                ];
            }
            return response()->success($data);
        } else {
            return response()->error('WAP_SYS_ERROR');
        }
    }

    public function chargeList(Request $request)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        /*if (env('OTHER_PAY_TEMPLATE') &&
            in_array($this->distribution_channel_id,
                explode(',', env('OTHER_PAY_TEMPLATE')))
        ) {
            $template_id = 3;
        } else {*/
        $bid = $request->input('bid', '');
        $temp = $bid;
        $template_id = PayTemplateService::getPayTemplate($this->distribution_channel_id);
        //}
        \Log::info('order:$template_id:' . $template_id);
        \Log::info('order:$distribution_channel_id:' . ($this->distribution_channel_id));

        if ($template_id == 2) { //模板2只有在长篇小说过来的用户才显示
            //部分渠道需要2元模板不管哪个入口进来都展示
            $exclude_channels = explode(',', env('PRICE_TWO_SHOW_ALL_CHANNEL'));
            if(!in_array($this->distribution_channel_id,$exclude_channels))
            {
                if ($bid) {
                    $bid = Hashids::decode($bid)[0];
                    \Log::info('order:$bid:' . $bid);
                    $book = BookService::getBookById($bid);
                    \Log::info('order:$$book:' . json_encode($book));
                    if ($book->size < 200000) {
                        $template_id = 1;
                    }
                } else {
                    $template_id = 1;
                }
            }
        }
        if($temp){
            $temp_bid = 0;
            try{
                $temp_bid =  Hashids::decode($temp)[0];
            }catch (\Exception $e){}

            $t = $this->recordFirstIntoPayPage($temp_bid);
            if ($t) {
                $template_id = $t;
            }
        }

        //男频站点 支付模板
        if( ($male_site_template = $this->maleSite($this->distribution_channel_id)) ){
            //\Log::info('$male_site_template is: '.$male_site_template);
            $template_id = $male_site_template;
        }

        if( ($compare_id = $this->templateCompare()) ){
            $template_id = $compare_id;
        }

        /*if( ($comparev2_id = $this->templateCompareV2()) ){
            $template_id = $comparev2_id;
        }*/

        \Log::info('recordFirstIntoPayPage:$template_id:' . $template_id);
        $res = ProductService::getChargeProduct($template_id);
        if (!$res) {
            return response()->error('WAP_SYS_ERROR');
        }

        /*if ($this->send_order_id) {
            try {
                Redis::sadd('pay_page_uv' . $this->send_order_id, $this->uid);
                Redis::sadd('pay_page_uv_send_order_ids', $this->send_order_id);
            } catch (\Exception $e) {
            }

        }*/
        //TODO 长篇小数才有模板2
        //$user = $this->_user_info;
        $uid = $this->uid;
        $is_first_recharge = OrderService::judgeUserFirstRecharge($uid);
        //yqLog('user')->info('user is ',['user'=>$user]);
        //yqLog('user')->info('user is ',['charge_count'=>$user->charge_count]);
        $data = [];
        $appad =0;
        if(in_array($this->distribution_channel_id,explode(',',env('ADS_OPEN_SITE')))){
            $appad = $this->appad();
            $my_bid = $bid;
            if($appad) {
                try{
                    AdvertiseUsersService::addAdAccessRec(['uid'=>$this->uid,
                        'bid'=>$my_bid,
                        'position'=>'RECHARGE',
                        'created_at'=>date('Y-m-d H:i:s'),
                        'updated_at'=>date('Y-m-d H:i:s'),
                        'remark'=>$request->url()
                    ]);
                }catch(\Exception $e){
                    \Log::error('insert into advertise_access_rec failded:'.$e->getMessage());
                }
            }
        }
        //\Log::info('ad-tu:uid:'.$uid.':'.$appad);
        foreach ($res as $v) {
            if($appad && $v->price == 100){
                //continue;
            }
            if ($v->type == 'NEW_USER' && $is_first_recharge) {
                if (env('NO_NEW_USER_CHARGE') &&
                    in_array(
                        $this->distribution_channel_id,
                        explode(',', env('NO_NEW_USER_CHARGE'))
                    )
                ) {
                    continue;
                }
                $temp = [
                    'price' => (float)$v->price . '元',
                    'is_year_order' => 0,
                    'text' => sprintf('%s+%s书币', $v->price * 100, $v->given),
                    'first_charge' => true,
                    'today_special' => false,
                    'save_text' => round($v->given / 100, 1) . '元',
                    'product_id' => $v->id,
                    'show_free_ads'=>$appad
                ];
                $data[] = $temp;
            } elseif ($v->type == 'YEAR_ORDER') {
                if ($v->type == 'NEW_USER') {
                    continue;
                }
                $save_text = '年费vip会员';
                $text = '每天1元,全年免费看';
                $temp = [
                    'price' => (int)$v->price . '元',
                    'is_year_order' => 1,
                    'text' => $text,
                    'first_charge' => false,
                    'today_special' => false,
                    'save_text' => $save_text,
                    'product_id' => $v->id,
                    'show_free_ads'=>$appad
                ];
                $data[] = $temp;
            } else {
                if ($v->type == 'NEW_USER') {
                    continue;
                }
                $save_text = '';
                if ($v->given) {
                    $save_text = round($v->given / 100, 1) . '元';
                    $text = sprintf('%s+%s书币', $v->price * 100, $v->given);
                } else {
                    $text = sprintf('%s书币', $v->price * 100);
                }

                $temp = [
                    'price' => (float)$v->price . '元',
                    'is_year_order' => 0,
                    'text' => $text,
                    'first_charge' => false,
                    'today_special' => $v->is_default == 1 ? true : false,
                    'save_text' => $save_text,
                    'product_id' => $v->id,
                    'show_free_ads'=>$appad
                ];
                $data[] = $temp;
            }
        }
        return response()->success($data);
    }


    public function substitutePayChargeList(Request $request)
    {
        $default = $request->get('product_id');
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $su = $request->get('su');
        $res = ProductService::getChargeProduct();
        if (!$res) {
            return response()->error('WAP_SYS_ERROR');
        }
        $is_can_allow_pay = 1;
        if ($su) {
            $su_user = UserService::getById($su);
            $now_user = $this->_user_info;
            if ($now_user && $su_user && $su_user->openid == $now_user->openid) {
                $is_can_allow_pay = 0;
            }
        }
        SubstituteOrderService::substitutePageUvPv($this->uid, $this->distribution_channel_id);
        $data = [];
        foreach ($res as $v) {
            if ($v->type == 'YEAR_ORDER') {
                $temp = [
                    'price' => (int)$v->price . '元',
                    'text' => '年费VIP会员',
                    'first_charge' => false,
                    'today_special' => $v->is_default == 1 ? true : false,
                    'save_text' => '全年免费',
                    'product_id' => $v->id,
                    'default' => false,
                    'is_vip' => 1,
                    'is_can_allow_pay' => $is_can_allow_pay
                ];
                if ($default) {
                    if ($default == $v->id) {
                        $temp['default'] = true;
                    }
                } else {
                    $temp['default'] = $v->is_default == 1 ? true : false;
                }
                $data[] = $temp;

            } else {
                $save_text = '';
                if ($v->given) {
                    $save_text = round($v->given / 100, 1) . '元';
                    $text = sprintf('%s+%s书币', $v->price * 100, $v->given);
                } else {
                    $text = sprintf('%s书币', $v->price * 100);
                }

                $temp = [
                    'price' => (int)$v->price . '元',
                    'text' => $text,
                    'first_charge' => false,
                    'today_special' => $v->is_default == 1 ? true : false,
                    'save_text' => $save_text,
                    'product_id' => $v->id,
                    'default' => false,
                    'is_vip' => 0,
                    'is_can_allow_pay' => $is_can_allow_pay
                ];
                if ($default) {
                    if ($default == $v->id) {
                        $temp['default'] = true;
                    }
                } else {
                    $temp['default'] = $v->is_default == 1 ? true : false;
                }

                $data[] = $temp;
            }
        }
        return response()->success($data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 单本消费记录
     * @api {get} order/bookOrderList 单本消费记录
     * @apiGroup Order
     * @apiName bookOrderList
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         uid uid
     * @apiSuccess {Int}         bid bid
     * @apiSuccess {Int}         book_name 书名
     * @apiSuccess {Int}         fee 钱
     * @apiSuccess {String}      created_at 时间
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: list:[
     *               {
     *                   uid: 4,
     *                   bid: 1,
     *                   book_name: "dfsedfertrwet",
     *                   fee: 100,
     *                   created_at: "2017-12-02 16:24:54"
     *                   }
     *               ]
     *            meta: {
     *                       total: 1,
     *                       per_page: 15,
     *                       current_page: 1,
     *                       last_page: 1,
     *                       next_page_url: "",
     *                       prev_page_url: ""
     *               }
     *       }
     */
    public function bookOrderList(Request $request)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $page_size = $request->input('page_size', 15);
        $book_order = BookOrderService::getRecord($this->uid, $page_size);
        //$book_order = BookOrder::where('uid', $this->uid)->select('bid', 'uid', 'book_name', 'created_at', 'fee')->paginate($page_size);

        return response()->pagination(new BookOrderTransformer(), $book_order);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节消费记录
     * @api {get} order/chapterOrderList 章节消费记录
     * @apiGroup Order
     * @apiName chapterOrderList
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         uid uid
     * @apiSuccess {Int}         bid bid
     * @apiSuccess {Int}         cid cid
     * @apiSuccess {Int}         chapter_name 章节名
     * @apiSuccess {Int}         book_name 书名
     * @apiSuccess {Int}         fee 钱
     * @apiSuccess {String}      created_at 时间
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: list:[
     *               {
     *                   uid: 4,
     *                   bid: 1,
     *                   cid: 1,
     *                   chapter_name: "sdfsd",
     *                   book_name: "dfsedfertrwet",
     *                   fee: 100,
     *                   created_at: "2017-12-02 16:24:54"
     *                   }
     *               ]
     *            meta: {
     *                       total: 1,
     *                       per_page: 15,
     *                       current_page: 1,
     *                       last_page: 1,
     *                       next_page_url: "",
     *                       prev_page_url: ""
     *               }
     *       }
     */
    public function chapterOrderList(Request $request)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $chapter_model = new ChapterOrderService();
        $page_size = $request->input('page_size', 15);
        $chapter_order = $chapter_model->getByUid($this->uid, $page_size);
        foreach ($chapter_order as $item){
            if($item->fee == 0){
                $result = AdVisitStatService::getInfoV2($this->uid,$item->cid,['UNLOCK','UNLOCK_2']);
                if($result) $item->fee = '解锁';
            }
        }
        return response()->pagination(new ChapterOrderTransformer(), $chapter_order);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 充值记录
     * @api {get} order/chargeRecordLists 充值记录
     * @apiGroup Order
     * @apiName chargeRecordLists
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {String}      data.price       价格
     * @apiSuccess {String}      data.status      状态
     * @apiSuccess {String}      data.trade_no    订单号
     * @apiSuccess {String}      data.created_at  时间
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *    {
     *       code: 0,
     *       msg: "",
     *           data: {
     *               list: [
     *               {
     *                    id: 134,
     *                    price: "1.00",
     *                    status: "PAID",
     *                    trade_no: "201712021915481585670623626232",
     *                    created_at: "2017-12-02 19:15:56"
     *           }
     *       ],
     *           meta: {
     *               total: 1,
     *               per_page: 15,
     *               current_page: 1,
     *               last_page: 1,
     *               next_page_url: "",
     *               prev_page_url: ""
     *           }
     *       }
     *    }
     */
    public function chargeRecordLists(Request $request)
    {
        $page_size = $request->input('page_size', 15);
        $res = OrderService::getOrderList($this->uid, $page_size);
        return response()->pagination(new ChargeListTransformer(), $res);
    }

    //订单是否成功
    public function isSuccess(Request $request)
    {
        $order = $request->input('order');
        $order_info = OrderService::getByTradeNo($order);
        if ($order_info && $order_info->status == 'PAID') {
            return response()->success();
        }
        return response()->error('WAP_SYS_ERROR');
    }

    public function substitutePay(Request $request)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $product_id = $request->get('product_id');
        SubstituteOrderService::substituteButtonUvPv($this->uid, $this->distribution_channel_id);
        $user = $this->_user_info;
        $data = [
            'head_img' => '',
            'nickname' => $user->nickname
        ];
        //$help_pay_page_channel_id = env('HELP_PAY_PAGE_CHANNEL_ID', 123);
        $help_pay_page_channel_id = $this->distribution_channel_id;
        $url_format = '%s://site%s.%s.com/helppay?%s';
        $param = [];
        $param['su'] = $this->uid;
        if ($product_id) {
            $param['product_id'] = $product_id;
        }

        $help_pay_page = sprintf(
            $url_format,
            env('PROTOCOL'),
            encodeDistributionChannelId($help_pay_page_channel_id),
            env('CUSTOM_HOST'),
            http_build_query($param)
        );
        $data['help_pay_page'] = $help_pay_page;
        return response()->success($data);
    }

    private function recordFirstIntoPayPage($bid)
    {
        $start_time = env('RECORD_FIRST_VISIT_PAY_PAGE_TIME');
        $template_id = 0;
        if (in_array($this->distribution_channel_id,[123,211])  && $start_time && $this->uid) {
            $user = $this->_user_info;
            if (strtotime($user->created_at) > $start_time) {
                $old = DB::table('user_first_visit_pay_page')->where('uid', $this->uid)->select('uid', 'template_type')->first();
                if ($old) {
                    $template_id = $old->template_type;
                    if($template_id) return $template_id;
                }
                if ($bid && $bid == 1148) {
                    $template_id = $this->uid % 2 == 0 ? 2 : 1;
                    if (empty($old)) {
                        try {
                            DB::table('user_first_visit_pay_page')->insert([
                                'uid' => $this->uid,
                                'template_type' => $template_id,
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s')
                            ]);
                        } catch (\Exception $e) {
                        }
                    }
                }
            }
        }
        return $template_id;
    }

    private function templateCompare(){
        //if(!in_array($this->distribution_channel_id,[2,14,211,155,4427,4488,256,691,146,255,722,4364,5,202,318,4237,266,196,273,4236,148,8,4241,160,271,4053,123,4334,4487,4593,695,4025,4426,4174])){
        /*$start_time = env('TEMPLATE_COMPARE_START_TIME_3',0);
        if(!$start_time){
            return 0;
        }*/
        if(!in_array($this->distribution_channel_id,[14,123,211,5,8,160,4236,4237,4241,374,243,244,245,320,321,324,337,338,538,539,751,752,753,754,4331,4384,4578,4580,4768,4769,4778,130,163,164,165,166,4126])){
            return 0;
        }

        //$user = $this->_user_info;
        /*if(strtotime($user->created_at) < $start_time){
            return 0;
        }*/
        $template_id = 0;
        $user = DataAnalysisSelectUserService::getByUidAndType($this->uid,'TEMPLATE_COMPARE_V3');
        if($user){
            $template_id = $user->attach;
        }

        return $template_id;
    }


    private function templateCompareV2(){
        $start_time = env('TEMPLATE_COMPARE_START_TIME',0);
        if(!$start_time){
            return 0;
        }

        if(!in_array($this->distribution_channel_id,[2,146 ,155 ,255 ,256 ,691 ,722 ,4364 ,695 ,4174 ,4025 ,4593 ,4426 ,4742 ,4053 ,4334 ,4487])){
            return 0;
        }
        $user = $this->_user_info;
        if(strtotime($user->created_at) < $start_time){
            return 0;
        }

        $user = DataAnalysisSelectUserService::getByUidAndType($this->uid,'TEMPLATE_COMPAREV2');
        if($user){
            $template_id = $user->attach;
        }else{
            $template_id = $this->uid % 2 == 0? 1:6;
            DataAnalysisSelectUserService::create(
                $this->uid,
                $this->distribution_channel_id,
                'TEMPLATE_COMPAREV2',
                -1, $template_id);
        }

        return $template_id;
    }

    private function maleSite($distribution_channel_id){
        $info = ChannelService::getChannelCompanyInfo($distribution_channel_id);
        //\Log::info('maleSite info is:');
        //\Log::info($info);
        if($info && isset($info->fans_gender)){
            if($info->fans_gender == 1){
                return 1;
            }
        }
        return 0;
    }

    private function appad(){
        if($this->force_subscribe_info){
            $force_subscribe_info = $this->force_subscribe_info;
        }else{
            $force_subscribe_info = $this->force_subscribe_info = ForceSubscribeService::forceSubscribeUsersByUid(['uid' => $this->uid]);
        }
        if(!$force_subscribe_info){
            return 0;
        }
        $force_sub_user_by_openid = ForceSubscribeUserIService::getForceSubscribeByUidOpenid($this->uid);
        if($force_sub_user_by_openid){
            $force_subscribe_info = $force_sub_user_by_openid;
        }
        if($force_subscribe_info->subscribe_time &&
            (time()-strtotime($force_subscribe_info->subscribe_time) >=3*86400)
            && !OrderService::isPaidUser($this->uid) &&
            !AdvertiseUserQueueService::getUserAdvertise($this->uid) &&
            in_array($this->distribution_channel_id,explode(',',env('ADS_OPEN_SITE')))
        ){
            return 1;
        }
        return 0;
    }
}