<?php

namespace App\Services;

use App\Constants\HttpEnumCode;
use App\Model\Coupon;
use App\Model\OrderInquiry;
use App\Model\PatientHistoryInquiry;
use App\Model\Product;
use App\Model\ProductPlatformAmount;
use App\Model\User;
use App\Model\UserCoupon;
use App\Model\UserPatient;
use App\Utils\Mask;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 患者
 */
class UserPatientService extends BaseService
{
    /**
     * 获取患者个人中心数据
     * @return array
     */
    public function getPatientCenter(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        // 获取患者信息
        $fields = [
            'patient_id',
            'user_id',
            'user_name',
            'avatar',
        ];
        $params = array();
        $params['patient_id'] = $user_info['client_user_id'];
        $user_patient = UserPatient::getOne($params,$fields);
        if (empty($user_patient)){
            return fail(HttpEnumCode::HTTP_ERROR, "非法用户");
        }

        // 获取福利数据
        $coupon = $this->getPatientAvailableCouponList($user_patient['user_id'],1);

        // 获取问诊数量-待支付
        $InquiryService = new InquiryService();
        $order_inquiry_count = $InquiryService->getPatientInquiryWithStatus($user_patient['patient_id'],1);

        // 获取处方数量-未使用
        $OrderPrescriptionService = new OrderPrescriptionService();
        $order_prescription_count = $OrderPrescriptionService->getPatientPrescriptionWithStatus($user_patient['patient_id'],3);

        // 获取药品数量-待支付
        $OrderProductService = new OrderProductService();
        $order_product_count = $OrderProductService->getPatientProductWithStatus($user_patient['patient_id'],1);

        // 处理头像
        $user_patient['avatar'] = addAliyunOssWebsite($user_patient['avatar']);

        $result = array();
        $result['patient_id'] = $user_patient['patient_id'];
        $result['avatar'] = $user_patient['avatar'];
        $result['user_name'] = $user_patient['user_name'];
        $result['coupon'] = empty($coupon);
        $result['order_inquiry_count'] = $order_inquiry_count;
        $result['order_prescription_count'] = $order_prescription_count;
        $result['order_product_count'] = $order_product_count;
        return success($result);
    }

    /**
     * 获取患者信息
     * @return array
     */
    public function getPatientCenterInfo(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        // 获取患者信息
        $fields = [
            'patient_id',
            'user_id',
            'user_name',
            'avatar',
        ];
        $params = array();
        $params['patient_id'] = $user_info['client_user_id'];
        $user_patient = UserPatient::getOne($params,$fields);
        if (empty($user_patient)){
            return fail(HttpEnumCode::HTTP_ERROR, "非法用户");
        }

        $params = array();
        $params['user_id'] = $user_patient['user_id'];
        $user = User::getOne($params);
        if (empty($user)){
            return fail(HttpEnumCode::HTTP_ERROR, "非法用户");
        }

        // 手机号
        $user_patient['mobile'] = Mask::maskPhoneStr($user['mobile']);

        // 头像
        $user_patient['avatar'] = addAliyunOssWebsite($user_patient['avatar']);

        return success($user_patient->toArray());
    }

    /**
     * 获取患者优惠卷列表
     * @return array
     */
    public function getPatientCouponlist(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $user_coupon_status = $this->request->input('user_coupon_status');

        // 获取患者信息
        $fields = [
            'patient_id',
            'user_id',
            'user_name',
            'avatar',
        ];
        $params = array();
        $params['patient_id'] = $user_info['client_user_id'];
        $user_patient = UserPatient::getOne($params,$fields);
        if (empty($user_patient)){
            return fail(HttpEnumCode::HTTP_ERROR, "非法用户");
        }

        $CouponService = new CouponService();

        $user_coupon = $CouponService->getUserCouponStatusList($user_patient['user_id'],[1,2,3,4,5],$user_coupon_status);

        $result = [];
        foreach ($user_coupon as $item){
            $data = array();
            $data['user_coupon_id'] = $item['user_coupon_id'];
            $data['coupon_id'] = $item['coupon_id'];
            $data['user_coupon_status'] = $item['user_coupon_status'];

            if ($item['user_coupon_status'] == 0){
                // 未使用
                if ($item['valid_end_time'] <= date('Y-m-d H:i:s',time())){
                    // 已过期
                    $data['user_coupon_status'] = 3;
                }
            }

            $data['coupon_use_date'] = $item['coupon_use_date'];
            $data['valid_start_time'] = $item['valid_start_time'];
            $data['valid_end_time'] = $item['valid_end_time'];
            $data['coupon_name'] = $item['coupon']['coupon_name'];
            $data['coupon_price'] = $item['coupon']['coupon_price'];
            $data['application_scope'] = $item['coupon']['application_scope'];

            $result[] = $data;
        }

        unset($user_coupon);

        return success($result);
    }

    /**
     * 删除服务过患者的医生
     * 首页-个人中心
     * @return array
     */
    public function deletePatientDoctor(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $doctor_id = $this->request->route('doctor_id');

        $params = array();
        $params['doctor_id'] = $doctor_id;
        $params['patient_id'] = $user_info['client_user_id'];
        $params['history_status'] = 1; //

        $patient_history_inquiry = PatientHistoryInquiry::getList($params);
        if (empty($patient_history_inquiry)){
            return fail();
        }

        $params['doctor_id'] = $doctor_id;
        $params['patient_id'] = $user_info['client_user_id'];
        $params['history_status'] = 1; //

        $data = array();
        $data['history_status'] = 0;

        PatientHistoryInquiry::edit($params,$data);

        return success();
    }

