<?php
namespace app\shared\logic\pay;
use app\shared\model\HouseOrderContinue;
use app\shared\model\HouseOrder;
use app\shared\model\ShareOrder;
use app\shared\model\House;
use app\shared\model\User;
use app\shared\model\WeixinUser;
use app\shared\model\Option;
use app\shared\model\HouseRoom;
use app\shared\model\HouseStock;
use app\shared\model\Bill;
use app\shared\model\App;
use app\shared\model\Store;
use app\shared\model\StoreCleaning;
use app\shared\model\Electricity;
use app\shared\model\ElectricityLine;
use app\shared\model\LumiElectricityConfig;
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\CardUserOrder;
use app\shared\model\CardUser;
use app\shared\model\StoreUserMoney;
use app\shared\model\WxpayAccounting;
use wechatpay\WechatPay;
use slock\Slock;
use think\facade\Cache;
class HouseOrderContinueForm
{
    //获取数据
    public  function saveOrder($order_no='',$xml_array=[]){
        $order=HouseOrderContinue::where('order_no',$order_no)->find();
        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();
        $stockInsert=[];
        $start_time=$order->start_time;
        $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->order_id,
                        'store_id'=>$order->store_id,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                }else{
                    $stockOrder->order_id=$order->order_id;
                    $stockOrder->status=0;
                    $stockOrder->save();
                }
           } 
        }
        HouseStock::insertAll($stockInsert);
        self::decUserBill($order);
        self::addStoreBill($order);
        self::openRoom($order);//设备开锁
        self::sendSubscribe($order);
        if($order->pay_type==1){
            echo "success";
            exit();
        }else{
            return "success";
        }
    }
    private function openRoom($order=[]){
        $smart_device=Store::where('id',$order->store_id)->value('smart_device');
        if(empty($smart_device)){
           return false;
        }
        $smart_device=json_decode($smart_device,1);
        $house=House::where('id',$order->house_id)->find();
        $houseOrder=HouseOrder::where('id',$order->order_id)->find();
        $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'],
        ];
        if($houseOrder->end_time>time()&&$houseOrder->start_time<time()){
            $start_time=time();
        }else if($houseOrder->end_time<time()){
            $start_time=time();
        }else{
            $start_time=$houseOrder->start_time;
        }
        $end_time=$order->end_time;

        if($house['electricityid']=="-1"||$house['electricityid']=="0"||$house['electricityid']==''){
            self::lvjoinTask($house,$order,$start_time,$end_time);
        }else{
            $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($house['lockid'],$order,$order->id,2,$config,$house['electricityid'],$value['line'],($start_time-$ahead_time),($end_time+$forward_time));
            }
        }
    }
     //加入绿米任务
    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,reset_time');
        $params=[];
        $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']:'';
        foreach ($lumi_electricity_config as &$vlm){
            $resources=[];
            $resource=json_decode($vlm['resource'],1);
            foreach ($resource as $v){
              $resources[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$v['status'],
              ];
              $ahead_time=$v['ahead_time']*60;
              $forward_time=$v['forward_time']*60;
              $config=json_encode([
                [
                    'subjectId'=>$vlm['dev_did'],
                    'resources'=>$resources,
                ]
              ]);
              $form=Electricity::where(['acid'=>$order->acid,'order_id'=>$order->order_id,'config'=>$config])->find();
              if(!$form){
                    $form=new Electricity();
                    $form->status=0;
              }
              $form->save([
                  'acid'=>$order->acid,
                  'config'=>$config,
                  'order_id'=>$order->order_id,
                  'mac'=>$accessToken,
                  'line'=>-1,
                  'start_time'=>$start_time-$ahead_time,
                  'end_time'=>$end_time+$forward_time,
                  'reset_time'=>$vlm['reset_time']>0?$end_time+$forward_time+($vlm['reset_time']*60):0,
              ]);
              $task=new \app\shared\controller\Task();
              $task->lvhandleOther($form->id,$form->start_time,$form->end_time);
           }
        }
    }
    //加入任务
    public function joinTask($lockid,$order,$order_id,$type,$config,$mac,$line,$start_time,$end_time){
        if(!$mac)return;
        $form=Electricity::where(['acid'=>$order->acid,'line'=>$line,'order_id'=>$order->order_id])->find();
        if($form){
            $form->start_time=$start_time;
            $form->end_time=$end_time;
            $form->save();
            $task=new \app\shared\controller\Task();
            $task->handleOther($form->id,$start_time,$end_time);
        }
    }
    //增加商户账单
    public function addStoreBill($order=[]){
        if($order['pay_type']==1){
          sleep(10);
        }
        $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();
        $wxpayAccounting=self::WxpayAccounting($store,$order,$order->pay_price);
        if($wxpayAccounting['code']==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'=>$wxpayAccounting['data']->total_fee,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入'.$wxpayAccounting['data']->total_fee.'分账金额'.$wxpayAccounting['data']->sub_price
            ]);
           //进行了分账
           return false;
        }          
        //分红金额
        $sharePrice=0;           
        foreach($stockHouse as $hu){
           (new StockHouseUserOrder())->save([
              'acid'=>$order->acid,
              'type'=>2,
              '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){
             $store->money+=$orderPrice-$sharePrice;
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE_CONTINUE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order->store_id,
                'order_id'=>$order->id,
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order->pay_type,
                'balance'=>$store->money,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室续单收入其中股东分红扣除'.$sharePrice.'元'
            ]);
           
        }else{
             $store->money+=$orderPrice-$sharePrice;
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE_CONTINUE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order->store_id,
                'order_id'=>$order->id,
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order->pay_type,
                'balance'=>$store->money,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室续单收入'
            ]);
           
        }        
        $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'=>10])->find();
        if($cardUserOrder&&$order->pay_type!=3){
            $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_CONTINUE,
            '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 sendSubscribe($order=[]){
        $account=User::where(['id'=>$order->user_id])->value('account');
        $openid=WeixinUser::where(['mobile'=>$account])->value('wxapp_open_id');
        $app=App::where('id',$order->acid)->field('id acid,wx_app_id,wx_app_secret,wxapp_app_id,wxapp_app_secret')->find()->toArray();
        $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();
        $houseOrder=HouseOrder::where('id',$order->order_id)->find();
        $snapshoot=json_decode($houseOrder->snapshoot,1);
        //缓存单个数据
        $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->order_id,
                'order_no'=>$order->order_no,
                'title'=>$snapshoot['name'],
                'store_name'=>$store['name'],
                'start_time'=>$houseOrder['start_time'],
                'end_time'=>$order->end_time,
                'remark'=>'备注续单',
                'phone'=>$houseOrder['tel'],
                'cleaning_openid'=>$store['openid']
            ],
            'app'=>$app
        ];
        Cache::set('subscribeOrder'.$order->order_id,json_encode($listArray));
        $list=Cache::get('subscribeOrder');
        $list=json_decode($list,1);
        $listArray=[];
        if(!$list){
            $listArray[]=[
                'start_time'=>$houseOrder['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']>$order->end_time){
                        $listArray[]=$value;
                    }else{
                        $value['end_time']=$order->end_time;
                        $listArray[]=$value;
                    }
                }
            }
            $listArray[]=[
                'start_time'=>$houseOrder['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',$houseOrder['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');
        $houseOrder=HouseOrder::where('id',$order->order_id)->find();
        $snapshoot=json_decode($houseOrder->snapshoot,1);
        $store=Store::where('id',$houseOrder->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 WxpayAccounting($store,$order,$total_fee=1){
        
       if(!$order){
          return ['code'=>1];
       }
       if($order['pay_type']==2){
          return ['code'=>1];
       }
       $app=App::find($order->acid);
       if($app->wx_profit_sharing==0){
          return ['code'=>1];
       }
       if($app->wx_pay_type==1){
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$store['wx_mch_id'],
              'appsecret'=>$app->wxapp_app_secret,
              'key'=>$store['wx_key'],
              'sslcert'=>$store['wx_sslcert'],//$app->wx_cert_pem,
              'sslkey'=>$store['wx_sslkey'],//$app->wx_key_pem,
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }else{
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$app->wx_mch_id,
              'wx_server_appid'=>$app->wx_server_appid,
              'appsecret'=>$app->wxapp_app_secret,
              'wx_server_mch_id'=>$app->wx_server_mch_id,
              'key'=>$app->wx_server_key,
              'sslcert'=>$app->wx_server_cert_pem,
              'sslkey'=>$app->wx_server_key_pem,
              'sub_appid'=>$app->wxapp_app_id,
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }
      
       $is_server=$app->wx_pay_type==2?1:0;
       $xml_array=json_decode($order['xml_array'],1);
       $order_no=WxpayAccounting::crateOrderNo("FZ".$order->store_id."S");
         $store_fee=Store::where('id',$order->store_id)->value('fee');
         if($store_fee>30){
            //根据分账要求最多只能分账微信的百分之30
            $store_fee=29;
         }
         if($store_fee<=0){
            return ['code'=>1];
         }
         $form=new WechatPay($wx_config);
         $account=$app->wx_mch_id;
         $companyName=$app->wx_mch_name;
         $amount=$total_fee*$store_fee;//分账金额（分）
         $out_trade_no=$xml_array['out_trade_no'];//订单号
         $transaction_id=$xml_array['transaction_id'];//微信交易订单号
         $res=$form->profitsharingaddreceiver($account,$companyName,$is_server);
         if($res['code']==1){
            return ['code'=>1];
          //return fetchJson([],$res['msg'],1);
         }
         $res=$form->profitsharing($order_no,$transaction_id,$account,$amount,$companyName,$is_server);
         if($res['code']==0){
          if($res['data']['result_code']=="SUCCESS"){
            $form=new WxpayAccounting();
            $form->acid=$order->acid;
            $form->store_id=$order->store_id;
            $form->order_id=$order->id;
            $form->appid=$xml_array['appid'];
            $form->mch_id=$xml_array['mch_id'];
            $form->openid=$xml_array['openid'];
            $form->order_no=$order_no;
            $form->out_trade_no=$xml_array['out_trade_no'];
            $form->transaction_id=$xml_array['transaction_id'];
            $form->total_fee=$xml_array['total_fee']*0.01;
            $form->sub_price=$amount*0.01;
            $form->sub_account=$account;
            $form->sub_type=1;
            $form->save();
            return ['code'=>0,'data'=>$form];
            //return fetchJson($res,"分账成功");
          }else{
            return ['code'=>1];
            //return fetchJson([],$res['data']['err_code_des'],1);
          }
         }else{
           return ['code'=>1];
           //return fetchJson("",$res['msg'],1);
         }

    }

}