<?php
/**
 * 获取用户的充值模板
 */

namespace App\Modules\User\Services;

use App\Consts\ErrorConst;
use App\Libs\Utils;
use App\Modules\SendOrder\Models\QappSendOrder;
use App\Modules\User\Models\User;
use App\Modules\Trade\Models\Order as TradeOrder;
use App\Modules\User\Models\QappChannelAccount;
use App\Modules\Product\Models\QappChargeTemplate;
use App\Modules\Product\Models\Product;
use App\Modules\Subscribe\Services\OrderService;

class UserChargeService
{
    /**
     * 派单id是使用阅读记录里的；
     * @param  [type] $uid           [description]
     * @param  [type] $send_order_id [description]
     * @return [type]                [description]
     */
    public static function getTemplate($uid,$send_order_id,$distribution_channel_id){
        //获取模板id
        $template_id = self::selectTemplate($uid,$send_order_id);

        if($template_id == 0){
            //official
            $ids = env('OFFICIAL_TEMPLATE_IDS');
            $idarr = explode(',',$ids);
            $products = Product::whereIn('id',$idarr)->where('is_enabled',1)->orderBy('sequence','asc')->get();
        }else{
            $template_info = QappChargeTemplate::where('id',$template_id)->first();
            if (getProp($template_info,'is_official') == 1) {
                //属于官方模板 直接根据id 从 product表里查找
                $idarr = explode(',',getProp($template_info,'product_ids'));
                $products = Product::whereIn('id',$idarr)->where('is_enabled',1)->orderBy('sequence','asc')->get();
            }else{
                $products = Product::where('qapp_charge_template_id',$template_id)->where('is_enabled',1)->orderBy('sequence','asc')->get();
            }
        }
        $is_first_recharge = OrderService::judgeUserFirstRecharge($uid);
        $data = [];
        foreach ($products as $key => $v) {
            $text = '';
            if ($v->type == 'NEW_USER' && $is_first_recharge) {
                if (
                    env('NO_NEW_USER_CHARGE') &&
                    in_array(
                        $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),
                    'today_special'  => $v->is_default,
                    'first_charge'   => true,
                    'save_text'      => round($v->given / 100, 1) . '元',
                    'product_id'     => $v->id,
                ];
                $data[] = $temp;
            } elseif ($v->type == 'YEAR_ORDER') {
                $save_text = '年费vip会员';
                $text      = '全年免费看';
                $temp      = [
                    'price'          => (int)$v->price . '元',
                    'is_year_order'  => 1,
                    'is_month_order' => 0,
                    'text'           => $text,
                    'today_special'  => $v->is_default,
                    'first_charge'   => false,
                    'save_text'      => $save_text,
                    'product_id'     => $v->id,
                ];
                $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,
                    'is_month_order' => 0,
                    'text'           => $text,
                    'today_special'  => $v->is_default,
                    'first_charge'   => false,
                    'save_text'      => $save_text,
                    'product_id'     => $v->id,
                ];
                $data[] = $temp;
            }
        }
        return $data;

    }
    /**
     * 判断选择用哪个模板id
     * @param  [type] $uid           [description]
     * @param  [type] $send_order_id [description]
     * @return [type]                [description]
     */
    public static function selectTemplate($uid,$send_order_id){
        $default_template_id = 0;
        if (!$send_order_id) {
            return $default_template_id;
        }
        $user_order_num = TradeOrder::where('uid', $uid)->where('status', 'PAID')->orderBy('id')->count();
        $qappSendOrder = QappSendOrder::getSendOrderById($send_order_id);
        $first_charge_template_id       = getProp($qappSendOrder, 'first_charge_template_id');
        $second_charge_template_id       = getProp($qappSendOrder, 'second_charge_template_id');
        //找该派单的建立者设置的默认模板
        $account = getProp($qappSendOrder, 'account');
        $account_info = QappChannelAccount::getByAccount($account);
        if ($user_order_num == 0) {
            //若该派单设置了模板
            if($first_charge_template_id) return $first_charge_template_id;

            //找该派单的建立者设置的默认模板
            $account_info = QappChannelAccount::getByAccount($account);
            $template_id = QappChargeTemplate::where('qapp_channel_account_id',getProp($account_info, 'id'))
                            ->where('type','first_charge')
                            ->where('is_default',1)
                            ->value('id');
            if ($template_id) {
                return $template_id;
            }
            //如果设置了非首冲，则返回非首冲
            if($second_charge_template_id) return $second_charge_template_id;

            if(!$template_id){
                //无默认首冲模板，找非首冲默认模板
                $template_id = QappChargeTemplate::where('qapp_channel_account_id',getProp($account_info, 'id'))
                            ->where('type','second_charge')
                            ->where('is_default',1)
                            ->value('id');
            }
            return $template_id > 0 ? $template_id : $default_template_id;
        }
        if ($user_order_num > 0) {
            //不是首单
            if($second_charge_template_id) return $second_charge_template_id;
            //无派单非首冲模板，找非首冲默认模板
            $template_id = QappChargeTemplate::where('qapp_channel_account_id',getProp($account_info, 'id'))
                        ->where('type','second_charge')
                        ->where('is_default',1)
                        ->value('id');
            
            return $template_id > 0 ? $template_id : $default_template_id;
        }
    }

    
}