<?php

namespace App\Http\Controllers\API\H5;

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

class OrderController extends Controller
{
  public function list(Request $request)
  {
    // status 1-待支付 2-已预约 3-交易关闭 4-已完成 5-已退款
    $openid = $request->post('openid');
    $user = DB::table('web_users')->where(['openid' => $openid, 'is_del' => 0])->first();
    if (!$user) return \Yz::echoError1("openid对应用户不存在");
    $OrderList = DB::table('orders')
      ->select('id', 'title', 'status', 'name', 'appointment_time as time', 'order_number as order',
        DB::raw("CASE WHEN type = 1 THEN '个检' WHEN type = 2 THEN '团检' ELSE 'unknown' END as type"),
        'price', 'true_price', 'pay_time', 'refund_time', 'created_at')
      ->where(['web_user_id' => $user->id])->get();
    $WaitingPaymentTime = config('app.globals.WaitingPaymentTime');//支付等待時間
    foreach ($OrderList as $key => $list) {
      if ($list->status == 1) {
        $datetime = new DateTime($list->created_at);
        $timestamp = $datetime->getTimestamp();
        $list->end_time = $timestamp + (60 * $WaitingPaymentTime);
      }
    }
    $list = [[
      'id' => 1,
      'title' => '测试套餐1',
      'status' => 1,
      'name' => '陆予',
      'time' => '2024-08-05 08:00:00',
      'order' => '1234567890987654321',
      'type' => '个检',
      'price' => '4999.99',
      'true_price' => '4999.99',
      'end_time' => time() + (60 * 20)
    ], [
      'id' => 1,
      'title' => '测试套餐2',
      'status' => 2,
      'name' => '陆予',
      'time' => '2024-08-05 08:00:00',
      'order' => '1234567890987654321',
      'type' => '个检',
      'price' => '4999.99',
      'true_price' => '4999.99',
      'pay_time' => '2024-08-06 08:00:00'
    ], [
      'id' => 1,
      'title' => '测试套餐2',
      'status' => 3,
      'name' => '陆予',
      'time' => '2024-08-05 08:00:00',
      'order' => '1234567890987654321',
      'type' => '个检'
    ], [
      'id' => 1,
      'title' => '测试套餐2',
      'status' => 4,
      'name' => '陆予',
      'time' => '2024-08-05 08:00:00',
      'order' => '1234567890987654321',
      'type' => '团检',
      'price' => '4999.99',
      'true_price' => '0.01',
      'pay_time' => '2024-08-06 08:00:00',
      'report' => true,
      'decode' => 0,
    ], [
      'id' => 1,
      'title' => '测试套餐2',
      'status' => 5,
      'name' => '陆予',
      'time' => '2024-08-05 08:00:00',
      'order' => '1234567890987654321',
      'type' => '团检',
      'price' => '4999.99',
      'true_price' => '0.01',
      'refund_time' => '2024-08-06 08:00:00'
    ]];

    return \Yz::Return(true, '获取成功', [
      'list' => $OrderList
    ]);
  }

