<?php

namespace App\Http\Controllers\Wap\Order;

use App\Modules\Book\Services\BookGiftsService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Subscribe\Models\Order;
use App\Http\Controllers\Wap\BaseController;
use App\Modules\Book\Services\BookConfigService;
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\UserDivisionCpcPropertyService;
use App\Modules\User\Services\UserDivisionPropertyService;
use App\Modules\User\Services\UserGiftService;
use App\Modules\User\Services\UserMonthService;
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;
use Cookie;

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

    private $force_subscribe_info;

    private $chargeList;


    /**
     * @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');
        }

        $bid = $request->input('bid', '');
        $temp = $bid;
        $template_id = PayTemplateService::getPayTemplate($this->distribution_channel_id);

        $book_config = null;
        if ($bid) {
            $bid = Hashids::decode($bid)[0];
            $book_config = BookConfigService::getBookById($bid);
        }
        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 ($book_config) {
                    if ($book_config->charge_type == 'BOOK') $template_id = 1;
                }
            }
        }

        //男频站点 支付模板
        if (($male_site_template = $this->maleSite($this->distribution_channel_id))) {
            $template_id = $male_site_template;
        }

        /*if($book_config && $book_config->charge_type == 'BOOK'){
            if( ($compare_id = $this->templateCompareV3()) ){
                $template_id = $compare_id;
            }
        }*/
        /*if( ($compare_id = $this->templateCompare()) ){
            $template_id = $compare_id;
        }*/

        /*if( ($comparev2_id = $this->templateCompareV2()) ){
            $template_id = $comparev2_id;
        }
        $template_10_site = redisEnv('TEMPLATE_10_NO_AB_TEST_SITE','');
        if($template_10_site && in_array($this->distribution_channel_id,explode(',',$template_10_site))  ){
            $template_id = 10;
        }*/
        $outstandingYearOrder = $this->outstandingYearOrder($this->uid);

        $res = ProductService::getChargeProduct($template_id);
        if (!$res) {
            return response()->error('WAP_SYS_ERROR');
        }
        $this->chargeList = $res;
        $this->exchangeList();
        /*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);

        $data = [];
        $appad = 0;

        $property = UserDivisionCpcPropertyService::getUserPropertyV2($this->uid);
        $user_info = $this->_user_info;
        $result = $this->monthAbTest($property,$user_info->openid);
        if($result == 0){$this->monthPayExposureRecord($property,$user_info->openid);}
        $this->monthPayExposureRecordOther();
        foreach ($res as $v) {
            if ($template_id == 7 && $book_config && $book_config->charge_type == 'BOOK' && $v->price == 2) {
                continue;
            }
            if($template_id == 2 && $v->type == 'NEW_USER' && !$bid){
                //2元模版,直接进充值,不出现
                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,
                    'is_month_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,
                    'gift' => BookGiftsService::chargeGiveGift($property, $v->price, $v->type)
                ];
                $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,
                    'is_month_order' => 0,
                    'text' => $text,
                    'first_charge' => false,
                    'today_special' => $outstandingYearOrder,
                    'save_text' => $save_text,
                    'product_id' => $v->id,
                    'show_free_ads' => $appad,
                    'gift' => BookGiftsService::chargeGiveGift($property, $v->price, $v->type)
                ];
                $data[] = $temp;
            } /*elseif ($v->type == 'MOUTH') {
                if (!$property) $property = 'low';
                if (in_array($this->distribution_channel_id, explode(',', redisEnv('INNER_SITES')))
                    && in_array($property, ['low', 'medium'])
                ) {
                    $data[] = [
                        'price' => (int)$v->price . '元',
                        'is_year_order' => 0,
                        'is_month_order' => 1,
                        'text' => sprintf('%s元包月 全站万本精彩小说免费看', (int)$v->price),
                        'first_charge' => false,
                        'today_special' => false,
                        'save_text' => '每月自动续费,可随时关闭',
                        'product_id' => $v->id,
                        'show_free_ads' => false,
                        'link' => generateMonthOrderUrl($this->uid),
                        'gift' => BookGiftsService::chargeGiveGift($property, $v->price, $v->type)
                    ];
                } else {
                    continue;
                }
            }*/ 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,
                    'is_month_order' => 0,
                    'text' => $text,
                    'first_charge' => false,
                    'today_special' => ($v->is_default == 1 && $outstandingYearOrder == false) ? true : false,
                    'save_text' => $save_text,
                    'product_id' => $v->id,
                    'show_free_ads' => $appad,
                    'gift' => BookGiftsService::chargeGiveGift($property, $v->price, $v->type)
                ];
                $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 = '解锁';
                $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;
        }

        $template_10_site = redisEnv('TEMPLATE_10_SITE', '');
        if (!$template_10_site) {
            return 0;
        }
        if (!in_array($this->distribution_channel_id, explode(',', $template_10_site))) {
            return 0;
        }

        $user = $this->_user_info;
        if (strtotime($user->created_at) < $start_time) {
            return 0;
        }

        $user = DataAnalysisSelectUserService::getByUidAndType($this->uid, 'TEMPLATE_COMPAREV10_2');
        if ($user) {
            return $user->attach;
        } else {
            if ($this->uid % 2 == 0) {
                DataAnalysisSelectUserService::create(
                    $this->uid,
                    $this->distribution_channel_id,
                    'TEMPLATE_COMPAREV10_2',
                    -1, 10);
                return 10;
            } else {
                DataAnalysisSelectUserService::create(
                    $this->uid,
                    $this->distribution_channel_id,
                    'TEMPLATE_COMPAREV10',
                    -1, 0);
                return 0;
            }

        }
    }

    //进入4593的心注册用户,若当前阅读的是短篇书籍,则根据注册id的奇偶分别进入AB两个充值模板。
    //测试3天(测试时长看数据分析组建议)后,分别统计两个模板下的用户数、付费用户数和充值总额.
    private function templateCompareV3()
    {
        $start_time = redisEnv('TEMPLATE_COMPARE_START_TIME', 0);
        if (!$start_time) {
            return 0;
        }

        $template_compare_sites = redisEnv('TEMPLATE_COMPARE_SITES', 0);

        if (!in_array($this->distribution_channel_id, explode(',', $template_compare_sites))) {
            return 0;
        }
        $user = $this->_user_info;
        if (strtotime($user->created_at) < $start_time) {
            return 0;
        }

        $user = DataAnalysisSelectUserService::getByUidAndType($this->uid, 'TEMPLATE_COMPAREV3');
        if ($user) {
            $template_id = $user->attach;
        } else {
            $template_id = $this->uid % 2 == 0 ? 1 : 9;
            DataAnalysisSelectUserService::create(
                $this->uid,
                $this->distribution_channel_id,
                'TEMPLATE_COMPAREV3',
                -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;
        }
        //\Log::info('force1:'.json_encode($force_subscribe_info));
        $force_sub_user_by_openid = ForceSubscribeUserIService::getForceSubscribeByUidOpenid($this->uid);
        if ($force_sub_user_by_openid) {
            $force_subscribe_info = $force_sub_user_by_openid;
            //\Log::info('force:'.json_encode($force_subscribe_info));
        }
        if ($force_subscribe_info->subscribe_time &&
            (time() - strtotime($force_subscribe_info->subscribe_time) >= 3 * 86400)
            && !OrderService::isPaidUserByOpenid($force_subscribe_info->openid) &&
            !AdvertiseUserQueueService::getUserAdvertise($this->uid) &&
            in_array($this->distribution_channel_id, explode(',', env('ADS_OPEN_SITE')))
        ) {
            return 1;
        }
        return 0;
    }

    private function outstandingYearOrder($uid)
    {
        /*if (!in_array($this->distribution_channel_id, explode(',', env('OUTSTANDING_YEAR_ORDER_SITE')))) {
            return false;
        }*/

        //$userDivisionProperty = UserDivisionPropertyService::getUserProperty($uid);
        //$userDivisionProperty = UserDivisionCpcPropertyService::getUserPropertyV2($uid);
        //if (!$userDivisionProperty) return false;

        //if ($userDivisionProperty != 'high') return false;

        /*if ($uid % 2 == 0) {
            $is_show_outstanding_year_order = true;
            $template_id = 1;
        } else {
            $is_show_outstanding_year_order = false;
            $template_id = 2;
        }*/

        $exist = DataAnalysisSelectUserService::getByUidAndType($uid, 'OUTSTANDING_YEAR_ORDER_V2');
        if ($exist) return true;

        return false;

        /*DataAnalysisSelectUserService::create(
            $uid,
            $this->distribution_channel_id,
            'OUTSTANDING_YEAR_ORDER_V2',
            -1, $template_id);
        return $is_show_outstanding_year_order;*/
    }

    public function exchangeList()
    {
        foreach ($this->chargeList as &$item) {
            if (!$item->switch_to) continue;
            $order = Order::where('uid', $this->uid)->where('status', 'PAID')->where('product_id', $item->id)->first();
            if ($order) {
                $change = ProductService::getProductSingle($item->switch_to);
                $item->id = $change->id;
                $item->price = $change->price;
                $item->given = $change->given;
            }
        }
    }

    public function monthPay(Request $request){
        \Log::info('monthPay url--------------');
        \Log::info($request->all());
        $uid = $this->uid;
        $count = OrderService::getUserChargeTimes($uid);
        $count = $count + 1;
        $send_order_id = 0;
        try {
            $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
        } catch (\Exception $e) {
        }
        $distribution_channel_id = $this->distribution_channel_id;
        $trade_no = date("YmdHis") . str_shuffle(hexdec(uniqid()));
        $send_order_name = '';
        if ($send_order_id) {
            $send_order_info = SendOrderService::getById($send_order_id);
            if ($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)) {
                $send_order_name = $send_order_info->name;
            }
        }
        $init_order = [
            'distribution_channel_id' => $distribution_channel_id,
            'uid' => $uid,
            'product_id' => 6826,
            'price' => 30,
            'pay_type' => $count,
            'trade_no' => $trade_no,
            'pay_merchant_source' => 'MONTH',
            'pay_merchant_id' => 99,
            'create_ip' => '',
            'send_order_id' => $send_order_id,
            'send_order_name' => $send_order_name,
            'order_type' => 'RECHARGE',
            'from_bid' => '0',
            'from_type' => 'auto_month',
            'activity_id' => 0,
            'inner_send_order_id' => '',
            'status'=>'UNPAID',
            'transaction_id'=>''
        ];
        $init_order['pay_end_at'] = '0000-00-00 00:00:00';
        $info = Order::create($init_order);
        return redirect()->to(generateMonthOrderUrl($info->id));
    }

    private function monthPayExposureRecordOther(){
        $month_info = UserMonthService::getOrderAndSignStatusByUid($this->uid);
        if($month_info){
            if(in_array('MONTH',$month_info)){
                DB::table('user_month_visit_record')->insert([
                    'uid'=>$this->uid,'day'=>date('Y-m-d'),
                    'type'=>'MONTH',
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }
            else{
                DB::table('user_month_visit_record')->insert([
                    'uid'=>$this->uid,'day'=>date('Y-m-d'),
                    'type'=>'WEEK',
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }
        }
    }
    private function monthPayExposureRecord($property,$openid){
        if (!$property) return '';
        if (in_array($this->distribution_channel_id, explode(',', redisEnv('OPEN_ORDER_INNER_SITES')))
            && in_array($property, ['none','low', 'medium'])
        ) {
            if(!UserMonthService::isSignMonth($openid)){
                try{
                    if(in_array($property,['low','medium'])){
                        $type = 'MONTH';
                    }else{
                        $type = 'WEEK';
                    }
                    DB::table('user_month_visit_record')->insert([
                        'uid'=>$this->uid,'day'=>date('Y-m-d'),
                        'type'=>$type,
                        'created_at'=>date('Y-m-d H:i:s'),
                        'updated_at'=>date('Y-m-d H:i:s')
                    ]);
                }catch (\Exception $e){}
            }
        }
        return '';
    }

    private function monthAbTest($property,$openid){
        $start_time = redisEnv('MONTH_TEMPLATE_COMPARE_START_TIME', 0);
        if (!$start_time) {
            return 0;
        }

        $user = $this->_user_info;
        if (strtotime($user->created_at) < $start_time) {
            return 0;
        }

        if (in_array($this->distribution_channel_id, explode(',', redisEnv('OPEN_ORDER_INNER_SITES')))
            && in_array($property, ['none','low', 'medium'])
        ) {
            $exist = DataAnalysisSelectUserService::getByUidAndType($this->uid, 'MONTH_V2');
            if ($exist) {
                $attach = $exist->attach;
                if($attach == 'week-show' || $attach == 'show'){
                    $ret = 0;
                }else{
                    $ret = -1;
                }
                return $ret;
            }
            if(!UserMonthService::isSignMonth($openid)){
                if($property == 'none'){
                    $attach = $this->uid %2 == 0 ? 'week-show':'week-hide';
                }else{
                    $attach = $this->uid %2 == 0 ? 'show':'hide';
                }
                if($attach == 'week-show' || $attach == 'show'){
                    $ret = 0;
                }else{
                    $ret = -1;
                }

                DataAnalysisSelectUserService::create(
                    $this->uid,
                    $this->distribution_channel_id,
                    'MONTH_V2',
                    -1, $attach);
                return $ret;
            }
        }
        return -1;
    }
}