<?php
namespace app\shared\logic\user;
use app\shared\model\App;

use app\shared\model\StoreVerifier;
use app\shared\model\StoreVerifierOrder;
use app\shared\model\HouseOrder;
use app\shared\model\HouseOrderContinue;
use app\shared\model\Store;
use app\plugin\model\stock\User as StockUser;
use app\plugin\model\stock\House as StockHouse;
use app\plugin\model\stock\HouseUser as StockHouseUser;
use app\plugin\model\stock\HouseUserOrder as StockHouseUserOrder;
use app\shared\model\Bill;
use app\shared\model\User;
use app\shared\model\Option;
use app\shared\model\ShareOrder;
use app\BaseController;
use wechatpay\WechatPay;
use think\exception\ValidateException;
//核销管理
class VerifierForm extends  UserForm
{	
	private $verifierGroup;
	public function __construct()
    {
        parent::__construct();
        $verifierGroup=StoreVerifier::where(['acid'=>$this->acid,'account'=>$this->user->account,'is_delete'=>0,'status'=>1])->column('id,store_id,name');
        if(!$verifierGroup){
        	die(json_encode(['code'=>-3,'data'=>[],'msg'=>'您不是核销员']));
        }
        $this->verifierGroup=$verifierGroup;
    }
    //统计
    public function statistics(){
    	$verifierIds=array_column($this->verifierGroup,'id');
    	$type=1;
    	$status=input('status');
    	//1累计，2今日，3昨日，4 七日，5，三十日
    	
    	$query=StoreVerifierOrder::alias('vo')
                    ->leftJoin([StoreVerifier::getTable()=>'v'],'vo.verifier_id=v.id')
                    ->leftJoin([HouseOrder::getTable()=>'o'],'vo.order_id=o.id')
                    ->where(['vo.acid'=>$this->acid,'vo.is_delete'=>0,'type'=>$type])
                    ->where('vo.verifier_id','in',$verifierIds);
        if($status==2){
        	$query->whereDay('vo.create_time',date('Y-m-d'));
        }elseif($status==3){
        	$query->whereDay('vo.create_time','yesterday');
        }elseif($status==4){
        	$end_time=time();
        	$start_time=time()-86400*6;
        	$query->whereTime('vo.create_time', '<=',$end_time)->whereTime('vo.create_time', '>=',$start_time);
        }elseif($status==5){
        	$end_time=time();
        	$start_time=time()-86400*30;
        	$query->whereTime('vo.create_time', '<=',$end_time)->whereTime('vo.create_time', '>=',$start_time);
        }else{
        	
        }            
        return fetchJson([
        	'sum_price'=>$query->sum('o.price'),
        	'count'=>$query->count()
        ]);             
    }
    public function list(){
    	$storeIds=array_column($this->verifierGroup,'store_id');
    	$status=input('status')?1:0;
    	if($status==1){
    		$verifier_ids=array_column($this->verifierGroup,'id');
    		$list=StoreVerifierOrder::alias('vo')->leftJoin([HouseOrder::getTable()=>'o'],'vo.order_id=o.id')
    		             ->where(['o.is_verifier'=>1,'o.acid'=>$this->acid])
				    	 ->where('vo.verifier_id','in',$verifier_ids)
				    	 ->field('o.id,o.order_no,o.username,o.tel,o.price,o.pay_type,o.start_time,o.end_time,o.snapshoot,vo.verifier_time,vo.verifier_id')
				    	 ->page($this->page)
				    	 ->limit(10)
				    	 ->order('o.id DESC')
				    	 ->select();
    	}else{
    		$list=HouseOrder::where(['is_verifier'=>1,'status'=>1,'acid'=>$this->acid])
				    	 ->where('store_id','in',$storeIds)
				    	 ->field('id,order_no,username,tel,price,pay_type,start_time,end_time,snapshoot')
				    	 ->page($this->page)
				    	 ->limit(10)
				    	 ->order('id DESC')
				    	 ->select();
    	}
        foreach ($list as &$value){
            $value['snapshoot']=json_decode($value['snapshoot'],1);

            $value['verifier_time']=isset($value['verifier_time'])?date('Y-m-d H:i:s',$value['verifier_time']):0;
        }
        return fetchJson($list);
    }
    public function handle(){
    	try {
          $data=request()->post();
          $rule = [
               'order_id|订单ID' => 'require',
               'type|类型'=>'require|number|in:1',
           ];
          $this->validate($data,$rule);
        }catch (ValidateException $e){
           return fetchJson([],$e->getError(),1);
        }
        $storeIds=array_column($this->verifierGroup,'store_id');
        if($data['type']==1){
        	$order=HouseOrder::where(['id'=>$data['order_id'],'status'=>1,'is_delete'=>0,'is_verifier'=>1])->find();
        	if($order){
        		if(in_array($order->store_id,$storeIds)){
        			$verifierIds=array_column($this->verifierGroup,'id','store_id');
        			if(StoreVerifierOrder::where([
        				'acid'=>$this->acid,
        				'type'=>$data['type'],
        				'order_id'=>$order->id,
        				'status'=>1
        			])->count()){
        				return fetchJson([],'已被核销');
        			}
        			$form=new StoreVerifierOrder();
        			$form->save([
        				'acid'=>$this->acid,
        				'type'=>$data['type'],
        				'verifier_id'=>$verifierIds[$order->store_id],
        				'order_id'=>$order->id,
        				'store_id'=>$order->store_id,
        				'verifier_time'=>time(),
        				'status'=>1,
        			]);
        			self::addStoreBill($order);
        			return fetchJson([],'核销成功');
        		}
        		return fetchJson([],'您不是该商户的核销人员',1);
        	}
        	return fetchJson([],'暂无订单',1);
        }
        return fetchJson([],'暂无核销码',1);
    }
    //增加商户账单
    private function addStoreBill($order=[]){
      if($order->status==2){
        return false;
      }
      $order->status=2;
      $order->save();
        $store=Store::where('id',$order['store_id'])->find();
        $fee=($store->fee*0.01)*$order['price'];
        $fee=$fee>0?$fee:0;//手续费
        $orderPrice=$order->price-$fee; //总金额   
        $stockHouse=StockHouseUser::alias('h_u')
               ->leftJoin([StockHouse::getTable()=>'h'],'h_u.stock_house_id=h.id')
               ->where(['h_u.acid'=>$order->acid,'h.house_id'=>$order->house_id,'h_u.is_delete'=>0,'h.is_delete'=>0])
               ->field('h_u.stock_user_id,h_u.ratio,h.house_id,h_u.stock_house_id')
               ->select()
               ->toArray();
        //分红金额
        $sharePrice=0;           
        foreach($stockHouse as $hu){
           (new StockHouseUserOrder())->save([
              'acid'=>$order->acid,
              'type'=>1,
              'order_id'=>$order->id,
              'stock_house_id'=>$hu['stock_house_id'],
              'stock_user_id'=>$hu['stock_user_id'],
              'ratio'=>$hu['ratio'],
              'price'=>$hu['ratio']*$orderPrice*0.01, 
            ]);
           $user=StockUser::where('id',$hu['stock_user_id'])->field('money,total_price')->find();
           if($user){
             $user->money+=$hu['ratio']*$orderPrice*0.01;
             $user->total_price+=$hu['ratio']*$orderPrice*0.01;
             $user->save();
           }
           $sharePrice+=$hu['ratio']*$orderPrice*0.01;
        }  
        if($sharePrice>0){
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入其中股东分红扣除'.$sharePrice.'元'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }else{
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }        
        $store->save();
        self::shareOrder($order);
    }
    //分销订单
    private function  shareOrder($order=[]){
        $share_setting=Option::get_data($order->acid,'platform','app_share_setting');
        $share_setting=json_decode($share_setting,1);
        if(isset($share_setting['status'])){
             if($share_setting['status']){
                //一级
                $parent1_id=User::where('id',$order->user_id)->value('parent_id');
                if($share_setting['one']>0){
                    if($parent1_id){
                        $price=$share_setting['one']*0.01*$order->price;
                        self::shareUserMoney($order,$parent1_id,$price,$order->user_id);
                    }
                }
                //二级
                if($share_setting['two']>0){
                    if($parent1_id){
                        $parent2_id=User::where('id',$parent1_id)->value('parent_id');
                        $price=$share_setting['one']*0.01*$order->price;
                        if($parent2_id){
                            self::shareUserMoney($order,$parent2_id,$price,$parent1_id);
                        }
                    }
                }
             }
        }
    }
    private function shareUserMoney($order=[],$user_id=0,$price=0,$child_userid=0){
        if($price>0){
            $user=User::where('id',$user_id)->find();
            if(!$user){
                return false;
            }
            $user->price+=$price;
            $user->total_price+=$price;
            $user->save();
            $shareOrder=new ShareOrder();
            $shareOrder->save([
                'acid'=>$order->acid,
                'user_id'=>$user_id,
                'form_user_id'=>$child_userid,
                'user_type'=>ShareOrder::USER_TYPE_USER,
                'type'=>ShareOrder::TYPE_HOUSE,
                'order_id'=>$order->id,
                'price'=>$price,
                'status'=>2,
                'pay_time'=>time()
            ]);
            (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_SHARE,
                'account_type'=>Bill::ACCOUNT_TYPE_USER,
                'form_id'=>$user_id,
                'order_id'=>$shareOrder->id,
                'price'=>$price,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'des'=>'分销佣金:茶室预订'
            ]);
        }
    }
}