  //创建订单
  public function Create()
  {
    $hospital_id = request('hospital');
    $openid = request('openid');
    $person_id = request('person_id');
    $combo_id = request('combo_id');
    $type = request('type');//1个检2团检
    $group_id = request('group_id');//团检id
    $item_ids = request('item_ids');//自选item的ids
    $plan_id = request('plan_id');//自选item的ids

    $user = DB::table('web_users')->where(['openid' => $openid, 'status' => 1, 'is_del' => 0])->first();
    if (!$user) return \Yz::echoError1('用户不存在');
    $person = DB::table('web_user_person')->where(['id' => $person_id, 'is_del' => 0])->first();
    if (!$person) return \Yz::echoError1('体检人不存在');
    $title = "自选项目";
    $price = 0;
    $buy_info = [
      'combo' => [
        'id' => 0,
        'name' => $title,
        'price' => 0,
      ],
      'items' => [],
      'group' => [
        'id' => '',
      ],
    ];
    //如果是套餐
    if (isset($combo_id) and $combo_id <> 0) {
      $combo_info = DB::table('combos')->where(['combo_id' => $combo_id, 'status' => 1])->first();
      if(!$combo_info) return \Yz::echoError1("套餐不存在");
      $price += $combo_info->price;
      $title = $combo_info->name;
      $buy_info['combo'] = [
        'id' => $combo_info->combo_id,
        'name' => $combo_info->name,
        'price' => $combo_info->price,
      ];
    }

    //如果有自选项目
    $items_list = [];
    if (count($item_ids) != 0) {
      $items_list = DB::table('items')->whereIn('item_id', $item_ids)->where(['status' => 1])->get();
      foreach ($items_list as $item) {
        $price += $item->price;
        $buy_info['items'][] = [
          'id' => $item->item_id,
          'name' => $item->name,
          'price' => $item->price
        ];
      }
    }
    //判断号源是否可用vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    $plan = DB::table('plans')->where(['id' => $plan_id, 'hospital_id' => $hospital_id, 'status' => 1, 'is_del' => 0])->first();
    if (!$plan) return \Yz::echoError1("号源不可用");
    //判断个检/团检类型
    if ($plan->use_type <> 0 and $plan->use_type <> $type) {
      $type_temp = '';
      if ($plan->use_type == 1) $type_temp = '个检';
      if ($plan->use_type == 2) $type_temp = '团检';
      return \Yz::echoError1("此号源为" . $type_temp . "号源，不可用");
    }
    //判断是否是预留号源
    if ($plan->type <> 1) return \Yz::echoError1("此号源为预留号源，不可用");
    //判断是否是vip
    //判断性别
    if ($plan->sex <> 0 and $plan->sex <> $person->sex) return \Yz::echoError1("此号源性别与体检人性别不符，不可用");
    //判断体检类型checkup_type
    //判断金额
    if ($plan->use_type == 1 and $plan->amount_limit1 <> 0) {
      if ($price < $plan->amount_limit1) return \Yz::echoError1("未达到此号源限制的金额，不可用");
    }
    if ($plan->use_type == 2 and $plan->amount_limit2 <> 0) {
      if ($price < $plan->amount_limit2) return \Yz::echoError1("未达到此号源限制的金额，不可用");
    }
    //判断时间是否过期
    $plan_datetime=$plan->date.' '.$plan->time;
    if($plan_datetime < date('Y-m-d H:i:s')) return \Yz::echoError1("号源已过期，不可用");
    //判断号源是否可用^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    //构建订单号
    $order_num=$this->generateOrderNumber();
    $data=[
      'title'=>$title,
      'type'=>$type,
      'web_user_id'=>$user->id,
      'person_id'=>$person->id,
      'name'=>$person->name,
      'id_number'=>$person->id_number,
      'buy_info'=>json_encode($buy_info, JSON_UNESCAPED_UNICODE),
      'price'=>$price,
      'true_price'=>$price,
      'order_number'=>$order_num,
      'status'=>1,
      'appointment_date'=>$plan->date,
      'appointment_time'=>$plan->time,
      'plan_id'=>$plan->id,
      'plan_number'=>$plan->plan_number,
      'combo_id'=>$combo_id,
      'hospital_id'=>$hospital_id,
      'phone'=>$person->phone,
      'sex'=>$person->sex,
      'birthday'=>$person->birthday,
      'married'=>$person->married,
    ];
    DB::beginTransaction();
    $insert=DB::table('orders')->insert($data);
    $up_plan=DB::table('plans')->where(['id'=>$plan->id,'status'=>1])->update([
      'status'=>2
    ]);
    if($insert and $up_plan){
      DB::commit();
      return \Yz::return(true,"操作成功",[]);
    }else{
      DB::rollBack();
      return \Yz::echoError1('操作失败');
    }
  }

  function generateOrderNumber() {
    // 获取当前时间的时间戳（精确到毫秒）
    $timestamp = round(microtime(true) * 1000);

    // 生成一个随机数（可以根据需要调整长度）
    $randomPart = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);

    // 拼接时间戳和随机部分
    $orderNumber = date("YmdHis", $timestamp / 1000) . substr($timestamp % 1000, -3) . $randomPart;

    return $orderNumber;
  }
}
