<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ItemController extends Controller
{
  //获取套餐
  public function UpdateItem()
  {
    $hospital_id =request('hospital');
    if(!isset($hospital_id))  return \Yz::echoError1('医院不能为空');
    date_default_timezone_set('PRC');
    $data=[
      "价格下限"=>"0","价格上限"=>"999999","性别"=>null,"妇检"=>false,"套餐Id"=>null
    ];
    $peis=new PEISApiController();
    $info= $peis::Post('自选项目查询',$hospital_id,$data,false);
    $successCount=0;//成功的数量

    if(count($info['data'])>0){
      $items=$info['data'];
      //查询医院下所有缓存的套餐
      $db_items_all=DB::table('items')->where(['hospital_id'=>$hospital_id])->get();
      foreach($db_items_all as $key=>$db_items){
        $cunzai=false;
        foreach ($items as $c_key=>$item){
          if($db_items->item_id==$item['Id']){
            $cunzai=true;
          }
        }
        if(!$cunzai){
          DB::table('items')->where(['id'=>$db_items->id])->update([
            'status'=>0
          ]);
        }
      }
      foreach ($items as $c_key=>$item){
        $sex=null;
        if(isset($item['性别限制'])){
          $sex_array=['全部'=>0,'男'=>1,'女'=>2];
          $sex=$sex_array[$item['性别限制']]>=0?$sex_array[$item['性别限制']]:null;
        }

        $db_item=DB::table('items')->where(['hospital_id'=>$hospital_id,'item_id'=>$item['Id']])->first();
        $ItemData=[
          'hospital_id'=>$hospital_id,
          'item_id'=>$item['Id'],
          'sex'=>$sex,
          'name'=>$item['名称'],
          'pinyin'=>$item['拼音'],
          'price'=>$item['价格'],
          'is_choose'=>$item['可选']===false ? "0" : "1",
          'keshi_id'=>$item['科室Id'],
          'keshi_name'=>$item['科室名称'],
          'beizhu'=>$item['备注'],
          'jianjie'=>$item['简介'],
          'status'=>1,
          'updated_at'=>date('Y-m-d H:i:s'),
        ];
        if(!!$db_item){
          //如果存在项目
          $u=DB::table('items')->where(['hospital_id'=>$hospital_id,'item_id'=>$item['Id']])->update($ItemData);
        }else{
          //如果不存在套餐
          $u= DB::table('items')->insert($ItemData);
        }
        if($u){
          $successCount++;
        }else{
          return \Yz::echoError1('更新失败');
        }

      }

      return \Yz::Return(true,'操作完成',['success_count'=>$successCount,'combos_count'=>count($items)]);

    }else{
      return \Yz::echoError1('未查询到套餐');
    }
  }
}
