<?php

namespace App\Repositories\Customers;


use App\Exceptions\Api\ApiException;
use App\Modules\Enums\ErrorCode;
use App\Modules\Models\CouponOrder\CouponOrder;
use App\Modules\Models\CouponType\CouponType;
use App\Modules\Models\Customer\Customer;
use App\Modules\Models\WxGuide\WxGuide;
use App\Modules\Repositories\BaseRepository;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
/**
 * Class EloquentHistoryRepository.
 */
class CouponRepository extends BaseRepository
{

    /**
     * 验证手机号
     * @param $phone
     * @param $code
     * @return int
     */
    function validate($phone, $code)
    {
        $get_code = Redis::get($phone);
        if (!$get_code) {
            return 1;
        }
        if ($code != $get_code) {
            return 2;
        }
        return 3;
    }


    /**
     * 发放优惠券
     * @param $customer_id
     */


    function autoSend($customer_id)
    {
        $where = [
            'auto_send' => 1
        ];
        $coupons = CouponType::where($where)->get();//获取所有绑定手机优惠券
        $cout = count($coupons);
        if ($cout == 0) {
            throw new ApiException(ErrorCode::NO_AUTO_SEND, trans('api.error.no_auto_send'));
        }
        $coupon = $coupons[rand(0, $cout - 1)];
        $coupon_order = new  CouponOrder();
        $coupon_order->coupon_type_id = $coupon->id;
        $coupon_order->customer_id = $customer_id;
        $coupon_order->expire_time = date("Y-m-d", strtotime("+ $coupon->schedule_time day"));
        $coupon_order->status = 1;
        $coupon_order->add_time = date('Y-m-d H:i:s');
        $coupon_order->save();

        $data = [
            'full' => $coupon->discount,
            'discount_money' => $coupon->discount_money,
            'expire_time' => $coupon_order->expire_time,
        ];
        return $data;


    }

    function updatePhone($customer_obj, $phone)
    {
        $customer_obj->phone = $phone;
        $customer_obj->save();
    }

    function myAllRecord($customer_id)
    {
        return CouponOrder::where('customer_id', $customer_id)->rightjoin('coupon_type', 'coupon_order.coupon_type_id', '=', 'coupon_type.id')->get();
    }

    function recordFormat($record_obj)
    {

        $available = [];
        $has_used = [];
        $expire = [];

        if ($record_obj != null) {
            foreach ($record_obj as $coupon_obj) {

                $data['expire_time'] = $coupon_obj->expire_time;
                $data['full'] = $coupon_obj->discount;
                $data['discount_money'] = $coupon_obj->discount_money;

                switch ($coupon_obj->status) {
                    case 1:
                        if ($coupon_obj->expire_time <= date('Y-m-d H:i:s')) {
                            $expire[] = $data;
                        } else {
                            $available[] = $data;
                        }
                        break;
                    case 2:

                        $has_used[] = $data;
                        break;
                    default:
                        break;
                }
            }
        }

        return ['available' => $available, 'has_used' => $has_used, 'expire' => $expire];


    }

    /**
     * @param $qrCode
     * @return mixed
     */
    public function checkBinder($qrCode)
    {
        $where = [
            'qrcode' => $qrCode
        ];
        $data = WxGuide::where($where)->first();

        if (!$data) {
            throw new ApiException(ErrorCode::COUPON_QRCODE_INVALID, trans('api.error.coupon_qrcode_invalid'));
        }

        return $data;
    }

    /**
     * @param $uid
     * @param $qrCode
     * @return mixed
     */
    public function doCouponBind($uid, $qrCode, $oid)
    {
        $lock = Redis::setnx('COUPON_QRCODE_BIND' . $qrCode, date("Y-m-d H:i:s"));

        if ($lock == 1) {
            //如果无人在取货，（获得锁成功）设置锁5秒自动删除
            Redis::expire('COUPON_QRCODE_BIND' . $qrCode, 5);
        } else {
            return 1;//绑定失败 正在绑定操作
        }

        $where = [
            'qrcode' => $qrCode
        ];
        $data = WxGuide::where($where)->first();
        if (!$data) {
            throw new ApiException(ErrorCode::COUPON_QRCODE_INVALID, trans('api.error.coupon_qrcode_invalid'));
        }
        $expireDate = date("Y-m-d", strtotime("+$data->expire_time day", strtotime($data->created_at)));
        $nowDate = date('Y-m-d');
        if ($expireDate < $nowDate) { //检测是否过期
            throw new ApiException(ErrorCode::COUPON_EXPIRE, trans('api.error.coupon_expire'));
        }

        if ($data->user_id) {
            if($data->user_id != $uid){
                return 2;//绑定失败 已被他人绑定
            }else{
                return 3;//绑定失败 您已绑定
            }
        }else{
            //绑定操作
            DB::beginTransaction();
            try {
                $res = WxGuide::where($where)->update(['user_id'=>$uid]);
                $r = Customer::where('id', $uid)->update(['openid'=>$oid]);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                throw new ApiException(ErrorCode::DATABASE_ERROR, trans('api.error.database_error'));
            }

            return 4;//绑定成功

        }

    }

