<?php

namespace app\home\controller;

use think\Lang;
use think\Cache;
use think\Request;
use think\Controller;
use think\Validate;

/**
 * 主页管理类
 */
class Product extends Common
{


    /**
     * 构造函数
     *
     * @access public
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 产品与服务
     *
     * @access public
     * @return array JsonString
     */
    public function product()
    {
        $fatherProductField = [
            'product_name',
            'product_content',
            'product_img',
            'product_id',
        ];
        $fatherProductWhere = [
            'product_pid' => 0,
            'product_status' => 1,
        ];
        $getFatherProduct = model('Product')->getSelect($fatherProductField, $fatherProductWhere);
        $this->assign('fatherProduct', $getFatherProduct);
        $id = input('get.id') ?? $getFatherProduct[0]->product_id;
        $productWhere = [
            'product_pid' => $id,
            'product_status' => 1,
        ];
        $getProduct = model('Product')->getSelect($fatherProductField, $productWhere);
        $this->assign('product', $getProduct);
        $this->assign('id', $id);

        return $this->fetch();
    }

    /**
     * 产品与服务详情
     *
     * @access public
     * @return array JsonString
     */
    public function details()
    {
        $findProductinfo = model('Productinfo')->getFind();
        $id = input('get.id') ?? $findProductinfo->product_id;
        $productWhere = [
            'product_id' => $id,
        ];
        $getProductInfo = model('Productinfo')->getSelect($productWhere);
        $this->assign('productInfo', $getProductInfo);
        $productWhere['product_status'] = 1;
        $getProduct = model('Product')->getFind($productWhere);
        $this->assign('product', $getProduct);
        $fatherProductWhere = [
            'product_id' => $getProduct->product_pid,
        ];
        $getFatherProduct = model('Product')->getFind($fatherProductWhere);
        $this->assign('fatherProduct', $getFatherProduct);
        $getRenewal = model('Renewal')->getRenewal();
        $this->assign('renewal', $getRenewal);

        return $this->fetch();
    }

