<?php
namespace app\shared\logic\user;
use app\shared\model\User;
use app\shared\model\Store;
use app\shared\model\ApplyBecomeStore;
use app\shared\model\House;
use app\shared\model\App;
use app\shared\model\Tags;
use app\shared\model\HouseOrder;
use app\shared\model\GoodsOrder;
use app\shared\model\Category;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\Facility;
use app\shared\model\HouseStock;
use app\shared\model\StoreCoupon;
use app\shared\model\StoreCouponUser;
use think\exception\ValidateException;
use app\shared\model\StoreRechargeOrder;
use app\shared\model\StoreRecharge;
use app\shared\model\StoreUserMoney;
use app\shared\model\Bill;
use think\facade\Cache;;
use app\BaseController;
use wechatpay\WechatPay;
class StoreForm extends  Base
{
   // 分类列表
    public function categoryList(){
       $list=Category::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1])->order('sort ASC')->column('id,name,cover,sort');
       foreach ($list as $key => &$value) {
             $value['cover_url']=get_file_url($value['cover']);
       }
       return fetchJson($list);
    }
    //列表
    public function info(){
         $store_id=input('id');
         $store=Store::where(['acid'=>$this->acid,'id'=>$store_id])->field('id,name,address,tags,tel,dec,lng,lat,banner,logo,service_facilities,facilities,policy,is_shop,config,local,video_url')->find();
         if(!$store){
             return fetchJson([],'暂无数据',1);
         }
         $store['banner']=get_file_urls($store['banner']);
         $store['logo']=get_file_url($store['logo']);
         $store['logo']=str_replace("http://","https://", $store['logo']);
         $tags=Tags::where(['acid'=>$this->acid])->where('id','in',explode(',', $store['tags']))->column('id,title');
         $store['tags']=$tags;
         $config=json_decode($store['config'],1);
         $store['wifi_username']=isset($config['wifi_config']['username'])?$config['wifi_config']['username']:'';
         $store['wifi_password']=isset($config['wifi_config']['password'])?$config['wifi_config']['password']:'';
         $icon_config=isset($config['icon_config']['home']['icon'])?$config['icon_config']:[];
         $icon_config=isset($config['icon_config']['home']['icon'])?$config['icon_config']:[];
         if(!$icon_config){
            $url=request()->domain().str_replace('index.php', '',request()->baseFile()).'static/shared/';
            $icon_config=[
                  'home'=>[
                    'title'=>'首页',
                    'status'=>1,
                    'icon'=>$url.'store_icon/home.png'
                  ],
                  'shop'=>[
                    'title'=>'茶城',
                    'status'=>1,
                    'icon'=>$url.'store_icon/shop.png'
                  ],
                  'kefu'=>[
                    'title'=>'客服',
                    'status'=>1,
                    'icon'=>$url.'store_icon/kefu.png'
                  ],
                  'wifi'=>[
                    'title'=>'WiFi',
                    'status'=>1,
                    'icon'=>$url.'store_icon/wifi.png'
                  ],
                  'code'=>[
                    'title'=>'商家码',
                    'status'=>1,
                    'icon'=>$url.'store_icon/code.png'
                  ],
                ];
         }
         $store['icon_config']=$icon_config;
         $keyword=input('keyword');
         $list=House::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$store_id,'status'=>1])
         ->order('sort ASC')
         ->select()
         ->toArray();
         foreach ($list as $key => &$value) {
             $value['cover_url']=get_file_url($value['cover']);
             $value['banner_list']=get_file_urls($value['banner']);
             $value['booktime']=$value['booktime']?$value['booktime']:1;
             $value['booknum']=HouseOrder::where(['acid'=>$this->acid,'is_pay'=>1,'house_id'=>$value['id']])->where('status','<>',4)->count();
             $virtual_sales=isset($value['virtual_sales'])?$value['virtual_sales']:0;
             $value['booknum']+=$virtual_sales;
             $discount=Card::where(['acid'=>$this->acid,'is_delete'=>0])->order('discount ASC')->value('discount');
             if(!$discount){
                  $value['member_price']=-1;
             }else{
                if($value['member_price']<=0){
                  $value['member_price']=$value['price']*$discount*0.1;
                  $value['member_price']=round($value['member_price'],2);
                }
                
             }
             $value['discount']=$discount;
             $value['is_book']=HouseStock::where(['acid'=>$this->acid,'house_id'=>$value['id']])->where('hour',"<",time()+$value['booktime']*3600)->where('hour',">",time())->count();
             $value['is_book']=$value['is_book']>0?1:0;
         }
         $user_id=User::where('access_token',input('access_token'))->value('id');
         $cardUser=CardUser::alias('c_u')
          ->leftJoin([Card::getTable()=>'c'],'c_u.card_id=c.id')
          ->where(['c_u.status'=>1,'c_u.user_id'=>$user_id,'c.is_delete'=>0])
          ->where('c_u.start_time','<',time())
          ->where('c_u.end_time','>',strtotime(date('Y-m-d',time()+86400)))
          ->order('c_u.level DESC')->field('c_u.*,c.discount')->find();
          $discount=-1;
          if($cardUser){
            $discount=$cardUser['discount'];
          }
          $store['user_discount']=$discount;

          //商户访问量
          \app\shared\model\UserUv::todayUv($this->acid,1,$store['id'],$user_id,$store['id']);
         return fetchJson([
            'info'=>$store,
            'house_list'=>$list
         ]);
    }
    //商户列表
    public function list(){
        $lat=input('lat')?input('lat'):0;
        $lng=input('lng')?input('lng'):0;
        $query=Store::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1])->field('id,name,logo,local,is_list_open,address,tel,lat,lng,score,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - '.$lat.' * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos('.$lat.' * pi() / 180) * pow(sin((lng * pi() / 180 - '.$lng.' * pi() / 180) / 2),2))) * 1000) as distance');
        if($keyword=input('keyword')){
          $query->where('name','like',"%$keyword%");
        }
        if($price_sort=input('price_sort')){
           if($price_sort==1){
               $query->order('tea_price ASC');
           }else{
               $query->order('tea_price DESC');
           }
        }
        if($category=input('category')){
          $query->whereFindInSet('category',$category);
        }
       if($distance_sort=input('distance_sort')){
           if($distance_sort==1){
               $query->order('distance ASC');
           }else{
               $query->order('distance DESC');
           }
       }else{
          $query->order('distance ASC');
       }
       $list=$query->page($this->page)->select();
       foreach ($list as $key => &$value) {
            $value['logo']=get_file_url($value['logo']);
            $house=House::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$value['id'],'status'=>1])->field('booktime,half_price,price,original_price')->order('sort ASC')->find();
            if(!$house){
                $value['price']=0;
                $value['booktime']=1;
                $value['business_time']="00:00-24:00";
            }else{
              $house['booktime']=$house['booktime']?$house['booktime']:1;
              $value['price']=$house['price']*($house['booktime']);
              $value['booktime']=$house['booktime'];
              $value['original_price']=$house['original_price'];
              $value['business_time']="00:00-24:00";
              $discount=Card::where(['acid'=>$this->acid,'is_delete'=>0])->order('discount ASC')->value('discount');
              if(!$discount){
                  $value['member_price']=-1;
              }else{
                 if($value['member_price']<=0){
                  $value['member_price']=$value['price']*$discount*0.1;
                  $value['member_price']=round($value['member_price'],2);
                }

              }
              $value['discount']=$discount;
              $value['local']=json_decode($value['local'],1);
            }
       }    
       return fetchJson($list); 
    }
    private function changeHouseStock($stockToday){
       $orderNew=[];
       foreach ($stockToday as &$t){
           $orderNew[$t['order_id']][]=$t;
       }
       foreach ($orderNew as &$n){
          $n=array_merge([[
            'hour'=>$n[0]['hour']-1800,
            'status'=>$n[0]['status'],
            'order_id'=>$n[0]['order_id'],
          ]],$n);
       }
       $stockToday=[];
       foreach ($orderNew as &$d){
           foreach ($d as $s){
               $stockToday[]=$s;
           }
       }
       $dateTime=input('date')?strtotime(input('date')):time();
       $stockDatas=[];
       for ($j=0;$j<96;$j++){
           $time=strtotime(date('Y-m-d H:i',$dateTime))+1800*$j;
           foreach($stockToday as $v){
              if($time>($v['hour']-1800)&&$time<($v['hour']+1800)){
                    $stockDatas[$time]=[
                      'hour'=>$time,
                      'status'=>$v['status'],
                      'order_id'=>$v['order_id'],
                   ];
              }
           }
        }
       return $stockDatas;
    }
    //茶室信息
    public function houseInfo(){
       $form=House::where(['acid'=>$this->acid,'is_delete'=>0,'id'=>input('house_id'),'status'=>1])->find();
       if(!$form){
          return fetchJson([],'暂无数据',1);
       }
       $dateTime=input('date')?strtotime(input('date')):time();
       $form['package_price']=json_decode($form['package_price'],1);
       //___________________________________________________
       //今天
       $stockToday=HouseStock::where(['acid'=>$this->acid,'store_id'=>$form->store_id,'house_id'=>$form['id'],'date'=>$dateTime,'status'=>0])->order('hour ASC')->column('hour,status,order_id');
       $tomorrowtime=$dateTime+86400;
       $stockTomorrow=HouseStock::where(['acid'=>$this->acid,'store_id'=>$form->store_id,'house_id'=>$form['id'],'date'=>$tomorrowtime,'status'=>0])->column('hour,status,order_id');
       $allstock=array_merge($stockToday,$stockTomorrow);
       $orderNew=[];
       $allstock=self::changeHouseStock($allstock);

       $allstock=array_column($allstock,'status','hour');
       $servicing_today_time=[];
       $price_list=json_decode($form['price_list'],1);
       if($price_list){
         $priceData=array_column($price_list,'price','time');
       }
       for ($j=0;$j<(49);$j++){
          $time=strtotime(date('Y-m-d H:i',$dateTime))+1800*$j; 
          $timeTomorrow=strtotime(date('Y-m-d H:i',$dateTime+86400))+1800*$j; 
          $t=date('H',$time);
          $tt=date('H',$timeTomorrow);
          $servicing_today_time[]=[
            'status'=>isset($allstock[$time])?$allstock[$time]:1,
            'time'=>date('H:i',$time),
            'price'=>isset($priceData[$t])?$priceData[$t]/2:$form['price']/2,
          ];
          $servicing_tomorrow_time[]=[
            'status'=>isset($allstock[$timeTomorrow])?$allstock[$timeTomorrow]:1,
            'time'=>date('H:i',$time),
            'price'=>isset($priceData[$tt])?$priceData[$tt]/2:$form['price']/2,
          ];
       }
       $form['servicing_today_time']=$servicing_today_time;
       $form['servicing_tomorrow_time']=$servicing_tomorrow_time;
       $form['banner_list']=get_file_urls($form['banner']);
       $form['facility_servicing_list']=Facility::where('id','in',$form['facility_servicing'])->column('id,title');
       $store=Store::where(['id'=>$form['store_id']])->find();
       $form['tel']=$store['tel'];
       $form['local']=$store['local'];
       $form['lat']=$store['lat'];
       $form['lng']=$store['lng'];
       $form['address']=$store['address'];
       $form['is_wallet']=$store['is_wallet'];
       $discount=Card::where(['acid'=>$this->acid,'is_delete'=>0])->order('discount ASC')->value('discount');
       if(!$discount){
            $form['member_price']=-1;
       }else{
          if($form['member_price']<=0){
            $form['member_price']=$form['price']*$discount*0.1;
            $form['member_price']=round($form['member_price'],2);
          }
       }
       $form['discount']=$discount; 
       $form['booknum']=HouseOrder::where(['acid'=>$this->acid,'is_pay'=>1,'house_id'=>$form['id']])->where('status','<>',4)->count();
       $virtual_sales=isset($form['virtual_sales'])?$form['virtual_sales']:0;
       $form['booknum']+=$virtual_sales;
       $form['is_book']=HouseStock::where(['acid'=>$this->acid,'store_id'=>$form->store_id,'house_id'=>$form['id']])->where('hour',"<",time()+$form['booktime']*3600)->where('hour',">",time())->count();
       $form['is_book']=$form['is_book']>0?1:0;
       //茶室访问量
       $user_id=User::where('access_token',input('access_token'))->value('id');
       \app\shared\model\UserUv::todayUv($this->acid,2,$form['store_id'],$user_id,$form['id']);
       return fetchJson($form);
    }
    //二维码
    public function qrcode(){
        $app=App::where('id',$this->acid)->find();
        $store_id=input('id');
        $url=self::getQrcode($app,[
          'path'=>'pages/aboutTea/teaStoreDetail?id='.$store_id
        ],'store',$store_id);
        return fetchJson([
          'qrcode_url'=>$url
        ]);
    
    }
    //微信小程序获取二维码
    public function getQrcode($acid=[],$param=[],$type='store',$user_id=0){
        //保存到本地
        $saveRoot = public_path();
        $saveDir="qrcode/{$this->acid}/{$type}/";
        if (!is_dir($saveRoot . $saveDir)) {
            @mkdir($saveRoot . $saveDir, 0755, true);
            file_put_contents($saveRoot . $saveDir . '.gitignore', "*\r\n!.gitignore");
        }
        $saveName = $user_id.'_'.md5($user_id).'.png';
        $base_file = request()->baseFile();
        $base_dir  = substr($base_file, 0, strripos($base_file, '/') + 1);

        if(Cache::get('store_share_qrcode'.$user_id)){
           return request()->domain().$base_dir.$saveDir.$saveName;
        }
        $token=self::getToken($acid['wxapp_app_id'],$acid['wxapp_app_secret']);
        if(isset($param['path'])){
          //$url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$token}";//方形
          $url="https://api.weixin.qq.com/wxa/getwxacode?access_token={$token}";//方形
        }else{
          $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";//圆形
        }
        $params = json_encode($param, JSON_UNESCAPED_UNICODE);
        $data=httpRequest($url,'POST',$params);
        file_put_contents($saveRoot.$saveDir.$saveName, $data);
        Cache::get('store_share_qrcode'.$user_id,1,20);
        return request()->domain().$base_dir.$saveDir.$saveName;
    }
    //获取令牌
    private function getToken($appid,$secret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        if($this->platform=="ttapp"){
          $url="https://developer.toutiao.com/api/apps/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        }
        $data=httpRequest($url);
        $data=json_decode($data);
        if(isset($data->access_token)){
            return ($data->access_token);
        }else{
            die(json_encode(['code'=>-1,'data'=>'','msg'=>'access_token获取错误请检查微信参数是否错误']));
        }
    }
    //申请成为商家
    public function applyBecomeStore(){
         $that=new UserForm();
         $data=request()->post();
         try {
            $rule = [
               'account|账号'   => 'require',
               // 'password|密码'=>'require',
               'area_id|区域ID'=>'require',
               'name|名称'=>'require',
               // 'logo|LOGO'=>'require',
               // 'banner|轮播'=>'require',
           ];
            $this->validate($data,$rule);
         }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
         }
         $form=ApplyBecomeStore::where(['user_id'=>$that->user_id,'status'=>0])->find();
         if($form){
            return fetchJson([],'已有提交申请，请等待审核通过',1);
         }
         // $store=Store::where(['account'=>$data['account'],'is_delete'=>1])->count();
         // if($store){
         //    return fetchJson([],'请用其他账号注册',1);
         // }
         $form=new ApplyBecomeStore();
         $form->save([
            'acid'=>$this->acid,
            'user_id'=>$that->user_id,
            'account'=>$data['account'],
            // 'password'=>$data['password'],
            'area_id'=>$data['area_id'],
            'name'=>$data['name'],
            'logo'=>0,//$data['logo'],
            'banner'=>0,//$data['banner'],
            'address'=>0,//input('address'),
            'lng'=>0,//input('lng'),
            'lat'=>0,//input('lat'),
         ]);
         return fetchJson([],'提交成功');
    }
    //优惠券列表
    public function couponList(){
        $user=new UserForm();
        $user_id=$user->user_id;
        $store_id=input('store_id');   
        $type=input('type');
        $query=StoreCouponUser::alias('a')
            ->leftJoin([StoreCoupon::getTable() => 'b'], 'a.coupon_id=b.id')
            ->where(['a.is_use'=>0,'a.user_id'=>$user_id,'a.store_id'=>$store_id])
            ->where('b.start_time','<=',time());
        if($type){
          $query->where('a.type',$type);
        }
        $list=$query->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(){
        $user=new UserForm();
        $user_id=$user->user_id;
        $store_id=input('store_id');      
        $condition = [
            ['a.status', '=', 1],
            ['a.store_id', '=', $store_id],
            ['a.send_type', '=', StoreCoupon::SEND_TYPE_RECEIVE],
            ['a.end_time', '>', time()],
            ['a.is_delete', '=', 0],
        ];
        $list = StoreCoupon::where($condition)->alias('a')
            ->leftJoin([StoreCouponUser::getTable() => 'b'], 'a.id=b.coupon_id and b.user_id='.$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(){
        $user=new UserForm();
        $user_id=$user->user_id;   
        $coupon_id=(int)input('coupon_id');
        $condition = [
            ['id', '=', $coupon_id],
            ['status', '=', 1],
            ['send_type', '=', StoreCoupon::SEND_TYPE_RECEIVE],
            ['end_time', '>', time()],
            ['is_delete', '=', 0],
        ];
        $coupon=StoreCoupon::where($condition)->find();
        if(!$coupon){
            return fetchJson([],'所领优惠券不存在');
        }
        $user_coupon=StoreCouponUser::where(['user_id'=>$user_id,'coupon_id'=>$coupon_id])->find();
        if(!$user_coupon){
            $create=[
                'acid'=>$this->acid,
                'store_id'=>$coupon->store_id,
                'coupon_id'=>$coupon_id,
                'type'=>$coupon->type,
                'user_id'=>$user_id,
                'is_use'=>0,
            ];
            StoreCouponUser::create($create);
            return fetchJson([],'领取成功');
        }else{
            return fetchJson([],'不可重复领取',1);
        }

    }
    //充值金额
    public function recharge(){
       $user=new UserForm();
       $money=input('money');
       if($money<0){
          return fetchJson([],'金额不得小于0',1);
       }
       $store_id=input('store_id');
       if(!Store::where(['id'=>$store_id,'is_delete'=>0,'status'=>1,'acid'=>$this->acid])->count()){
          return fetchJson([],'暂无商户ID',1);
       }
       $order=new StoreRechargeOrder();
       $order->order_no=StoreRechargeOrder::crateOrderNo();
       $order->money=$money;
       $order->acid=$this->acid;
       $order->user_id=$user->user_id;
       $order->store_id=$store_id;
       $app=App::find($this->acid);
       $appid=$app->wxapp_app_id;
       $app_secret=$app->wxapp_app_secret;
       $openid=$user->user->wxapp_open_id;
       $recharge=StoreRecharge::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=$user->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(){
        $user=new UserForm();
        $params=request()->only(['status']);
        $store_id=input('store_id');
        $condition = [
            ['b.account_type', '=', Bill::ACCOUNT_TYPE_USER],
            ['b.form_id', '=', $user->user_id],
            ['b.is_delete', '=', 0],
            ['o.store_id', '=', $store_id],
        ];
        if(isset($params['status']) && in_array($params['status'],[1,-1])){
            $condition[]=['b.status','=',$params['status']];
        }

        $query = Bill::alias('b');
        
        $type=input('type');
        if($type==Bill::TYPE_STORE_USER_RECHARGE){
          $query->leftJoin([StoreRechargeOrder::getTable()=>'o'],'b.order_id=o.id');
          $query->where('b.type',Bill::TYPE_STORE_USER_RECHARGE);
        }else if($type==Bill::TYPE_STORE_USER_HOUSE){
          $query->leftJoin([HouseOrder::getTable()=>'o'],'b.order_id=o.id');
          $query->where('b.type',Bill::TYPE_STORE_USER_HOUSE);
        }else if($type==Bill::TYPE_STORE_USER_GOODS){
          $query->leftJoin([GoodsOrder::getTable()=>'o'],'b.order_id=o.id');
          $query->where('b.type',Bill::TYPE_STORE_USER_GOODS);
        }else{
          $query->leftJoin([StoreRechargeOrder::getTable()=>'o'],'b.order_id=o.id');
          $query->where('b.type',Bill::TYPE_STORE_USER_RECHARGE);
        }
        $query->where($condition)->field('b.*,b.create_time time');
        $count=$query->count();
        $list=$query->order('b.create_time desc')
            ->page($this->page)
            ->limit($this->limit)
            ->select()->toArray();
        $month_data=[];
        $year=date('Y年');
        foreach ($list as $item) {
            $item_year=date('Y年',$item['time']);
            $key=($item_year==$year?'':$item_year).date('n月',$item['time']);
            $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 rechargeList(){
         $user=new UserForm();
         $query=StoreRecharge::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1,'store_id'=>input('store_id')]);
         $list=$query->order('price ASC')->field('id,price,give_price')
         ->select()
         ->toArray();
         foreach ($list as $key => &$value) {
             $value['give_text']='买'.$value['price'].'元送'.$value['give_price'].'元';
         }
         return fetchJson($list);
    }
    //用户金额
    public function userMoney(){
         $user=new UserForm();
         $query=Store::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1,'is_wallet'=>1]);
         $list=$query->order('id DESC')->field('id,name')
         ->page($this->page)
         ->select()
         ->toArray();
         foreach ($list as $key => &$value) {
             $money=StoreUserMoney::where(['store_id'=>$value['id'],'user_id'=>$user->user_id])->value('money');
             $value['money']=$money>0?$money.'元':"0元";
         }
         return fetchJson($list);
         
    }
}