    /**
     * @param $uid
     * @param $qrCode
     * @return int
     * @throws ApiException
     */
    public function doGetCoupon($uid, $qrCode)
    {
        $lock = Redis::setnx('COUPON_QRCODE_GET' . $qrCode.$uid, date("Y-m-d H:i:s"));

        if ($lock == 1) {
            //如果无人在取货，（获得锁成功）设置锁3秒自动删除
            Redis::expire('COUPON_QRCODE_GET' . $qrCode.$uid, 3);
        } else {
            return 1;//正在领取操作
        }

        $where = [
            'qrcode' => $qrCode
        ];
        $data = WxGuide::where($where)->first();

        if (!$data || !$data->user_id) {
            throw new ApiException(ErrorCode::COUPON_QRCODE_INVALID, trans('api.error.coupon_qrcode_invalid'));
        }

        $expireDate = date("Y-m-d", strtotime("+$data->expire_time day", strtotime($data->created_at)));
        $nowDate = date('Y-m-d');

        if ($expireDate < $nowDate) { //检测是否过期
            throw new ApiException(ErrorCode::COUPON_EXPIRE, trans('api.error.coupon_expire'));
        }

        $res = CouponOrder::firstOrNew(['wx_guide_id'=>$data->id, 'customer_id'=>$uid],
            [
                'spot_id'=>$data->spot_id,
                'business_id'=>$data->business_id,
                'coupon_type_id'=>$data->coupon_type_id,
                'wx_guide_id'=>$data->id,
                'customer_id'=>$uid,
                'status'=>1,
                'add_time'=>date('Y-m-d H:i:s'),
                'expire_time'=>$expireDate
        ]);

        if ($res->exists) {
            // already exists
            return 2;
        } else {
            // created from 'new'; does not exist in database.
            $r = $res->save();
            if($r){
                return 3;
            }else{
                return 4;
            }
        }

    }

    public function doCouponInfo($qrCode)
    {
        $where = [
            'qrcode' => $qrCode
        ];
        $data = WxGuide::where($where)->first();
        $expireDate = date("Y-m-d", strtotime("+$data->expire_time day", strtotime($data->created_at)));

        $datas = CouponOrder::select('coupon_order.wx_guide_id', 'coupon_order.status', DB::raw('COUNT(coupon_order.status) as num'))
            ->where('coupon_order.wx_guide_id', $data->id)
            ->groupBy('coupon_order.status', 'coupon_order.wx_guide_id')
            ->get()
            ->toArray();
        $totalNum = 0;
        $usedNum = 0;

        foreach ($datas as $da){
            if($da['status'] == 1){
                $totalNum += $da['num'];
            }elseif($da['status'] == 2){
                $totalNum += $da['num'];
                $usedNum += $da['num'];
            }
//            $extime = $da['expire_time'];
        }

        $res['todayMoney'] = $totalNum * $data['bonus'] * 0.01;
        $res['totalNum'] = $totalNum;
        $res['usedNum'] = $usedNum;
        $res['expireTime'] = $expireDate;
        $res['bonus'] = $data['bonus'] * 0.01;
//        $res['expireTime'] = '2018-10-30';

        return $res;
    }

    public function doCouponTypeInfo($qrCode)
    {
        $data = WxGuide::select('coupon_type.discount_money')
            ->leftjoin('coupon_type', 'coupon_type.id', '=', 'wx_guide.coupon_type_id')
            ->where('wx_guide.qrcode', $qrCode)
            ->first();

        return $data->discount_money;

    }

}