    /**
     * 获取购物车药品数据
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getShoppingCart(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $redis = $this->container->get(Redis::class);

        $redis_key = "shopping_cart" . $user_info['client_user_id'];
        $shopping_cart = $redis->get($redis_key);
        if (empty($shopping_cart)){
            // 购物车为空
            return success();
        }

        $shopping_cart = json_decode($shopping_cart,true);

        if (empty($shopping_cart)){
            return success();
        }

        $data = array();
        foreach ($shopping_cart as $item){
            // 获取商品数据
            $params =array();
            $params['product_id'] = $item['product_id'];
            $product = Product::getOne($params);
            if (empty($product)){
                continue;
            }

            $item['product_cover_img'] = addAliyunOssWebsite($product['product_cover_img']);
            $item['product_price'] = $product['product_price'];
            $item['product_name'] = $product['product_name'];
            $item['product_spec'] = $product['product_spec'];
            $item['manufacturer'] = $product['manufacturer'];
            $item['packaging_unit'] = $product['packaging_unit'];

            $data[] = $item;
        }

        return success($data);
    }

    /**
     * 修改购物车药品数据
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function putShoppingCart(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];
        $product_id = $this->request->input("product_id");
        $shopping_cart_num = $this->request->input("shopping_cart_num");

        if ($shopping_cart_num > 0){
            // 验证商品数据
            $params =array();
            $params['product_id'] = $product_id;
            $product = Product::getOne($params);
            if (empty($product)){
                return fail();
            }
            // 获取商品库存
            $params =array();
            $params['product_platform_id'] = $product['product_platform_id'];
            $product_platform_amount = ProductPlatformAmount::getOne($params);
            if ($product_platform_amount['stock'] <= 0){
                return fail(HttpEnumCode::HTTP_ERROR,"商品库存不足");
            }
        }

        // 读取缓存数据
        $redis = $this->container->get(Redis::class);
        $redis_key = "shopping_cart" . $user_info['client_user_id'];

        $shopping_cart = $redis->get($redis_key);
        if (!empty($shopping_cart)){
            $shopping_cart = json_decode($shopping_cart,true);
        }

        // 处理缓存数据为空的情况
        if (empty($shopping_cart)){
            if ($shopping_cart_num > 0){
                // 处理存储数据
                $data = array();
                $data['product_id'] = $product_id;
                $data['shopping_cart_num'] = $shopping_cart_num;
                $res = $redis->set($redis_key,json_encode([$data],JSON_UNESCAPED_UNICODE));
                if (!$res){
                    return fail(HttpEnumCode::SERVER_ERROR);
                }
            }

            return success();
        }

        $product_ids = array_column($shopping_cart,'product_id');
        if (in_array($product_id,$product_ids)){
            // 商品存在于购物车缓存中
            foreach ($shopping_cart as $key => $value){
                if ($value['product_id'] == $product_id){
                    if ($shopping_cart_num <= 0){
                        // 商品存在于购物车缓存中，此数据表示删除
                        unset($shopping_cart[$key]);
                    }else{
                        $shopping_cart[$key]['shopping_cart_num'] = $shopping_cart_num;
                    }
                }
            }
        }else{
            // 商品未存在于购物车缓存中。
            $data = array();
            $data['product_id'] = $product_id;
            $data['shopping_cart_num'] = $shopping_cart_num;

            array_unshift($shopping_cart,$data);
        }

        if (!empty($shopping_cart)){
            // 重置数组排列
            array_values($shopping_cart);

            // 添加到缓存中
            $res = $redis->set($redis_key,json_encode($shopping_cart,JSON_UNESCAPED_UNICODE));
            if (!$res){
                return fail(HttpEnumCode::SERVER_ERROR);
            }
        }else{
            $res = $redis->del($redis_key);
            if (!$res){
                return fail(HttpEnumCode::SERVER_ERROR);
            }
        }

        return success();
    }

    /**
     * 获取用户可领取优惠卷
     * @param string|int $user_id
     * @param int $coupon_client
     * @return array
     */
    public function getPatientAvailableCouponList(string|int $user_id,int $coupon_client): array
    {
        // 获取全部优惠卷
        $params = array();
        $params['coupon_client'] = $coupon_client;
        $params['coupon_status'] = 1;
        $params['is_display'] = 1;
        $coupon = Coupon::getList($params);
        if (empty($coupon)){
            return [];
        }

        // 处理优惠卷
        $result = array();
        foreach ($coupon as $item){
            if ($item['coupon_count'] <= $item['coupon_take_count']){
                // 已发放完毕
                continue;
            }

            if ($item['valid_type'] == 1){
                // 绝对时效
                $date = date('Y-m-d H:i:s',time());
                if ($item['valid_end_time'] < $date){
                    // 超出结束使用时间
                    continue;
                }
            }

            // 检测当前优惠卷是否被用户领取
            $params = array();
            $params['user_id'] = $user_id;
            $params['coupon_id'] = $item['coupon_id'];
            $user_coupon = UserCoupon::getOne($params);
            if (empty($user_coupon)){
                // 未被领取
                $result[] = $item;
            }
        }

        return $result;
    }

}