    /**
     * 选购产品
     *
     * @access public
     * @return array JsonString
     */
    public function shopping()
    {
        $userId = session('user_id');
        $userInfo = model('userinfo')->getInfo($userId);
        $this->assign('userInfo', $userInfo);
        $product_id = input('get.product_id');
        $productWhere = [
            'product_id' => $product_id,
            'product_status' => 1,
        ];
        $getProduct = model('Product')->getFind($productWhere);
        $this->assign('product', $getProduct);
        $fatherProductWhere = [
            'product_id' => $getProduct->product_pid,
        ];
        $getFatherProduct = model('Product')->getFind($fatherProductWhere);
        $this->assign('fatherProduct', $getFatherProduct);
        $renewal_identity = input('get.renewal_identity');
        $renewalWhere = [
            'renewal_identity' => $renewal_identity,
        ];
        $getRenewal = model('Renewal')->findRenewal($renewalWhere);
        $this->assign('renewal', $getRenewal);

        return $this->fetch();
    }
    public function purchased()
    {
        $product_id = input('post.product_id');
        if ($product_id) {
            $renewal_identity = input('post.renewal_identity');
            $userId = session('user_id');
            $userInfo = model('userinfo')->getInfo($userId);
            $productWhere = [
                'product_id' => $product_id,
                'product_status' => 1,
            ];
            $product = model('Product')->getFind($productWhere);
            $fatherProductWhere = [
                'product_id' => $product->product_pid,
            ];
            $getFatherProduct = model('Product')->getFind($fatherProductWhere);
            if (!$product) {
                return ["success" => false, "msg" => "错误：该产品已停售"];
            }
            switch($renewal_identity){
                case 1:
                    $money = $product->product_TypeOne;
                    break;
                case 2:
                    $money = $product->product_TypeTwo;
                    break;
                case 3:
                    $money =  $product->product_TypeThree;
                    break;
                case 4:
                    $money =  $product->product_TypeFour;
                    break;
            }
            if (isset($money) && $money <= $userInfo->userInfo_money) {
                $findRenewal = model('renewal')->findRenewal(['renewal_status' => 1, 'renewal_identity' => $renewal_identity]);
            } else {
                return ["msg" => "错误：您的余额不足", "success"=>false];
            }
            if (!$findRenewal) {
                return ["msg" => "错误：该期限已不支持购买", "success"=>false];
            }
            $day = $findRenewal->renewal_day;
            $cashMoney = $userInfo->userInfo_money - $money;
            $dbUserInfo = model('Userinfo');
            $dbUserProduct = model('Userproduct');
            $dbOrder = model('Order');
            $capitalMovements = model('CapitalMovements');
            $dbUserInfo->startTrans();
            $dbUserProduct->startTrans();
            $dbOrder->startTrans();
            $capitalMovements->startTrans();
            try {
                $userProduct = model('Userproduct')->findUserProduct(['user_id'=>$userId,'product_id'=>$product_id]);
                $dbUserInfo->updateInfo($userId, ['userInfo_money' => $cashMoney]);
                $nowDate = date('Y-m-d');
                $orderID = OrderID();
                $data['userProduct_identity'] = $orderID;
                $data['userProduct_buyTime'] = $nowDate;
                if ($userProduct) {
                    $data['userProduct_dayNumber'] = $userProduct->userProduct_dayNumber + $day;
                    if ($userProduct->userProduct_maturityTime > $nowDate) {
                        $data['userProduct_maturityTime'] = date('Y-m-d', strtotime(intval($day) . " day", strtotime($userProduct->userProduct_maturityTime)));
                    } else {
                        $data['userProduct_maturityTime'] = date('Y-m-d', strtotime(intval($day) . " day"));
                    }
                    $dbUserProduct->updateUserProduct(['userProduct_id' => $userProduct->userProduct_id], $data);
                } else {
                    $data['userProduct_dayNumber'] = $day;
                    $data['user_id'] = $userId;
                    $data['product_id'] = $product_id;
                    $data['userProduct_maturityTime'] = date('Y-m-d', strtotime(intval($day) . " day"));
                    $dbUserProduct->addUserProduct($data);
                }
                $addOrderData = [
                    'order_identity' => $orderID,
                    'user_id' => $userId,
                    'product_id' => $product_id,
                    'order_dayNumber' => $day,
                    'order_buyTime' => $nowDate,
                    'order_money' => $money,
                ];
                $dbOrder->addOrder($addOrderData);
                $cplMvtData = [
                    'user_id' => $userId,
                    'capitalMovements_describe' => '购买服务：' . $getFatherProduct->product_name . ' ▪ ' . $product->product_name,
                    'capitalMovements_identity' => $orderID,
                    'capitalMovements_create' => $nowDate,
                    'capitalMovements_update' => $nowDate,
                    'capitalMovements_money' => $money,
                    'capitalMovements_type' => 2,
                    'capitalMovements_cash' => $cashMoney,
                    'capitalMovements_operator' => $userId,
                ];
                $capitalMovements->add($cplMvtData);
                // 提交事务
                $dbUserInfo->commit();
                $dbUserProduct->commit();
                $dbOrder->commit();
                $capitalMovements->commit();
                $returnData = [
                    "msg" => "恭喜你购买成功",
                    "success"=> true,
                    "data"=> json_encode([
                        "orderID" => $orderID,
                        "product" => $getFatherProduct->product_name . " ▪ " . $product->product_name,
                        "order_money" => $money,
                        "userProduct_maturityTime" => $data['userProduct_maturityTime'],
                    ]),
                ];
                return $returnData;
            } catch (\Exception $e) {
                // 回滚事务
                $dbUserInfo->rollBack();
                $dbUserProduct->rollBack();
                $dbOrder->rollBack();
                $capitalMovements->rollBack();
                return ["msg" => "操作失败", "success"=>false];
            }
        }
        $data = json_decode(input('get.data'));//print_r($data->orderID);die;
        $this->assign('data', $data);

        return $this->fetch();
    }

}
