<?php
namespace app\shared\logic\pay;
use app\shared\model\HouseOrder;
use app\shared\model\ShareOrder;
use app\shared\model\House;
use app\shared\model\WeixinUser;
use app\shared\model\User;
use app\shared\model\Option;
use app\shared\model\App;
use app\shared\model\HouseRoom;
use app\shared\model\CouponUser;
use app\shared\model\StoreCouponUser;
use app\shared\model\StoreCleaning;
use app\shared\model\CardUserOrder;
use app\shared\model\CardUser;
use app\shared\model\CardCoupon;
use app\shared\model\CardCouponOrder;
use app\shared\model\StoreUserMoney;
use app\shared\model\HouseStock;
use app\shared\model\Bill;
use app\shared\model\Store;
use app\shared\model\PartnerUser;
use app\shared\model\PartnerUserOrder;
use app\shared\model\PartnerUserBill;
use app\shared\model\Electricity;
use app\shared\model\ElectricityLine;
use app\shared\model\LumiElectricityConfig;
use think\facade\Cache;
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;
class HouseOrderForm
{
    
    //获取数据
    public  function saveOrder($order_no='',$xml_array=[]){
    	$order=HouseOrder::where('order_no',$order_no)->find();
        if(!$order){
            echo "success";
            exit();
        }
    	if($order->is_pay==1){
           if($order->pay_type==1){
                echo "success";
                exit();
            }else{
                return "success";
            }
        }
        $order->pay_time=time();
    	$order->status=1;
        $order->xml_array=json_encode($xml_array);
    	$order->is_pay=1;
    	$order->save();
        //优惠券
        CouponUser::where(['id'=>$order->coupon_user_id])->update(['is_use'=>1,'use_time'=>time(),'order_id'=>$order->id]);
        $storeCouponUser=StoreCouponUser::where(['id'=>$order->store_coupon_user_id])->find();
        if($storeCouponUser){
            $order->price-=$storeCouponUser->discounts_price;
            $order->save();
            $storeCouponUser->save(['is_use'=>1,'use_time'=>time(),'order_id'=>$order->id]);
        }
        HouseStock::where([
            'acid'=>$order->acid,
            'house_id'=>$order->house_id,
            'order_id'=>$order->id,
            'store_id'=>$order->store_id,
        ])->update(['status'=>1]);
        //------------------------------------
        $start_time=$order->start_time;
        if($order['book_type']==3){
           $minute=date('i',$start_time);
           $hour=date('Y-m-d H',$start_time).":00";
           if($minute<=30&&$minute>0){
              $hour=strtotime($hour);
           }
           if($minute>30){
              $hour=strtotime($hour)+1800;
           }
           $start_time=$hour;
        }
         $stockInsert=[];
         $numB=($order->end_time-$start_time)/1800;
         for ($j=0;$j<$numB+1;$j++){
           $time=$start_time+(1800*$j);
           if($time>($start_time-1800)&&$time<($order->end_time+1800)){
                $stockOrder=HouseStock::where([
                    'acid'=>$order->acid,
                    'date'=>strtotime(date('Y-m-d',$time)),
                    'house_id'=>$order->house_id,
                    'hour'=>$time,
                    'store_id'=>$order->store_id,
                ])->find(); 
                if(!$stockOrder){
                    $stockInsert[]=[
                        'acid'=>$order->acid,
                        'date'=>strtotime(date('Y-m-d',$time)),
                        'house_id'=>$order->house_id,
                        'hour'=>$time,
                        'order_id'=>$order->id,
                        'store_id'=>$order->store_id,
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                }else{
                    $stockOrder->order_id=$order->id;
                    $stockOrder->status=0;
                    $stockOrder->save();
                }
           } 
        }
        //------------------------------------
        HouseStock::insertAll($stockInsert);
        self::decUserBill($order);
        self::sendSubscribe($order);
        //卡券处理
        $cardCoupon=CardCoupon::where(['id'=>$order->card_coupon_id])->find();
        if($cardCoupon){
            if($cardCoupon->start_time<time()&&$cardCoupon->end_time>time()){
                $cardCoupon->num-=1;
                if($cardCoupon->num<=0){
                    $cardCoupon->status=0;
                }
            }else{
                 $cardCoupon->status=0;
            }
            $cardCoupon->save();
            CardCouponOrder::where(['order_id'=>$order->id])->update(['status'=>1,'use_time'=>time()]);
        }
        //更新合伙人订单状态
        self::partnerOrderBill($order);
        self::thatIsOrder($order);
        if($order->pay_type==1){
            echo "success";
            exit();
        }else{
            return "success";
        }
    }
    //更新合伙人订单状态
    public function partnerOrderBill($order=[]){
        $partnerOrder=PartnerUserOrder::where(['order_id'=>$order->id])->find();
        if($partnerOrder){
            $partnerOrder->status=1;
            $partnerOrder->save();
            $partnerUser=PartnerUser::where(['id'=>$partnerOrder->user_partner_id])->find();
            if($partnerUser){
                $partnerUser->money-=$partnerOrder->price;
                $partnerUser->money=$partnerUser->money<0?0:$partnerUser->money;
                $partnerUser->save();
                (new PartnerUserBill())->save([
                    'acid'=>$order->acid,
                    'user_id'=>$order->user_id,
                    'order_id'=>$order->id,
                    'title'=>'茶室订单消费',
                    'price'=>$partnerOrder->price,
                    'status'=>-1
                ]);
            }
        }
    }
    //增加商户账单
    public function addStoreBill($order=[]){
        $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();
    }
    //减少用账单
    public function decUserBill($order=[]){
        $user=User::where('id',$order['user_id'])->find();
        
        if($order->pay_type==2){
            $user->money-=$order['pay_price'];
            $user->save();
        }
        $balance=$user->money;
        if($order->pay_type==3){
            $userStore=StoreUserMoney::where(['store_id'=>$order->store_id,'user_id'=>$order->user_id])->find();
            if($userStore){
                
                $userStore->money-=$order['pay_price'];
                $userStore->save();
                $balance=$userStore->money;
            }
        }
        $cardUserOrder=CardUserOrder::where(['order_id'=>$order['id'],'type'=>1])->find();
        if($cardUserOrder){
            $cardUserOrder->status=1;
            $cardUserOrder->save();
            $cardUser=CardUser::where('id',$cardUserOrder->card_user_id)->find();
            if($cardUser){
                $cardUser->hour-=$cardUserOrder['hour'];
                $cardUser->hour=$cardUser->hour<0?0:$cardUser->hour;
                $cardUser->save();
            }
        }
        (new Bill())->save([
            'acid'=>$order->acid,
            'type'=>$order->pay_type==3?Bill::TYPE_STORE_USER_HOUSE:Bill::TYPE_HOUSE,
            'account_type'=>Bill::ACCOUNT_TYPE_USER,
            'form_id'=>$order['user_id'],
            'order_id'=>$order['id'],
            'price'=>$order['pay_price'],
            'price_type'=>$order['pay_type'],
            'balance'=>$balance,
            'status'=>-1,
            'des'=>'用户: 【'.$user->nickname.'】茶室预订'
        ]);
    }
    public function  shareOrder($order=[]){
        if($order->pay_type==3){
            return 0;
        }
        $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);
                        }
                    }
                }
             }
        }
    }
    public function shareUserMoney($order=[],$user_id=0,$price=0,$child_userid=0){
        if($order->pay_type==3){
            return 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'=>'分销佣金:茶室预订'
            ]);
        }
    }
   public function sendSubscribe($order=[]){
        set_time_limit(0);
        $account=User::where(['id'=>$order->user_id])->value('account');
        $openid=WeixinUser::where(['mobile'=>$account])->value('wxapp_open_id');
        $snapshoot=json_decode($order->snapshoot,1);
        $app=App::where('id',$order->acid)->field('id acid,wx_app_id,wx_app_secret,wxapp_app_id,wxapp_app_secret')->find();
        $app['wx_subscibe_book_finish']=Option::get_data($order->acid,'platform','wx_subscibe_book_finish');
        $app['wx_subscibe_book_overtime']=Option::get_data($order->acid,'platform','wx_subscibe_book_overtime');
        $app['wx_subscibe_book_inform']=Option::get_data($order->acid,'platform','wx_subscibe_book_inform');
        $app['wx_subscibe_book_sweep']=Option::get_data($order->acid,'platform','wx_subscibe_book_sweep');
        $app['wx_template_cleaning_inform']=Option::get_data($order->acid,'platform','wx_template_cleaning_inform');
        $app['wx_template_cleaning_port_inform']=Option::get_data($order->acid,'platform','wx_template_cleaning_port_inform');
        $store=Store::where('id',$order['store_id'])->field('name,openid')->find();

        //缓存单个数据
        $listArray=[
            'wx_template'=>[
                'cleaning_inform'=>$app['wx_template_cleaning_inform']//保洁员openid
            ],
            'book_finish'=>0,
            'book_overtime'=>0,
            'book_inform'=>0,
            'order'=>[
                'openid'=>$openid,
                'page'=>'order/orderDetail?id='.$order->id,
                'order_no'=>$order->order_no,
                'title'=>$snapshoot['name'],
                'store_name'=>$store['name'],
                'start_time'=>$order->start_time,
                'end_time'=>$order->end_time,
                'remark'=>'备注',
                'phone'=>$order->tel,
                'cleaning_openid'=>$store['openid']
            ],
            'app'=>$app
        ];
        Cache::set('subscribeOrder'.$order->id,json_encode($listArray));
        $list=Cache::get('subscribeOrder');
        $list=json_decode($list,1);
        $listArray=[];
        if(!$list){
            $listArray[]=[
                'start_time'=>$order->start_time,
                'end_time'=>$order->end_time,
                'order_id'=>$order->id,
            ];
        }else{
            foreach ($list as $key => $value){
                if(isset($value['end_time'])){
                    if($value['end_time']>time())
                      $listArray[]=$value;
                }
            }
            $listArray[]=[
                'start_time'=>$order->start_time,
                'end_time'=>$order->end_time,
                'order_id'=>$order->id,
            ];
        }
        Cache::set('subscribeOrder',json_encode($listArray));
        
        //发送保洁人员
        $weixin=new \weixin\Wechat();
        $data=[
            "first"    =>[
              "value"  =>"用户下单提醒",
              "color"  =>"#173177"
            ],
            "keyword1" =>[
              "value"  =>$snapshoot['name'],//房间名称：
              "color"  =>"#173177"
            ],
            "keyword2" =>[
              "value"  =>$store['name'],//保洁员：
              "color"  =>"#173177"
            ],
            "keyword3" =>[
              "value"  =>"共享茶室",//保洁类型：
              "color"  =>"#173177"
            ],
            "keyword4" =>[
              "value"  =>date('Y-m-d H:i:s',$order->start_time).'之前', //保洁时间：
              "color"  =>"#173177"
            ],
            "remark"   =>[
              "value"  =>'用户订单时间'.date('Y-m-d H:i:s',$order->start_time).'至'.date('Y-m-d H:i:s',$order->end_time),
              "color"  =>"#173177"
            ]
        ];
        $openidArr=explode(',', $store['openid']);
        foreach ($openidArr as $openid) {
            $res=$weixin->sendWxopenTemplate($app,$app['wx_template_cleaning_inform'],$openid,"pages/index/index",$data);
        }
        self::sendCleaningTpl($app,$order);
        
    }
    //保洁端用户下单提醒
    public function sendCleaningTpl($app,$order){
        set_time_limit(0);
        $cleaning= StoreCleaning::where(['acid'=>$order->acid,'store_id'=>$order->store_id,'is_delete'=>0,'status'=>1])->where('openid','<>','')->column('openid,account');
        $snapshoot=json_decode($order->snapshoot,1);
        $store=Store::where('id',$order->store_id)->field('address,name')->find();
        //发送保洁人员
        $weixin=new \weixin\Wechat();
        $data=[
            "first"    =>[
              "value"  =>"用户在店【{$store['name']}】"."下单提醒",
              "color"  =>"#173177"
            ],
            "keyword1" =>[
              "value"  =>$snapshoot['name'],//房间名称：
              "color"  =>"#173177"
            ],
            "keyword2" =>[
              "value"  =>$store['address'],//房间地址：
              "color"  =>"#173177"
            ],
            "keyword3" =>[
              "value"  =>date('Y-m-d H:i:s',$order->end_time).'之后', //保洁时间：
              "color"  =>"#173177"
            ],
            "remark"   =>[
              "value"  =>'用户订单时间'.date('Y-m-d H:i:s',$order->start_time).'至'.date('Y-m-d H:i:s',$order->end_time),
              "color"  =>"#173177"
            ]
        ];
        foreach($cleaning as $value){
            $res=$weixin->sendWxopenTemplate($app,$app['wx_template_cleaning_port_inform'],$value['openid'],"pages/index/index",$data);
            \app\shared\model\MessageLog::pushMsg($order->acid,$value['account'],$order->order_no,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($res));
        }
    }
    public function thatIsOrder($order=[]){
        if($order['book_type']!=3){
            return 0;
        }
        $house=House::where(['id'=>$order->house_id])->find();
        if($house['electricityid']=="-1"||$house['electricityid']=="0"||$house['electricityid']==''){    
            //绿米
            $ahead_time=$house['ahead_time']*60;
            $forward_time=$house['forward_time']*60;
            self::lvjoinTask($house,$order,$order->start_time-$ahead_time,$order->end_time+$forward_time);
            return 0;
        }

        $mac=$house['electricityid'];
        $smart_device=Store::where('id',$order->store_id)->value('smart_device');
        $smart_device=json_decode($smart_device,1);
        //曼顿取电
        $config=[
            'appKey'=>$smart_device['electronic_mandun_appKey'],
            'appSecret'=>$smart_device['electronic_mandun_appSecret'],
            'uname'=>$smart_device['electronic_mandun_uname'],
            'passwd'=>$smart_device['electronic_mandun_passwd'],
            'projectCode'=>$smart_device['electronic_mandun_projectCode'],
            'api_url'=>$smart_device['electronic_mandun_apiUrl'],
        ];
        $lineList=ElectricityLine::where([
            'acid'=>$house['acid'],
            'store_id'=>$house['store_id'],
            'mac'=>$house['electricityid'],
            'house_id'=>$house['id'],
            'is_delete'=>0
         ])->column('line,ahead_time,forward_time');
        foreach ($lineList as $key => $value) {
           $ahead_time=$value['ahead_time']*60;
           $forward_time=$value['forward_time']*60;
           self::joinTask($order->acid,$house['is_network'],$house['lockid'],$order->id,1,$config,$house['electricityid'],$value['line'],($order->start_time-$ahead_time),($order->end_time+$forward_time));
        }
    }
    //加入任务
    public function joinTask($acid=1,$is_network,$lockid,$order_id,$type,$config,$mac,$line,$start_time,$end_time){
        $form=Electricity::where(['acid'=>$acid,'order_id'=>$order_id,'mac'=>$mac,'line'=>$line])->find();
        if(!$form){
            $form=new Electricity();
            $form->status=0;
            $form->mac=$mac;
            $form->line=$line;
        }
        $form->save([
          'acid'=>$acid,
          'config'=>json_encode($config),
          'order_id'=>$order_id,
          'lockid'=>$lockid,
          'start_time'=>$start_time,
          'end_time'=>$end_time
        ]);
        $task=new \app\shared\controller\Task();
        $task->handleOther($form->id,$start_time,$end_time,3);
    }
     //加入绿米任务
    public function lvjoinTask($house,$order,$start_time,$end_time){
        $lumi_electricity_config=LumiElectricityConfig::where([
            'acid'=>$order->acid,
            'store_id'=>$house['store_id'],
            'house_id'=>$house['id'],
            'is_delete'=>0
        ])->column('dev_did,dev_model,resource,ahead_time,forward_time');
        $params=[];
        $status=input('status');
        foreach ($lumi_electricity_config as &$vlm){
            $resources=[];
            $resource=json_decode($vlm['resource'],1);
           foreach ($resource as $v){
              $resources[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$status,
              ];
           }
           $params[]=[
            'subjectId'=>$vlm['dev_did'],
            'resources'=>$resources,
           ];
        }
        $lvmi_device=Store::where(['id'=>$house['store_id']])->value('lvmi_device');
        $lvmi_device=json_decode($lvmi_device,1);
        $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
        $form=Electricity::where(['acid'=>$order->acid,'order_id'=>$order['id'],'config'=>json_encode($params)])->find();
        if(!$form){
            $form=new Electricity();
            $form->status=0;
        }
        $form->save([
          'acid'=>$order->acid,
          'config'=>json_encode($params),
          'order_id'=>$order['id'],
          'mac'=>$accessToken,
          'start_time'=>$start_time,
          'end_time'=>$end_time
        ]);
        $task=new \app\shared\controller\Task();
        $task->lvhandleOther($form->id,$start_time,$end_time);
    }
}