<?php

namespace Modules\User\Http\Controllers\Api\Identity;

use App\Api\Controllers\Controller;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jason\Api\Api;
use Modules\User\Http\Resources\IdentityMiddleResource;
use Modules\User\Http\Resources\UserAndIdentityResource;
use Modules\User\Http\Resources\UserIdentityBaseResource;
use Modules\User\Http\Resources\UserIdentityResource;
use Modules\User\Models\Identity;
use Modules\User\Models\Order;
use Modules\User\Models\User;
use Validator;

class IndexController extends Controller
{

    public function index(): JsonResponse
    {
        $user = Api::user();
        $list = Identity::where('can_buy', 1)->get();
        $vips = User::query()
            ->whereHas('identities', function ($q) {
                $q->where('order', '>', 1);
            })
            ->take(10)
            ->get();
        $data = [
            'vips'       => UserAndIdentityResource::collection($vips),
            'identities' => UserIdentityBaseResource::collection($list),
        ];

        return $this->success($data);
    }

    /**
     * Notes: 获取可开通的身份
     *
     * @Author: 玄尘
     * @Date  : 2021/6/4 9:37
     * @param  Identity  $identity
     * @return JsonResponse
     */
    public function create(Identity $identity): JsonResponse
    {
        $user     = Api::user();
        $ended_at = '';
        //可开通的身份ids
        $ids              = Identity::where('can_buy', 1)->pluck('id')->toArray();
        $identity_middles = $user->identityMiddle;

        //是否可以前台开通
        if (in_array($identity->id, $ids)) {
            //有有效期
            if ($identity->years) {
                //已经开通的身份ids
                $identity_ids = $identity_middles->pluck('identity_id')->toArray();
                //是否已经开通了此身份
                if (in_array($identity->id, $identity_ids)) {
                    $ended_at = $identity_middles->where('identity_id', $identity->id)
                        ->first()->ended_at ?? now()->format('Y-m-d H:i:s');

                    $ended_at = Carbon::parse($ended_at)->addMonths($identity->years)->format('Y/m/d');
                } else {
                    $ended_at = now()->addMonths($identity->years)->format('Y/m/d');
                }
            } else {
                $ended_at = '永久';
            }

        }

        $price = $identity->getCondition('price', '0');
        $cost  = $identity->getCondition('cost', '0');
        if (! $cost) {
            $cost = $price;
        }


        $data = [
            'identity' => [
                'identity_id'  => $identity->id,
                'name'         => $identity->name,
                'cover'        => $identity->cover_url,
                'description'  => $ended_at ? '有效期至'.$ended_at : $identity->description,
                'cost'         => $cost,
                'price'        => $price,
                'can_buy'      => (bool) $identity->can_buy,
                'ended_at'     => $ended_at,
                'service'      => config('user.experience.service'),
                'protocol_url' => (string) $identity->protocol_url,//协议地址
            ],
        ];

        return $this->success($data);

    }

    /**
     * Notes: 开通会员
     *
     * @Author: 玄尘
     * @Date  : 2021/6/4 10:02
     * @param  Identity  $identity
     * @param  Request  $request
     * @return JsonResponse
     */
    public function store(Identity $identity, Request $request): JsonResponse
    {
        $user = Api::user();

        $price     = $request->price ?? 0;
        $validator = \Validator::make($request->all(), [
            //            'name'  => 'required',
            //                'card_no' => 'required|numeric',
            'cover' => 'required',
            'price' => 'required',
        ], [
            'name.required'    => '缺少姓名',
            'card_no.required' => '缺少银行卡号',
            'card_no.numeric'  => '银行卡号只能是数字',
            'cover.required'   => '缺少打款凭证',
            'price.required'   => '缺少打款金额',
        ]);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }


        if (! $identity->can_buy) {
            return $this->failed('当前身份不可开通,请联系客服开通。');
        }

        $type = Order::TYPE_OPEN;
        $year = $request->year ?? 1;
        //是否可以开通多身份 false不可
        if (config('identity.can_has_many_identity') == false) {
            if ($user->identities->isNotEmpty()) {
                $this_identity = $user->identities->first();

                if ($this_identity->order > $identity->order) {
                    return $this->failed('不可降级开通');
                }

                if ($this_identity->id == $identity->id) {
                    $type = Order::TYPE_RENEW;
                }

            }
        }


        $hasOne = Order::query()
            ->byUser($user)
            ->where('identity_id', $identity->id)
            ->where('state', Order::STATE_INIT)
            ->exists();

