<?php
namespace app\shared\logic\user;
use app\shared\model\User;
use app\shared\model\WeixinUser;
use app\shared\model\App;
use app\shared\model\Bill;
use app\shared\model\Store;
use app\shared\model\Collection;
use app\shared\model\Coupon;
use app\shared\model\CouponUser;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\CardCoupon;
use app\shared\model\CardCouponOrder;
use think\exception\ValidateException;
use app\shared\model\RechargeOrder;
use app\shared\model\Withdraw;
use wechatpay\WechatPay;
use app\shared\model\Option;
use app\shared\model\House;
use app\shared\model\HouseOrder;
use app\shared\model\Recharge;
use app\shared\model\PartnerUser;
use app\shared\model\TeaSpecialist;
use app\shared\model\StoreVerifier;
use app\BaseController;
use think\facade\Db;
use think\facade\Cache;
use app\shared\model\PartnerUserOrder;
use app\shared\model\PartnerUserBill;
use app\shared\model\Conversion;
use app\shared\model\StoreCleaning;
use app\shared\model\StoreUserMoney;
class UserForm extends  Base
{
  public $user;
  public $user_id;
  public function __construct()
  {
        parent::__construct();
        $access_token=request()->post('access_token');
        if(!$access_token){
             $access_token=request()->get('access_token')?request()->get('access_token'):404;
        }
        $user=User::where('access_token',$access_token)->cache(10)->find();
        if(!$user){
            die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
        }
        if(Cache::get('is_system_unauthorized')==-1){
            die(json_encode(['code'=>-1,'data'=>[],'msg'=>'系统未授权，请联系管理员']));
        }
        $user['wxapp_open_id']=WeixinUser::where(['acid'=>$this->acid,'mobile'=>$user->account])->cache(10)->value('wxapp_open_id');
        $this->user=$user;
        $this->user_id=$this->user->id;
        if($user['is_blacklist']==1){
           die(json_encode(['code'=>-1,'data'=>[],'msg'=>'您的行为异常，已被加入黑名单，请联系我们！']));
        }
        self::partnerUserBill();
    }
    //获取数据
    public  function index(){
       $platform=App::where(['id'=>$this->acid])->value('other');
       $is_verifier=StoreVerifier::where(['acid'=>$this->acid,'account'=>$this->user->account,'is_delete'=>0,'status'=>1])->count();
       $partnerUser=PartnerUser::where([
          'user_id'=>$this->user_id,
          'acid'=>$this->acid,
        ])->order('id DESC')->find();
       if($partnerUser){
          $partnerUser->start_time=date('Y-m-d H:i:s',$partnerUser->start_time);
          $partnerUser->end_time=date('Y-m-d H:i:s',$partnerUser->end_time);
       }
       $is_tea_specialist=TeaSpecialist::where(['account'=>$this->user->account,'is_delete'=>0])->count();
       $is_cleaning=StoreCleaning::where(['account'=>$this->user->account,'is_delete'=>0])->count();
       $coupon_num=CouponUser::alias('a')
            ->leftJoin([Coupon::getTable() => 'b'], 'a.coupon_id=b.id')
            ->where(['a.is_use'=>0,'a.user_id'=>$this->user_id])
            ->where('b.start_time','<=',time())
            ->where('b.end_time','>=',strtotime(date('Y-m-d',time()))+86399)
            ->count();

       $card_coupon_num=CardCoupon::where([
              'acid'=>$this->acid,
              'type'=>1,
              'user_id'=>$this->user_id,
              'status'=>1
            ])
            ->where('start_time','<=',time())
            ->where('end_time','>=',strtotime(date('Y-m-d',time()))+86399)
            ->count();
       $info=User::where('id',$this->user_id)->find();
       $money=StoreUserMoney::alias('s_u_m')->leftJoin([Store::getTable()=>'s'],'s_u_m.store_id=s.id')->where(['s.is_delete'=>0,'s.status'=>1,'s_u_m.user_id'=>$this->user_id])->sum('s_u_m.money');
       $info['store_money']=$money;
       $platform_access_token='';  
       $is_system_user=Option::where(['acid'=>$this->acid,'name'=>'app_system_phones'])->whereFindInSet('value',$this->user->account)->count();
       if($is_system_user){
          $platform_access_token=App::where('id',$this->acid)->value('access_token');
       }
       return fetchJson([
            'info'=>$info,
            'coupon_num'=>$coupon_num+$card_coupon_num,
            'platform'=>json_decode($platform),
            'is_verifier'=>$is_verifier?1:0,
            'is_tea_specialist'=>$is_tea_specialist?1:0,
            'partner_user'=>$partnerUser,
            'is_cleaning'=>$is_cleaning?1:0,
            'is_system_user'=>$is_system_user,
            'platform_access_token'=>$platform_access_token,
            'house_order'=>[
              'num0'=>HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'is_delete'=>0,'status'=>0])->count(),
              'num1'=>HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'is_delete'=>0,'status'=>1])->count(),
              'num2'=>HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'is_delete'=>0,'status'=>2])->count(),
            ]
       ]);

    }
    //用户设置
    public function setting(){
      if($data=request()->post()){
        try {
            $rule = [
               'account|账号'   => 'require',
               'nickname|昵称'=>'require',
               'avatar_url|头像'=>'require',
               'old_password|旧密码'=>'require',
               'password|密码'=>'require',
               'repassword|重复密码'=>'require|confirm:password'
           ];
            $this->validate($data,$rule);
         }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
         }
         $user=User::where(['account'=>$data['account'],'password'=>md5($data['old_password'])])->find();
         if(!$user){
            return fetchJson([],'旧密码错误',1);
         }
         $user->avatar_url=$data['avatar_url'];
         $user->password=md5($data['password']);
         $user->nickname=$data['nickname'];
         $user->save();
         return fetchJson($user,'保存成功');
       }else{
          return fetchJson([],'请求错误',1);
       }
    }
    //充值金额
    public function recharge(){
       $money=input('money');
       if($money<0){
          return fetchJson([],'金额不得小于0',1);
       }
       $order=new RechargeOrder();
       $order->order_no=RechargeOrder::crateOrderNo();
       $order->money=$money;
       $order->acid=$this->acid;
       $order->user_id=$this->user_id;
       $app=App::find($this->acid);
       $appid=$app->wxapp_app_id;
       $app_secret=$app->wxapp_app_secret;
       $openid=$this->user->wxapp_open_id;
       $recharge=Recharge::where(['acid'=>$order->acid,'price'=>$money,'status'=>1,'is_delete'=>0])->find();
       if($recharge){
          if($recharge->give_price>0){
            $order->give_price=$recharge->give_price;
            $order->coupon_ids=$recharge->coupon_ids;
            $order->card_ids=$recharge->card_ids;
          }
       }
       $order->save();
       if(input('is_weixin')==1){
          $appid=$app->wx_app_id;
          $app_secret=$app->wx_app_secret;
          $openid=$this->user->wx_open_id;
       }
       //App
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            $appConfig=Option::get_data($this->acid,'platform','app_config');
            $appConfig=json_decode($appConfig);
            $appid=isset($appConfig->appid)?$appConfig->appid:'';
            $app_secret=isset($appConfig->app_secret)?$appConfig->app_secret:'';
       }
       $wx_config=[
            'appid'=>$appid,
            'appsecret'=>$app_secret,
            'mchid'=>$app->wx_mch_id,
            'key'=>$app->wx_key,
            'sslcert'=>$app->wx_cert_pem,
            'sslkey'=>$app->wx_key_pem,
       ];
       $wechatPay=new WechatPay($wx_config);
       $notify_url=request()->domain().str_replace('index.php', 'pay_shared.php',request()->baseFile());
       $paydata = [
            'body' =>'余额充值',
            'out_trade_no' => $order->order_no,
            'total_fee' => round($order->money,2)* 100,
            'notify_url' =>$notify_url ,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
        //字节跳动支付
        if($this->platform=='ttapp'){
             $paydata=[
                'body' =>'余额充值',
                'appid'=>$app->wx_app_id,
                'attach'=>'余额充值',
                'mch_id'=>$app->mch_id,
                'notify_url' =>$notify_url ,
                'out_trade_no' => $order->order_no,
                'total_fee' => round($order->money,2)* 100,
                'trade_type' => 'MWEB',
                'openid' => $openid,
                'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
              ];
              $ttapp=Option::get_data($this->acid,'platform','ttapp_config');
              $ttapp=json_decode($ttapp);
              $res=$wechatPay->toutiaoh5pay($paydata,$ttapp);
              if($res['code']==0){
                return fetchJson($res);
              }else{
                return fetchJson([],$res['msg'],1);
              }
        }
        //微信外部支付
        if($this->platform=='h5'&&input('is_weixin')==0){
            $paydata=[
              'body' =>'余额充值',
              'appid'=>$app->wx_app_id,
              'attach'=>'余额充值',
              'mch_id'=>$app->mch_id,
              'notify_url' =>$notify_url ,
              'out_trade_no' => $order->order_no,
              'total_fee' => round($order->money,2)* 100,
              'trade_type' => 'MWEB',
              'openid' => $openid,
              'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $rest['order_id']=$order->id;
            $res=$wechatPay->h5pay($paydata);
            if($res['code']==0){
              $rest['mweb_url']=$res['data'];
              return fetchJson($rest);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
      if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            unset($paydata['openid']);
            $paydata['trade_type']="APP";
            $res=$wechatPay->appPay($paydata);
       }else{
          $res=$wechatPay->pay($paydata);
       }
       $res['order_id']=$order->id;
       return fetchJson($res);
    }
    /**
     * 余额明细列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function moneyBill(){
        $params=request()->only(['status']);
        $condition = [
            ['account_type', '=', Bill::ACCOUNT_TYPE_USER],
            ['form_id', '=', $this->user_id],
            ['is_delete', '=', 0],
        ];
        if(isset($params['status']) && in_array($params['status'],[1,-1])){
            $condition[]=['status','=',$params['status']];
        }
        $query = Bill::where($condition)->field('*,create_time time')->where('type','not in','13,14,15');
        $count=$query->count();
        $list=$query->order('create_time desc')
            ->page($this->page)
            ->limit($this->limit)
            ->select()->toArray();
        $month_data=[];
        $year=date('Y年');
        $typeArray=['茶室订单','充值','提现','茶艺师','分销','茶室订单续单','商品订单','会员卡订单','茶室订单退款','合伙人','兑换码','茶艺师订单退款','商户储值卡余额充值','商户储值卡茶室消费','商户储值卡城消费'];
        foreach ($list as $item) {
            $item_year=date('Y年',$item['time']);
            $key=($item_year==$year?'':$item_year).date('n月',$item['time']);
            $item['title']=isset($typeArray[($item['type']-1)])?$typeArray[($item['type']-1)]:'其他订单';
            $month_data[$key][]=$item;
        }
        $month_list=[];
        foreach ($month_data as $key=>$item){
            $month_list[]=[
                'month'=>$key,
                'list'=>$item,
            ];
        }
        return fetchJson(compact('count','month_list'));
    }
    //提现申请
    public function applyWithdraw(){
        try {
            $data=request()->post();
            $rule = [
                'type|类型'   => 'require|in:1,2,3',
                'username|姓名'   => 'length:1,20',
                'account|账号'   => 'length:5,50',
                'money|金额'   => 'require|>=:50|float',
            ];
            $this->validate($data,$rule);
        }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        $form=Withdraw::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'status'=>0,'user_type'=>Withdraw::USER_TYPE_USER])->find();
        if($form){
            return fetchJson(['status'=>1],'已有提交，请等待审核通过');
        }
        if(User::where('id',$this->user_id)->value('price')<$data['money']){
             return fetchJson(['status'=>0],'可提现佣金不足');
        }
        $form=new Withdraw();
        $form->acid=$this->acid;
        $form->user_id=$this->user_id;
        $form->asset_type=1;
        $form->user_type=Withdraw::USER_TYPE_USER;
        $form->save($data);
        if($data['type']==1){
           $user=User::where(['acid'=>$this->acid,'id'=>$form->user_id])->find();
          if($user->price<$form->money){
              return fetchJson([],'该用户佣金不足无法提现',1);
          }
          $user->price-=$data['money'];
          $user->money+=$data['money'];
          $user->save();
          (new Bill())->save([
              'acid'=>$this->acid,
              'type'=>Bill::TYPE_WITHDRAW,
              'account_type'=>Bill::ACCOUNT_TYPE_USER,
              'form_id'=>$form->user_id,
              'order_id'=>$form->id,
              'price'=>$data['money'],
              'price_type'=>2,
              'status'=>1,
              'des'=>'用户: '.$user->nickname."分销佣金提现金额：￥{$data['money']}",
          ]);
          $form->status=1;
          $form->save();
          return fetchJson(['status'=>1],'提现成功');
        }
        return fetchJson(['status'=>0],'保存成功');
    }
    //提现列表
    public function withdrawList(){
        $list=Withdraw::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'asset_type'=>1,'user_type'=>Withdraw::USER_TYPE_USER])
        ->field('id,type,account,username,money,create_time,status,bank,open_bank')
        ->page($this->page)
        ->order('id DESC')
        ->limit(10)
        ->select();
        $type=[1=>'余额',2=>'微信',3=>'银行卡'];
        $status=[0=>'提现中',1=>'提现成功',2=>'提现失败'];
        $color=['#fbbd08','#FF7651','#39b54a'];
        foreach ($list as $key => &$value) {
            $value['type_title']=$type[$value['type']];
            if($value['type']!=3){
                $value['bank']='';
                $value['open_bank']='';
            }
            $value['status_name']=$status[$value['status']];
            $value['status_color']=$color[$value['status']];
        }
        return fetchJson([
            'list'=>$list
        ]);
    }

    //切换商户
    public function toggleStore(){
      $account=$this->user->account;
      $store=Store::where(['account'=>$account,'acid'=>$this->acid,'is_delete'=>0])->find();
      if(!$store){
        $store=Store::where(['acid'=>$this->acid,'is_delete'=>0])->whereFindInSet('store_manager',$account)->find();
        if(!$store){
             return fetchJson(['is_store'=>0],'不是商户');
        }
      }
      if(!$store->access_token){
        $store->access_token=create_access_token(3);
        $store->save();
      }
      $logo_url=request()->domain().substr(request()->baseUrl(),0,stripos(request()->baseUrl(),'index.php')).'static/logo.png';
      $store['logo_url']=get_file_url($store['logo']);
      $store['logo_url']=$store['logo_url']?$store['logo_url']:$logo_url;
      $store['is_store']=1;
      return fetchJson($store,'登录成功');
    }
    //优惠券列表
    public function couponList(){   
        $list=CouponUser::alias('a')
            ->leftJoin([Coupon::getTable() => 'b'], 'a.coupon_id=b.id')
            ->where(['a.is_use'=>0,'a.user_id'=>$this->user_id])
            ->where('b.start_time','<=',time())
            ->where('b.end_time','>=',strtotime(date('Y-m-d',time()))+86399)
            ->field('b.start_time,b.end_time,b.price,b.full_price,b.name,a.id,a.is_use,a.type,a.use_time')
            ->page($this->page)
            ->select()->toArray();       
        foreach ($list as $key=>&$value) {
           $value['end_time']=date('Y-m-d',$value['end_time']);
           $value['start_time']=date('Y-m-d',$value['start_time']);

        }
        return fetchJson($list);
    }

    /**
     * 领券中心
     * @return \think\response\Json
     */
    public function couponCenter(){
        $condition = [
            ['a.status', '=', 1],
            ['a.send_type', '=', Coupon::SEND_TYPE_RECEIVE],
            ['a.end_time', '>', time()],
            ['a.is_delete', '=', 0],
        ];
        $list = Coupon::where($condition)->alias('a')
            ->leftJoin([CouponUser::getTable() => 'b'], 'a.id=b.coupon_id and b.user_id='.$this->user_id)
            ->whereNull('b.id')
            ->order('a.id desc')
            ->field('a.*')->select();
        return fetchJson($list);
    }
    /**
     * 领取优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receiveCoupon(){
        $coupon_id=(int)input('coupon_id');
        $condition = [
            ['id', '=', $coupon_id],
            ['status', '=', 1],
            ['send_type', '=', Coupon::SEND_TYPE_RECEIVE],
            ['end_time', '>', time()],
            ['is_delete', '=', 0],
        ];
        $coupon=Coupon::where($condition)->find();
        if(!$coupon){
            return fetchJson([],'所领优惠券不存在');
        }
        $user_coupon=CouponUser::where(['user_id'=>$this->user_id,'coupon_id'=>$coupon_id])->find();
        if(!$user_coupon){
            $create=[
                'acid'=>$this->acid,
                'coupon_id'=>$coupon_id,
                'type'=>$coupon->type,
                'user_id'=>$this->user_id,
                'is_use'=>0,
            ];
            CouponUser::create($create);
            return fetchJson([],'领取成功');
        }else{
            return fetchJson([],'不可重复领取',1);
        }

    }
    //历史记录
    public function historyRecord(){
        $list=House::alias('h')
        ->leftJoin([HouseOrder::getTable()=>'ho'],'h.id=ho.house_id')
        ->leftJoin([Store::getTable()=>'s'],'h.store_id=s.id')
        ->where(['ho.user_id'=>$this->user_id,'h.status'=>1,'s.is_delete'=>0,'s.status'=>1])
        ->order('ho.id DESC')
        ->distinct(true)
        ->field('h.cover,h.address,h.name,h.price,h.id,h.booktime,h.store_id,s.tel')
        ->limit(10)
        ->page($this->page)
        ->select();
        foreach ($list as $key=>&$value){
        //  $value['tel']=Store::where(['id'=>$value['store_id']])->value('tel');
        }
        return fetchJson($list);
    }

    /**
     * 领取转发优惠券
     * @return \think\response\Json
     */
    public function forwardCoupon(){
        $condition = [
            ['a.status', '=', 1],
            ['a.send_type', '=', Coupon::SEND_TYPE_FORWARD],
            ['a.end_time', '>', time()],
            ['a.is_delete', '=', 0],
        ];
        $list = Coupon::where($condition)->alias('a')
            ->leftJoin([CouponUser::getTable() => 'b'], 'a.id=b.coupon_id and b.user_id='.$this->user_id)
            ->whereNull('b.id')
            ->field('a.*')->select();
        $insert=[];
        foreach ($list as $key=>$coupon){
            $insert[]=[
                'acid'=>$this->acid,
                'coupon_id'=>$coupon->id,
                'type'=>$coupon->type,
                'user_id'=>$this->user_id,
                'is_use'=>0,
            ];
        }
        $insert_count=count($insert);
        if($insert_count>0){
            CouponUser::insertAll($insert);
        }
        return fetchJson(['count'=>$insert_count]);
    }
    /*
     *
     * 卡券列表
     */
    public function cardCouponList(){

       $list=CardCoupon::where(['acid'=>$this->acid,'type'=>1,'user_id'=>$this->user_id,'is_delete'=>0,'status'=>1])
           ->where('end_time','>',time())
           ->order('id DESC')
           ->page($this->page)
           ->limit($this->limit)
           ->select();
       foreach($list as &$value){
          $value['start_time']=date('Y-m-d H:i:s',$value['start_time']);
          $value['end_time']=date('Y-m-d H:i:s',$value['end_time']);
       }
       return fetchJson($list);
    }
    /*
     *@card_coupon_id
     * 卡券订单列表
     */
    public function cardCouponOrder(){
       $query=CardCouponOrder::alias('a')
           ->leftJoin([CardCoupon::getTable()=>'b'],'a.card_coupon_id=b.id')
           ->where(['b.acid'=>$this->acid,'b.type'=>1,'a.user_id'=>$this->user_id,'b.is_delete'=>0]);
       if($card_coupon_id=input('card_coupon_id')){
           $query->where('a.card_coupon_id',$card_coupon_id);
       }    
       $list=$query->order('a.id DESC')
           ->page($this->page)
           ->limit($this->limit)
           ->field('a.*,b.name,b.start_time,b.end_time')
           ->select();
       foreach($list as &$value){
          $value['start_time']=date('Y-m-d H:i:s',$value['start_time']);
          $value['end_time']=date('Y-m-d H:i:s',$value['end_time']);
       }    
       return fetchJson($list);
    }
    //核销卡券
    public function verificationCardCoupon(){
       $form=new \app\meituan\controller\Index();
       $config=Option::get_data($this->acid,'platform','app_meituan_dianping');
       $config=json_decode($config,1);
       $qr_code=input('verification_code');
       $open_shop_uuid="";
       $session=$config['session'];
       if(!is_array($config['shop_list'])){
          return fetchJson([],'平台未配置美团验券',1);
       }
       $res=['code'=>1,'msg'=>'暂无店铺','data'=>[]];
       foreach ($config['shop_list'] as $value){
         $open_shop_uuid=$value['open_shop_uuid'];
         $res=$form->prepare($qr_code,$open_shop_uuid,$session);
         if($res['code']==0){
            break;
         }
       }
       if($res['code']==0){
            $coupon=CardCoupon::where([
              'acid'=>$this->acid,
              'type'=>1,
              'user_id'=>$this->user_id,
              'code'=>$res['data']['receipt_code'],
            ])->find();
            if(!$coupon){
               $coupon=new CardCoupon();
            }
            $coupon->save([
              'acid'=>$this->acid,
              'type'=>1,
              'user_id'=>$this->user_id,
              'code'=>$res['data']['receipt_code'],
              'name'=>$res['data']['deal_title'],
              'discounts_price'=>$res['data']['deal_marketprice'],
              'num'=>$res['data']['count'],
              'start_time'=>time(),
              'status'=>1,
              'end_time'=>$res['data']['receiptEndDate']/1000,
              'snapshoot'=>json_encode($res['data']),
            ]);
       }
       return fetchJson($res['data'],$res['msg'],$res['code']);
    }
    //更新合伙人每日领取元宝
    private function partnerUserBill(){
        if(Cache::get("IStodaypartnerUserBillPus_".$this->user_id)){
            return 0;
        }
        Cache::set("IStodaypartnerUserBillPus_".$this->user_id,1,10);
        $partnerUser=PartnerUser::where([
            'user_id'=>$this->user_id,
            'acid'=>$this->acid,
            'status'=>1
        ])->find();
        if($partnerUser){
          if($partnerUser->end_time>0&&$partnerUser->end_time<time()){
              $partnerUser->status=0;
              $partnerUser->save();
              return 0;
          }
          if($partnerUser->start_time<time()){
              $time=date('Y-m-d',time());
              $time=strtotime($time);
              $startTime=strtotime(date("Y-m-d",$partnerUser->start_time));
              $num=($time-$startTime)/86400;   
              if($num>0){
                    for($i=1;$i<=$num;$i++){
                        $partnerUser=PartnerUser::where([
                            'user_id'=>$this->user_id,
                            'acid'=>$this->acid
                        ])->find();
                        $create_time=$startTime+(86400*$i)+28800;
                        if($partnerUser->give_lngot>=$partnerUser->everyday_lngot){
                             if(partnerUserBill::where([
                                'acid'=>$this->acid,
                                'user_id'=>$partnerUser->id,
                                'order_id'=>-1,
                                'lngot'=>$partnerUser->everyday_lngot,
                                'price'=>0,
                                'status'=>1,
                                'create_time'=>$create_time,
                                'update_time'=>$create_time
                             ])->count()){
                               continue;
                             }else{
                               if($create_time>time()){
                                  (new PartnerUserBill())->save([
                                    'acid'=>$this->acid,
                                    'user_id'=>$partnerUser->id,
                                    'order_id'=>-1,
                                    'title'=>'每日领取',
                                    'lngot'=>$partnerUser->everyday_lngot,
                                    'price'=>0,
                                    'status'=>1,
                                    'create_time'=>$create_time,
                                    'update_time'=>$create_time
                                 ]);
                                 $partnerUser->give_lngot-=$partnerUser->everyday_lngot;
                                 $partnerUser->sum_lngot+=$partnerUser->everyday_lngot;
                                 $partnerUser->save();
                               }
                             }
                         }
                    }
              }

          }
        }
    }
    //兑换码
    public function conversionCode(){
        $form=Conversion::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>0,'code'=>input('code')])->find();
        if($form){
           $card_list=Card::where('id','in',$form['card_ids'])->where(['acid'=>$this->acid,'is_delete'=>0])->select();
           foreach ($card_list as $card){
              $cardUser=CardUser::where([
                  'card_id'=>$card->id,
                  'user_id'=>$this->user_id,
                  'acid'=>$this->acid
              ])->find();
              if($card->month<=0){
                  $card->month=1;
              }
              if(!$cardUser){
                  $cardUser=new CardUser();
                  $cardUser->card_id=$card->id;
                  $cardUser->user_id=$this->user_id;
                  $cardUser->acid=$this->acid;
                  $cardUser->start_time=time();
                  $cardUser->end_time=strtotime(date("Y-m-d",strtotime("+{$card->month} month")));
                  $cardUser->status=1;
                  $cardUser->hour=$card->hour;
              }else{
                  $time=strtotime(date("Y-m-d",strtotime("+{$card->month} month")))-strtotime(date("Y-m-d",time()));
                  if($cardUser->status==0){
                      $cardUser->end_time=time()+$time;
                  }else{
                      $cardUser->end_time+=$time;
                  }
                  $cardUser->hour+=$card->hour;
              }
              $cardUser->level=$card->level;
              $cardUser->save();
           }
           if($form['coupon_ids']){
              Coupon::giveUserCoupon($this->user_id,4,$this->acid,$form['coupon_ids']);
           }
           if($form->money>0){
              (new Bill())->save([
                  'acid'=>$this->acid,
                  'type'=>Bill::TYPE_CONVERSION,
                  'account_type'=>Bill::ACCOUNT_TYPE_USER,
                  'form_id'=>$this->user_id,
                  'order_id'=>$form->id,
                  'price'=>$form->money,
                  'price_type'=>1,
                  'balance'=>$this->user->money,
                  'status'=>1,
                  'des'=>"用户:【{$this->user->nickname}】兑换码充值金额"
             ]);
             $user=User::where('id',$this->user_id)->find();
             $user->money+=$form->money;
             $user->save();
           }
           $form->status=1;
           $form->finish_time=time();
           $form->user_id=$this->user_id;
           $form->save();
           return fetchJson([],'兑换成功');
        }
        return fetchJson([],'兑换码不存在，或已失效~',1);
    }
    //消费排行
    public function consumeRanking(){
      $billTab=Bill::getTable();
        $userTab=User::getTable();
      $sql="
         SELECT a.* FROM (select @rownum := @rownum + 1 AS ranking,t.* FROM
        (SELECT @rowNum := 0) r,
        (SELECT h.id,h.nickname,h.avatar_url,h.acid,r.type,IFNULL(sum(r.price),0) AS consumption_price
        FROM `{$billTab}` AS r RIGHT JOIN `{$userTab}` AS h
        ON r.form_id = h.id
        AND r.status = -1 
        AND r.acid = {$this->acid} 
        AND r.type  IN(1,2,4,6,7,8)
        GROUP BY h.id
        ORDER BY consumption_price DESC
        ) t) a 
      ";
      $sq1=$sql." WHERE a.id=".$this->user_id ." AND consumption_price>0";
      $sq2=$sql."WHERE consumption_price>0 ORDER BY consumption_price DESC LIMIT 10";
      $info=Db::query($sq1);
      if(!$info){
        $info=['ranking'=>0,'nickname'=>$this->user->nickname,'avatar_url'=>$this->user->avatar_url];
      }else{
        $info=$info[0];
      }
      return fetchJson([
        'list'=>Db::query($sq2),
        'info'=>$info
      ],'获取成功');
    }
    //选择商户
    public function selectStore(){
        $list=Store::where(['acid'=>$this->acid,])->whereFindInSet('store_manager',$this->user->account)->select();
        foreach($list as &$value){
            $type=get_access_token_type($value['access_token']);
            if($type!=3){
               $value['access_token']=create_access_token(3);
            }
        }
        return fetchJson($list);
    }
}