<?php

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

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

class ComboController extends Controller
{
  //获取套餐
  public function UpdateCombo()
  {
    $hospital_id = request('hospital');
    date_default_timezone_set('PRC');
    $data = [
      "价格下限" => "0", "价格上限" => "999999", "性别" => null, "妇检" => false
    ];
    $peis = new PEISApiController();
    $info = $peis::Post('套餐查询', $hospital_id, $data, false);
    $successCount = 0;//成功的数量
    if (count($info['data']) > 0) {
      $combos = $info['data'];
      //查询医院下所有缓存的套餐
      $db_combo_all = DB::table('combos')->where(['hospital_id' => $hospital_id])->get();
      foreach ($db_combo_all as $key => $db_combo) {
        $cunzai = false;
        foreach ($combos as $c_key => $combo) {
          if ($db_combo->combo_id == $combo['Id']) {
            $cunzai = true;
          }
        }
        if (!$cunzai) {
          DB::table('combos')->where(['id' => $db_combo->id])->update([
            'status' => 0
          ]);
        }
      }
      foreach ($combos as $c_key => $combo) {
        $sixin_combo_item_ids=[];//思信套餐内项目ids

        $item = [];
        $comboDetail = $peis::Post('套餐详情查询', $hospital_id, ['套餐Id' => $combo['Id']], false);
        if ($comboDetail['code'] != 0) return \Yz::echoError1("套餐详情查询失败");

        $comboDetail_list = $comboDetail['data'][0]['包含项目'];
        foreach ($comboDetail_list as $key => $v) {
          $sixin_combo_item_ids[]=$v['Id'];
          //在独立表中缓存一份套餐对应的项目信息
          $item_sex = null;
          if (isset($v['性别限制'])) {
            $item_sex_array = ['全部' => 0, '男' => 1, '女' => 2];
            $item_sex = $item_sex_array[$combo['性别限制']] >= 0 ? $item_sex_array[$combo['性别限制']] : null;
          }
          $item_date = [
            'combo_id'=>$combo['Id'],
            'item_id'=>$v['Id'],
            'name'=>$v['名称'],
            'desc' => $v['简介'],
            'keshi_id' => $v['科室Id'],
            'keshi_name' => $v['科室名称'],
            'price'=> $v['价格'],
            'sex'=>$item_sex,
            'can_qian_hou'=>$v['餐前餐后'],
            'status'=>1
          ];
          $db_combo_item = DB::table('combo_items')->where(['item_id' => $v['Id'], 'combo_id' => $combo['Id']])->first();
          if (!!$db_combo_item) {
            //如果存在项目
            $u = DB::table('combo_items')->where(['id' => $db_combo_item->id])->update($item_date);
          } else {
            //如果不在项目
            $u = DB::table('combo_items')->insert($item_date);
          }


          $item[] = [
            'id' => $v['Id'],
            'name' => $v['名称'],
            'desc' => $v['简介'],
            'keshi_name' => $v['科室名称'],
          ];
        }


        //查询当前套餐缓存的套餐项目ids
        $db_combo_item_ids=DB::table('combo_items')
          ->where(['combo_id' => $combo['Id']])->pluck('item_id')->toArray();
        // 查询在库里缓存但思信已经没有的项目ids,标注为弃用0
        $k_ids = array_diff($db_combo_item_ids, $sixin_combo_item_ids);
        if(count($k_ids)>0){
          DB::table('combo_items')->whereIn('item_id',$k_ids)->update(['status'=>0]);
        }


        $item = json_encode($item, JSON_UNESCAPED_UNICODE);
        $sex = null;
        if (isset($combo['性别限制'])) {
          $sex_array = ['全部' => 0, '男' => 1, '女' => 2];
          $sex = $sex_array[$combo['性别限制']] >= 0 ? $sex_array[$combo['性别限制']] : null;
        }

        $db_combo = DB::table('combos')->where(['hospital_id' => $hospital_id, 'combo_id' => $combo['Id']])->first();
        $comboData = [
          'hospital_id' => $hospital_id,
          'combo_id' => $combo['Id'],
          'sex' => $sex,
          'name' => $combo['名称'],
          'pinyin' => $combo['拼音'],
          'original_price' => $combo['原价'],
          'price' => $combo['价格'],
          'items' => $item,
          'item_count' => $comboDetail['data'][0]['项目数量'],
          'status' => 1,
          'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (!!$db_combo) {
          //如果存在套餐
          $u = DB::table('combos')->where(['hospital_id' => $hospital_id, 'combo_id' => $combo['Id']])->update($comboData);
        } else {
          //如果不存在套餐
          $comboData['tags'] = json_encode([]);
          $u = DB::table('combos')->insert($comboData);
        }
        if ($u) {
          $successCount++;
        } else {
          return \Yz::echoError1('更新失败');
        }

      }
      $hospital = DB::table('hospitals')->where(['id' => $hospital_id])->first();
      if (!!$hospital->frequency) {
        $date = new DateTime();
        $date->modify('+' . $hospital->frequency . ' minutes');
        $formatted_time = $date->format('Y-m-d H:i:s');
        DB::table("hospitals")->where(['id' => $hospital_id])->update([
          'next_time' => $formatted_time
        ]);
      }
      return \Yz::Return(true, '操作完成', ['success_count' => $successCount, 'combos_count' => count($combos)]);

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

  public function GetList()
  {
    $page = request('page');
    $pageSize = request('pageSize');
    $searchInfo = request('searchInfo');
    $list = DB::table('combos')
      ->select('combos.*', 'hospitals.name as hospital_name', 'combo_type.name as combo_type_name', 'combo_crowd.name as combo_crowd_name')
      ->leftJoin('hospitals', 'hospitals.id', '=', 'combos.hospital_id')
      ->leftJoin('combo_type', 'combos.type_id', '=', 'combo_type.id')
      ->leftJoin('combo_crowd', 'combos.crowd_id', '=', 'combo_crowd.id');
    if (isset($searchInfo['name'])) {

      $list = $list->where('combos.name', 'like', '%' . $searchInfo['name'] . '%');
    }
    $count = $list->count();
    $list = $list
      ->skip(($page - 1) * $pageSize) // 跳过前9999条记录
      ->take($pageSize)->get();

    return \Yz::Return(true, "查询完成", ['list' => $list, 'count' => $count]);
  }

  public function GetDetail()
  {
    $id = request('id');
    $query = DB::table('combos')->where(['id' => $id])->first();
    if (!!$query) {
      $query->tags = implode(", ", json_decode($query->tags, true));
      $query->tags2 = implode(", ", json_decode($query->tags2, true));
      $query->items = json_decode($query->items);
      return \Yz::Return(true, "查询完成", $query);
    } else {
      return \Yz::echoError1("获取详情失败");
    }
  }

  public function Save()
  {
    $Info = request('Info');
    $u = DB::table('combos')->where(['id' => $Info['id']])->update([
      'checkup_type_id' => $Info['checkup_type_id'],
      'type_id' => $Info['type_id'],
      'crowd_id' => $Info['crowd_id'],
      'tags' => isset($Info['tags']) ? json_encode($Info['tags'], JSON_UNESCAPED_UNICODE) : [],
      'tags2' => isset($Info['tags2']) ? json_encode($Info['tags2'], JSON_UNESCAPED_UNICODE) : [],
      'cover' => $Info['cover'],
      'intro' => $Info['intro'],
      'sub_intro' => $Info['sub_intro'],
      'desc' => $Info['desc']
    ]);
    if ($u) {
      return \Yz::Return(true, "更新完成", []);
    } else {
      return \Yz::echoError1("没有数据更新");
    }
  }
}