        if ($hasOne) {
            return $this->failed('您已经提交过了，请等待审核');
        }


        if (! $price) {
            $price = $identity->getCondition('price', '0');
            $price = $price * $year;
        }

        $data = [
            'user_id'     => $user->id,
            'identity_id' => $identity->id,
            'year'        => $year,
            'type'        => $type,
            'stock'       => $identity->stock,
            'name'        => $request->name,
            'card_no'     => $request->card_no,
            'cover'       => $request->cover,
            'state'       => Order::STATE_INIT,
            'price'       => $price,
        ];

        $order = Order::create($data);

        if ($order) {
            return $this->success('提交成功，请等待后台审核');
        } else {
            return $this->failed('创建订单失败，请稍后再试');
        }
    }

    /**
     * Notes: 微信支付
     *
     * @Author: 玄尘
     * @Date  : 2021/6/7 14:42
     * @param  Order  $order
     * @return JsonResponse
     * @throws Exception
     */
    public function wechat(Order $order, Request $request): JsonResponse
    {
        $channel = $request->channel ?? 'mp';
        $openid  = $request->openid ?? '';

        $user = Api::user();

        if (! $order->canPay()) {
            return $this->failed('支付失败，订单不可支付');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('支付失败，您没有权限支付');
        }

        $extends = [
            'notify_url' => route('api.payment.notify.wechat'),
        ];

        if (! $openid) {
            $openid = $user->wechat->getUserOpenid($channel);
        }

        $payment = $order->createWechatPayment($user, $order->price, $channel);
        if (! $openid) {
            return $this->failed('支付失败，缺少openid');
        }

        if (config('payment.version', 2) == 2) {
            $extends = array_merge($extends, [
                'openid' => $openid,
            ]);
        } else {
            $extends = array_merge($extends, [
                'payer' => [
                    'openid' => $openid,
                ],
            ]);
        }

        $notify = $payment->getPaymentParams('商品下单', $extends);

        if (config('payment.version', 2) == 2) {
            $notify = $notify->getContent();
        } else {
            $notify = $notify->toJson();
        }

        $data = [
            'wechat'   => $notify,
            'identity' => [
                'identity_id' => $order->identity_id,
                'name'        => $order->identity->name,
            ],
        ];

        return $this->success($data);
    }

    /**
     * Notes: 支付宝支付
     *
     * @Author: 玄尘
     * @Date  : 2021/6/7 14:42
     * @param  Order  $order
     * @return JsonResponse
     * @throws Exception
     */
    public function alipay(Order $order): JsonResponse
    {
        $user = Api::user();

        if (! $order->canPay()) {
            return $this->failed('支付失败，订单不可支付');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('支付失败，您没有权限支付');
        }

        $payment = $order->createAlipayPayment($user, $order->price, 'app');

        $notify = $payment->getPaymentParams('商品下单', [
            'notify_url' => route('api.payment.notify.alipay'),
        ]);

        $data = [
            'wechat'   => $notify->getContent(),
            'identity' => [
                'identity_id' => $order->identity_id,
                'name'        => $order->identity->name,
            ],
        ];

        return $this->success($data);

    }

    /**
     * Notes: 根据不同身份判定用户折扣
     *
     * @Author: Mr.wang
     * @Date  : 2021/6/10 11:00
     * @return JsonResponse
     */
    public function rule(): JsonResponse
    {
        $user            = Api::user();
        $defaultIdentity = Identity::orderBy('order', 'desc')->first();
        $defaultDiscount = $defaultIdentity->getRule('buy_discount', 0);
        if (! $user) {
            return $this->success([
                'message'  => '开通节点 最高享'.($defaultDiscount / 10).'折优惠',
                'not_vip'  => true,
                'discount' => $defaultDiscount / 100,
            ]);
        }

        $identity = $user->identities->first();
        $discount = $identity->getRule('buy_discount', 0);
        if ($discount >= 100) {
            $message = '开通节点 最高享'.($defaultDiscount / 10).'折优惠';
        } else {
            $message = $identity->name.'尊享'.($discount / 10).'折优惠';
        }

        return $this->success([
            'message'  => $message,
            'not_vip'  => (bool) $identity->default,
            'discount' => $discount / 100,
        ]);
    }

    /**
     * Notes: 获取身份权益
     *
     * @Author: 玄尘
     * @Date  : 2021/6/8 8:39
     * @param  Identity  $identity
     * @return JsonResponse
     */
    public function show(Identity $identity): JsonResponse
    {
        return $this->success(new UserIdentityResource($identity));
    }

}
