<?php

namespace App\Services\WeChatApplet\user;

use App\Services\CommonService;
use App\Services\LoginUserService;
use Illuminate\Database\Eloquent\Model;
use App\Models\WeChatApplet\User\MemberLevel;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\WeChatApplet\User\MemberLevelValidator;
use App\Services\WeChatApplet\User\WeixinUserService;
use App\Services\Business\MemberLevelService as levelService;
use App\Services\ReceivablePay\ReceivablePayService;

// 用户会员等级
class MemberLevelService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new MemberLevel();
        $this->mainValidator = new MemberLevelValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    // 详情
    public static function info($search_data)
    {
        $user_info = LoginUserService::getUser('wechatWash');
        $count = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->count();
        if($count <= 0){
            return ['code'=>500, 'msg'=>'暂未开通会员', 'data'=>''];
        }
        //用户信息
        $mem = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_shop_id', $user_info->adm_shop_id)
            ->where('mem_id', $user_info->ussh_user_id)
            ->first();
        //当前经验值
        $mem_value = self::currentExperience($user_info);
        $black_diamond = '';//黑钻价格
        $level_img_arr = self::levelImg();
        $level_text_arr = self::levelText($user_info);
        $now_level = 0;
        $black_term = '';
        $is_black = 2;
        //判断是否过期
        if($mem->mem_level == 5 && $mem->mem_level_end_time < date('Y-m-d H:i:s') && $mem->mem_level_length != '永久有效'){
            $gq_mem = DB::table('member')
                ->where('mem_cid', $user_info->adm_cid)
                ->where('mem_shop_id', $user_info->adm_shop_id)
                ->where('mem_id', $user_info->ussh_user_id)
                ->update(['mem_level'=>0,'mem_level_start_time'=>'','mem_level_end_time'=>'']);
            $gq_goods = DB::table('member_level_goods')
                ->where('memlg_cid', $user_info->adm_cid)
                ->where('memlg_shop_id', $user_info->adm_shop_id)
                // ->where('memlg_meml_id', 5)
                ->get()->toArray();
            $gq_memg_id = array_column($gq_goods,'memlg_goo_id');
            $ret = DB::table('member_goods')
                ->where('memg_cid', $user_info->adm_cid)
                ->where('memg_shop_id', $user_info->adm_shop_id)
                ->where('memg_mem_id', $user_info->ussh_user_id)
                // ->where('memg_meml_id', 5)
                ->whereIn('memg_id', $gq_memg_id)
                ->update(['memg_status'=>3]);
        }
        //用户对应的各等级信息
        $level = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->select('meml_id','meml_name','meml_total_amount','meml_price','meml_level','meml_forever','meml_effect_length')
            ->orderBy('meml_level','ASC')
            ->get()->toArray();
        $level_show = [];
        $goods_member = DB::table('member_goods')
            ->where('memg_cid', $user_info->adm_cid)
            ->where('memg_shop_id', $user_info->adm_shop_id)
            ->where('memg_mem_id', $user_info->ussh_user_id)
            ->select('memg_pic as memlg_pic','memg_goo_type_name as memlg_goo_type_name','memg_goo_name as memlg_goo_name','memg_goo_type as memlg_goo_type','memg_goo_id as memlg_goo_id','memg_meml_id as memlg_meml_id')
            ->get()->toArray();
        if($goods_member){
            $goods_member = CommonService::dataToArray($goods_member);
            $goods_member = CommonService::jointArrayKey($goods_member, 'memlg_meml_id',2);
        }
        foreach ($level as $key => $value){
            $level_show[] = $value->meml_level;
            $level[$key]->meml_img = $level_img_arr[$value->meml_level];
            $level[$key]->meml_text = $level_text_arr[$value->meml_level];
            $level[$key]->meml_is_use_goods = 1;//是否可以使用赠礼，1不可以 2可以

            if(isset($goods_member[$value->meml_id])){
                $level_goods = $goods_member[$value->meml_id];
            }else {
                $level_goods = DB::table('member_level_goods')
                    ->where('memlg_cid', $user_info->adm_cid)
                    ->where('memlg_shop_id', $user_info->adm_shop_id)
                    ->where('memlg_meml_id', $value->meml_level)
                    ->get()->toArray();
                $level_goods = CommonService::dataToArray($level_goods);
            }
            foreach ($level_goods as $lkey => $lvalue){
                if(empty($lvalue['memlg_pic'])){
                    $level_goods[$lkey]['memlg_pic'] = levelService::getGoodPic($lvalue['memlg_goo_type'],$lvalue['memlg_goo_id']);
                }
            }
            if($value->meml_total_amount <= $mem_value){
                $level[$key]->level_notice = '已达到该等级';
                if($value->meml_level != 5 && $mem->mem_level != 5){//会员不是黑钻，更新等级
                    $now_level = $value->meml_level;
                    $now_level_name = $value->meml_name;
                    $goods_list[$value->meml_level] = $level_goods;
                    $level[$key]->meml_is_use_goods = 2;
                }
            }else{
                $gap = ($value->meml_total_amount - $mem_value) / 100;
                $level[$key]->level_notice = '还差'.ceil($gap) .'升级' ;
            }
            $level[$key]->meml_total_amount = $value->meml_total_amount / 100;
            $level[$key]->goods = $level_goods;//赠礼商品列表
            if($value->meml_level == 5){
                $is_black = 1;
                $black_diamond = $value->meml_price / 100;
                $level[$key]->level_notice = '开通后立即生效';
                if($mem->mem_level == 5){//如果当前是黑钻会员
                    $level[$key]->meml_is_use_goods = 2;
                    if($mem->mem_level_end_time != '0000-00-00 00:00:00'){
                        $level[$key]->level_notice = '有效期到'.$mem->mem_level_end_time;
                    }
                    if($mem->mem_level_length == '永久有效'){
                        $level[$key]->level_notice = '永久有效';
                    }
                }
                if($value->meml_forever == 1){
                    $black_term = '永久有效';
                } else if($value->meml_forever == 2){
                    $black_term = $value->meml_effect_length.'个月';
                }
            }

        }
        //添加赠礼
        if(isset($goods_list) && !empty($goods_list)){
            $a = self::mem_add_goods($user_info,$goods_list,$now_level,$mem);
        }
        if(isset($now_level) && $mem->mem_id && $mem->mem_level != 5){
            $ret = DB::table('member')
                ->where('mem_cid', $user_info->adm_cid)
                ->where('mem_shop_id', $user_info->adm_shop_id)
                ->where('mem_id', $mem->mem_id)
                ->update(['mem_level'=>$now_level]);
        }
        if($mem->mem_level == 5){
            $now_level = 5;
            $now_level_name = '黑钻会员';
        }
        $show_level = 0;
        if($now_level>0){
            $show_level = array_search($now_level, $level_show);
            $show_level = $show_level + 1;
        }
        $data['data'] = $level;//等级信息
        $data['experience_value'] = intval($mem_value / 100);//当前经验值
        $data['is_black'] = $is_black;//黑钻
        $data['black'] = $black_diamond;//黑钻价格
        $data['black_term'] = $black_term;//黑钻有效期
        $data['now_level'] = $now_level;//当前等级id
        $data['show_level'] = $show_level;//等级展示
        $data['now_level_name'] = $now_level_name??'普通会员';//当前等级名称
        return ['code'=>200, 'msg'=>'成功', 'data'=>$data];
    }

    //列表
    public static function list(){
        $user_info = LoginUserService::getUser();
        $list = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->select('meml_id','meml_name','meml_total_amount')
            ->get()->toArray();
        //计算会员累计实付金额
        $all_price = self::currentExperience($user_info);
        //$list->amount = $all_price;
        foreach ($list as $key => $value){
            $list[$key]->gap = ceil($value->meml_total_amount - $all_price);
        }
        return ['code'=>200, 'msg'=>'成功', 'data'=>$list];
    }

    //获取当前经验值
    public static function currentExperience($user_info){
        $all_price = 0;
        $amount = DB::table('order')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->whereIN('ord_wor_state', [4,18,19,20])
            ->where('ord_delete', 1)
            ->where('ord_add_type', 1)
            ->where('ord_client_id', $user_info->ussh_user_id)
            /*->select(DB::raw('sum(ord_actual_price) as ord_actual_price'))
            ->first();*/
            ->select('ord_actual_price','ord_mem_price')
            ->get()->toArray();
            foreach ($amount as $key => $value){
                if($value->ord_mem_price > 0){
                    $price = $value->ord_mem_price;
                }else{
                    $price = $value->ord_actual_price;
                }
                $all_price += $price;
            }
        $value = intval($all_price);
        return $value;
    }

    //黑钻购买页面
    public static function blackInfo(){
        $user_info = LoginUserService::getUser();
        $data = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->where('meml_level', 5)//黑钻
            ->select('meml_id','meml_name','meml_price')
            ->get()->toArray();
        $level_goods = DB::table('member_level_goods')
            ->where('memlg_cid', $user_info->adm_cid)
            ->where('memlg_shop_id', $user_info->adm_shop_id)
            ->where('memlg_meml_id', 5)
            ->select('memlg_id','memlg_pic','memlg_goo_type_name','memlg_goo_name')
            ->get()->toArray();
        $data->goods = $level_goods;
        return ['code'=>200, 'msg'=>'成功', 'data'=>$data];
    }

    //添加赠礼
    public static function mem_add_goods($user_info,$goods_list,$now_level,$mem){
        for($i=1;$i<=$now_level;$i++) {
            if (isset($goods_list[$i])) {
                $goods_count = DB::table('member_goods')
                    ->where('memg_cid', $user_info->adm_cid)
                    ->where('memg_shop_id', $user_info->adm_shop_id)
                    ->where('memg_mem_id', $user_info->ussh_user_id)
                    ->where('memg_meml_id', $i)//等级id
                    ->count();
                if ($goods_count == 0) {//没有该等级对应得礼品
                    foreach ($goods_list[$i] as $key => $value) {
                        $add_data['memg_cid'] = $user_info->adm_cid;
                        $add_data['memg_shop_id'] = $user_info->adm_shop_id;
                        $add_data['memg_superior_shop_id'] = $user_info->adm_shop_id;
                        $add_data['memg_goo_type'] = $value['memlg_goo_type'];//类型
                        $add_data['memg_goo_type_name'] = $value['memlg_goo_type_name'];//类型名称
                        $add_data['memg_goo_id'] = $value['memlg_goo_id'];//商品id
                        $add_data['memg_goo_name'] = $value['memlg_goo_name'];//商品名称
                        $add_data['memg_meml_id'] = $value['memlg_meml_id'];//礼品对应的等级
                        $add_data['memg_mem_id'] = $user_info->ussh_user_id;//会员id
                        $add_data['memg_pic'] = $value['memlg_pic'];//商品封面图
                        $add_data['memg_status'] = 2;//1已使用2未使用
                        if ($mem->mem_level_end_time != '0000-00-00 00:00:00') {
                            $add_data['memg_use_end_time'] = $mem->mem_level_end_time;//有效截止时间
                        }
                        $add_data['memg_create_time'] = date('Y-m-d H:i:s');//添加时间
                        $ret_id = DB::table('member_goods')->insertGetId($add_data);
                    }
                }
            }
        }
        return ['code' => 200, 'msg' => '新增成功', 'data' =>''];

    }

    //礼品列表
    public static function goodsList(){
        $user_info = LoginUserService::getUser();
        $level_img_arr = self::levelImg();
        $level_arr = [1=>'白银会员',2=>'黄金会员',3=>'铂金会员',4=>'钻石会员',5=>'黑钻会员'];
        $data = DB::table('member_goods')
            ->where('memg_cid', $user_info->adm_cid)
            ->where('memg_shop_id', $user_info->adm_shop_id)
            ->where('memg_mem_id', $user_info->ussh_user_id)
            ->select('memg_id','memg_goo_type_name','memg_goo_name','memg_pic','memg_status','memg_meml_id','memg_use_end_time')
            ->get()->toArray();
        foreach ($data as $key => $value) {
            $data[$key]->memg_img = $level_img_arr[$value->memg_meml_id];
            $data[$key]->memg_text = $level_arr[$value->memg_meml_id].'特权';
        }
        if ($data) {
            return ['code' => 200, 'msg' => '成功', 'data' =>$data];
        } else {
            return ['code' => 200, 'msg' => '成功', 'data' => ''];
        }
    }

    //使用礼品
    public static function useLevelGoods($request){
        $user_info = LoginUserService::getUser();
        $data = DB::table('member_goods')
            ->where('memg_cid', $user_info->adm_cid)
            ->where('memg_shop_id', $user_info->adm_shop_id)
            ->where('memg_id', $request['memg_id'])//礼品id
            ->select('memg_goo_id as sigo_goo_id','memg_goo_type as sigo_goo_type','memg_status')
            ->first();
        if($data){
            if($data->memg_status == 1){
                return ['code' => 200, 'msg' => '已使用', 'data' => ''];
            }
            // 添加订单
            $poss['goods_data'] = json_decode(json_encode($data,true),true);
            $poss['weus_id'] = $request['weus_id'];
            $find_mem = DB::table('member')->where('mem_id', $user_info->ussh_user_id)->first();
            $poss['orcl_name'] = $find_mem->mem_name;
            $poss['orcl_phone'] = $find_mem->mem_phone;
            DB::beginTransaction();
            $res = WeixinUserService::addSignOrder($user_info, $poss, 12);
            if ($res['code'] == 200) {
                $goods_ret = DB::table('member_goods')
                    ->where('memg_cid', $user_info->adm_cid)
                    ->where('memg_shop_id', $user_info->adm_shop_id)
                    ->where('memg_id', $request['memg_id'])//礼品id
                    ->where('memg_status', 2)
                    ->update(['memg_status'=>1]);
                $ord_id =$res['data']['ord_id'];
                $order = DB::table('order')
                    ->where('ord_id', $ord_id)
                    ->first();
                $order = CommonService::dataToArray($order);
                $order['orcl_name'] = $find_mem->mem_name;
                $order['ord_order_price'] = 0;
                ReceivablePayService::addPay($ord_id,$order['ord_order_number'],1,$order['ord_client_id'],$user_info,[],$order,$order,NULL,2);
                if($goods_ret){
                    DB::commit();
                    return $res;
                }
            }
            DB::rollBack();
            return ['code' => 500, 'msg' => '操作失败', 'data' => ''];
        }else{
            return ['code' => 500, 'msg' => '操作失败', 'data' => ''];
        }
    }

    //购买黑钻
    public static function buyBlack($request){
        $user_info = LoginUserService::getUser();
        $count = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->count();
        if($count <= 0){
            return ['code'=>500, 'msg'=>'暂未开通会员', 'data'=>''];
        }
        //用户信息
        $mem = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_shop_id', $user_info->adm_shop_id)
            ->where('mem_id', $user_info->ussh_user_id)
            ->first();
        $level_img_arr = self::levelImg();
        $level = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->where('meml_level', 5)
            ->select('meml_id','meml_name','meml_total_amount','meml_price','meml_level')
            ->first();
        $level_goods = DB::table('member_level_goods')
            ->where('memlg_cid', $user_info->adm_cid)
            ->where('memlg_shop_id', $user_info->adm_shop_id)
            ->where('memlg_meml_id', $level->meml_id)
            ->get()->toArray();
        //下单
        $level = CommonService::dataToArray($level);
        $level['meml_price'] = $level['meml_price'] / 100;
        $level['orcl_name'] = $mem->mem_name;
        $level['orcl_phone'] = $mem->mem_phone;
        $level['ord_client_id'] = $user_info->ussh_user_id;
        //$res = levelService::addOrder($user_info,$level,2);
        $level['goods'] = $level_goods;//赠礼商品列表
        $black_diamond = $level['meml_price'];

        if($mem->mem_level == 5){
            if($mem->mem_level_end_time != '0000-00-00 00:00:00'){
                $level['level_notice'] = '有效期到'.$mem->mem_level_end_time;
            }
            if($mem->mem_level_length == '永久有效'){
                $level['level_notice'] = '永久有效';
            }
        }else{
            $level['level_notice'] = '开通后立即生效';
        }
        $data['data'] = $level;//等级信息
        $data['black'] = $black_diamond;//黑钻价格
        //$data['number'] = $res['data']['ord_id'];
        //添加应收应付
        /*$order = DB::table('order')
            ->where('ord_id', $res['data']['ord_id'])
            ->first();
        $order = CommonService::dataToArray($order);
        $order['orcl_name'] = $mem->mem_name;
        $order['ord_order_price'] = 0;
        ReceivablePayService::addPay($res['data']['ord_id'],$res['data']['ord_order_number'],1,$user_info->ussh_user_id,$user_info,[],$order,$order,NULL,2);*/
        if ($data) {
            return ['code'=>200, 'msg'=>'成功', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'新增失败', 'data'=>''];
        }

    }

    //购买黑钻
    public static function addOrder($request){

        $user_info = LoginUserService::getUser();
        //用户信息
        $mem = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_shop_id', $user_info->adm_shop_id)
            ->where('mem_id', $user_info->ussh_user_id)
            ->first();
        $level = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->where('meml_show', 2)//是否显示：1否2是
            ->where('meml_level', 5)
            ->select('meml_id','meml_name','meml_total_amount','meml_price','meml_level')
            ->first();
        //下单
        $level = CommonService::dataToArray($level);
        $level['meml_price'] = $level['meml_price'] / 100;
        $level['orcl_name'] = $mem->mem_name;
        $level['orcl_phone'] = $mem->mem_phone;
        $level['ord_client_id'] = $user_info->ussh_user_id;
        $res = levelService::addOrder($user_info,$level,2);
        $data['number'] = $res['data']['ord_id'];
        //添加应收应付
        $order = DB::table('order')
            ->where('ord_id', $res['data']['ord_id'])
            ->first();
        $order = json_decode(json_encode($order,true),true);
        $order['orcl_name'] = $mem->mem_name;
        $a = ReceivablePayService::addPay($res['data']['ord_id'],$res['data']['ord_order_number'],1,$user_info->ussh_user_id,$user_info,[],$order,$order,NULL,2);
        if ($res) {
            return ['code'=>200, 'msg'=>'成功', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'新增失败', 'data'=>''];
        }
    }

    //取消下单
    public static function cancelOrder($request){
        $data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->first();
        if(empty($data)){
            return ['code'=>500, 'msg'=>'该订单不存在', 'data'=>''];
        }
        $ret = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update(['ord_wor_state'=>11]);
        if ($ret) {
            return ['code'=>200, 'msg'=>'成功', 'data'=>$ret];
        } else {
            return ['code'=>500, 'msg'=>'失败', 'data'=>''];
        }
    }

    //会员图片
    public static function levelImg(){
        $level_img_arr = ['1'=> config('apisystem.server_name_https').'/image/customerImg/member_grade_by_l.png',
            '2'=> config('apisystem.server_name_https').'/image/customerImg/member_grade_hj_l.png',
            '3'=>config('apisystem.server_name_https').'/image/customerImg/member_grade_bj_l.png',
            '4'=>config('apisystem.server_name_https').'/image/customerImg/member_grade_zs_l.png',
            '5'=>config('apisystem.server_name_https').'/image/customerImg/member_grade_hz_l.png'];
        return $level_img_arr;
    }

    //等级说明
    public static function levelText($user_info){
        $data = DB::table('member_level')
            ->where('meml_cid', $user_info->adm_cid)
            ->where('meml_shop_id', $user_info->adm_shop_id)
            ->get()->toArray();
        foreach ($data as $key => $value){
            $level[$value->meml_level] = $value;
        }
        $level_text_arr = ['1'=> '注册账号，并且实际消费金额≥'.$level[1]->meml_total_amount / 100,
            '2'=> '注册账号，并且实际消费金额≥'.$level[2]->meml_total_amount / 100,
            '3'=> '注册账号，并且实际消费金额≥'.$level[3]->meml_total_amount / 100,
            '4'=> '注册账号，并且实际消费金额≥'.$level[4]->meml_total_amount / 100,
            '5'=> '注册账号后付费开通即时生效'];
        return $level_text_arr;
    }
}
