<?php
namespace app\hotel\logic\user;
use app\hotel\model\User;
use app\hotel\model\Store;
use app\hotel\model\Area;
use app\hotel\model\House;
use app\hotel\model\Option;
use app\hotel\model\GoodsCat;
use app\hotel\model\Goods;
use app\hotel\model\Tags;
use app\hotel\model\Collection;
use app\hotel\model\HouseRoomStock;
use app\hotel\model\HouseRoom;
use app\hotel\model\ApplyBecomeStore;
use app\hotel\model\HouseDiscounts;
use think\exception\ValidateException;
use app\BaseController;
use LddContract\LddContract;
class StoreForm extends  Base
{
  //民宿列表
	public function info(){
       $store_id=input('store_id');
       $store=Store::where(['acid'=>$this->acid,'id'=>$store_id,'is_delete'=>0])->field('id,name,address,tags,tel,dec,longitude,banner,logo,policy,is_shop,appearance,interior,service_facilities,facilities,housestatus,publicarea,base_info')->find();
       if(!$store){
          return fetchJson([],'暂无数据',1);
       }
       $store['banner']=get_file_urls($store['banner']);
       $store['logo']=get_file_url($store['logo']);
       $store['longitude']=explode(',', $store['longitude']);
       $store['appearance']=explode(',', $store['appearance']);
       $store['interior']=explode(',', $store['interior']);
       $store['housestatus']=explode(',', $store['housestatus']);
       $store['publicarea']=explode(',', $store['publicarea']);
       $store['base_info']=json_decode($store['base_info'],1);
       $store['service_facilities']=explode(',',$store['service_facilities']);
       $store['facilities']=explode(',',$store['facilities']);
       $tags=Tags::where(['acid'=>$this->acid])->where('id','in',explode(',', $store['tags']))->column('id,title');
       $store['tags']=$tags;
       $keyword=input('keyword');
       $list=House::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$store_id,'status'=>1])
       ->select()
       ->toArray();
       $book_date=[];
       $start_date=input('start_date');
       $end_date=input('end_date');
       $start_date=$start_date?strtotime($start_date):strtotime(date('Y-m-d'));
       $end_date=$end_date?strtotime($end_date):strtotime(date('Y-m-d'))+86400;

       $night_num=($end_date-$start_date)/86400;
       for($i=0;$i<$night_num;$i++){ 
           $book_date[]=date('Y-m-d',($start_date+(86400*$i)));
       }
       foreach ($list as $key => &$value) {
           $value['cover_url']=get_file_url($value['cover']);
           $value['service_facilities']=json_decode($value['service_facilities'],1);
           $value['longitude']=explode(',',$value['longitude']);
           $value['tags']=explode(',', $value['tags']);
           $value['is_free']=$value['price']==$value['member_price']?1:0;
           $value['house_bed']=json_decode($value['house_bed'],1);
           $value['house_bed_num']=array_sum(array_column($value['house_bed'], 'num'));
           $value['tip_title']='会员免费房';
           $room=HouseRoom::where(['house_id'=>$value['id'],'status'=>1])->column('id');
           $book_roomNum=0;
           foreach ($room as $roomValue) {
                if(!HouseRoomStock::where(['house_id'=>$value['id']])
                  ->where('status','>',0)
                  ->where('room_id',$roomValue)
                  ->whereIn('date',$book_date)
                  ->count()){
                  $book_roomNum++;
                }
           }
           $value['book_roomNum']=$book_roomNum;
           if($value['is_every_day_special']){
              $everyDaySpecial=HouseDiscounts::getHouse($value['acid'],HouseDiscounts::EVERYDAYSPECIAl,$value['id']);
               
              if($everyDaySpecial){
                  $value['every_day_special']=$everyDaySpecial;
              }
           }
           if($value['is_even_live_preferential']){
              $everyDaySpecial=HouseDiscounts::getHouse($value['acid'],HouseDiscounts::EVERLIVEPREFERENTIAL,$value['id']);

              if($everyDaySpecial){
                  $value['even_live_preferential']=$everyDaySpecial;
              }
           }
           if($value['is_early']){
              $everyDaySpecial=HouseDiscounts::getHouse($value['acid'],HouseDiscounts::EARLY,$value['id']);
              if($everyDaySpecial){
                  $value['early']=$everyDaySpecial;
              }
           }
       }
       $user_id=User::where('access_token',input('access_token'))->value('id');
       $is_collection=Collection::where(['type'=>1,'form_id'=>$store_id,'is_delete'=>0,'user_id'=>$user_id])->count();
       $store['tel']=Option::get_data($this->acid,'platform','customer_service_tel');
       return fetchJson([
          'info'=>$store,
          'is_collection'=>$is_collection,
          'house_list'=>$list
       ]);
  }

  public function mall(){
       $store_id=input('store_id');
       $store=Store::where(['acid'=>$this->acid,'id'=>$store_id])->field('id,shop_banner')->find();
       if(!$store){ 
          return fetchJson([],'暂无数据',1);
       }
       $shop_banner=get_file_urls($store['shop_banner']);
       $cat_list=GoodsCat::where(['acid'=>$this->acid,'store_id'=>$store_id,'parent_id'=>0,'is_delete'=>0])->order('sort DESC')->column('id,title,cover');
       foreach ($cat_list as &$cat) {
           $cat['cover']=get_file_url($cat);
       }
        $hotsell_list=Goods::where(['acid'=>$this->acid,'is_store_hotsell'=>1,'is_delete'=>0,'store_id'=>$store_id])
        ->field('id,name,price,original_price,cover')->limit(10)->select();
        foreach ($hotsell_list as $key => &$hotsell) {
            $hotsell['cover_url']=get_file_url($hotsell['cover']);
        }
        $choiceness_list=Goods::where(['acid'=>$this->acid,'is_store_choiceness'=>1,'is_delete'=>0,'store_id'=>$store_id])
        ->field('id,name,price,original_price,cover')->limit(10)->select();
        foreach ($choiceness_list as $key => &$choiceness) {
            $choiceness['cover_url']=get_file_url($choiceness['cover']);
        }
       return fetchJson([
          'banner_list'=>$shop_banner,
          'cat_list'=>$cat_list,
          'choiceness_list'=>$choiceness_list,
          'hotsell_list'=>$hotsell_list
       ]);
  }
  public function area_info(){
      //
      $info=Area::where('id',input('id'))->find();
      if($info){
        $info['administrative_list']=explode(',', $info['administrative']);
        $info['business_list']=explode(',', $info['business']);
      }
      return fetchJson($info);
  }
  //商户列表
  public function list(){
       $query=House::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1]);
       $store_ids=Store::where(['acid'=>$this->acid,'is_delete'=>0])->column('id');
       if(!$store_ids){
          $store_ids=['-1'];
       }
       $query->where('store_id','in',$store_ids);
       if($keyword=input('keyword')){
           $store_ids=Store::where(['acid'=>$this->acid,'is_delete'=>0])->where('name','like',"%{$keyword}%")->column('id');
           $query->where('store_id','in',$store_ids);//->where('name|id','like',"%{$keyword}%")
       }
       if($area_id=input('area_id')){
          $query->where('area_id',$area_id);
       }
       if($house_count=input('house_count')){
          $query->where('house_count',$house_count);
       }
       if($category_id=input('category_id')){
          $query->where('category_id',$category_id);
       }
       if($administrative=input('administrative')){
          $query->where('administrative','in',explode(',', $administrative));
       }
       if($business=input('business')){
          $query->where('business','in',explode(',', $business));
       }
       if($sort=input('sort')){
          switch ($sort) {
            case '2'://高价排序
              $query->order('price DESC');
              break;
            case '3'://低价排序
              $query->order('price ASC');
              break;
             case '4'://新品优先 
              $query->order('id DESC');
              break;     
            default:
              break;
          }
       }
       if($sort==1){
        //根据经纬度查询
        $query->field('cover cover_url,id,name,price,member_price,service_facilities,longitude,tags,address,store_id,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - '.input('lat').' * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos('.input('lat').' * pi() / 180) * pow(sin((lng * pi() / 180 - '.input('lng').' * pi() / 180) / 2),2))) * 1000) as distance')
         ->order('distance');
       }else{
         $query->field('cover cover_url,id,name,price,member_price,service_facilities,longitude,tags,address,store_id');
       }
       $list=$query
       ->page($this->page)
       ->group('store_id')
       ->select()
       ->toArray();
       foreach ($list as $key => &$value) {
           $store=Store::where('id',$value['store_id'])->find();
           $value['name']=$store['name'];
           $value['cover_url']=get_file_url($store['logo']);
           $value['service_facilities']=json_decode($value['service_facilities'],1);
           $value['longitude']=explode(',', $store['longitude']);
           $value['tags']=explode(',', $value['tags']);
           $value['is_free']=$value['price']==$value['member_price']?1:0;
       }
       return fetchJson($list);
    }
    //申请成为商家
    public function apply_become_store(){
        try {
            $data=request()->post();
            $rule = [
                'name|名称'=>'require',
                'logo|商家logo'=>'require',
                'banner|民宿图片'=>'require',
                'area_id|区域ID'=>'require|number',
                'contractID|合同编号'=>'require',
                'customerID|客户编号'=>'require',
                'appearance|外观'=>'require',
                'publicarea|公共区域'=>'require',
                'address|酒店地址'=>'require',
                'area|区域地址'=>'require',
                'house_num|客房数量'=>'require',
                'license_type|执照类型'=>'require',
                'license_name|执照名称'=>'require',
                'license_image|执照图片'=>'require',
                'license_status|长期有效'=>'require|number|in:1,0',
                'license_date|执照有效期'=>'require',
                'identity_card_front|身份证正面'=>'require',
                'identity_card_reverse|身份证反面'=>'require',
                'user_name|姓名'=>'require',
                'identity_card_number|身份证号码'=>'require',
                'is_public|是否对公'=>'require',
                'bank_name|银行名称'=>'require',
                'bank_sub|支行'=>'require',
                'email|经营者邮箱'=>'require',
                'phone|经营者手机'=>'require',
                'tel|前台电话'=>'require',
            ];
            $this->validate($data,$rule);
        }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        $config=Option::get_data($this->acid,'hotel','LddContractConfig');
        $config=json_decode($config,1);
        //下载合同
        (new LddContract($config))->downLoadContract($data);
        $form= new ApplyBecomeStore();
        $form->acid=$this->acid;
        $form->name=$data['name'];
        $form->logo=$data['logo'];
        $form->banner=$data['banner'];
        $form->area_id=$data['area_id'];
        $form->appearance=input('appearance');
        $form->publicarea=input('publicarea');
        $form->address=input('address');
        $form->house_num=input('house_num');
        $form->license_type=input('license_type');
        $form->license_name=input('license_name');
        $form->license_image=input('license_image');
        $form->license_status=input('license_status')?1:0;
        $form->license_date=input('license_date');
        $form->identity_card_front=input('identity_card_front');
        $form->identity_card_reverse=input('identity_card_reverse');
        $form->user_name=input('user_name');
        $form->identity_card_number=input('identity_card_number');
        $form->is_public=input('is_public');
        $form->bank_name=input('bank_name');
        $form->bank_sub=input('bank_sub');
        $form->bank_number=input('bank_number');
        $form->email=input('email');
        $form->phone=input('phone');
        $form->scheme=input('scheme');
        $form->tel=input('tel');
        $form->contractID=$data['contractID'];
        $form->customerID=$data['customerID'];
        $form->save();
        return fetchJson([],'提交申请成功');
    }
    
}