<?php

namespace app\home\controller;

use app\common\controller\Frontend;
use hehe\Trade;
use think\Db;
use think\Exception;


class Pay extends Frontend {

    protected $layout = 'default';

    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['*'];

    public function _initialize() {
        parent::_initialize(); // TODO: Change the autogenerated stub

        if(!$this->request->isPjax()){
//            $this->pjaxLayout();
            $this->view->engine->layout('default/layout/layout_' . $this->layout);
        }

    }

    /**
     * 购买商品
     */
    public function goods(){
        $params = $this->request->param();

		db::startTrans();
		try{
			$params['num'] = empty($params['num']) ? 1 : intval($params['num']);
			$goods = Db::name('goods')->where(['id' => $params['goods_id']])->find();
			$agency = $this->userAgency();
			$goods = $this->goodsDetail($goods, $agency);
			/**
			 * 写入订单前准备
			 * 	1，验证附加选项
			 *  2，验证商品规格
			 *  3，验证商品库存
			 *  4，验证优惠券
			 */
			// 1，验证附加选项
			foreach($goods['attach'] as $val){
				foreach($params['attach'] as $v){
					if($val['title'] == $v['title'] && !empty($val['checked']) && empty($v['value'])) {
						exception('请输入' . $val['title']);
					}
				}
			}

			// 2，验证商品规格
			$params['sku'] = empty($params['sku']) ? null : $params['sku'];
			$goodsMoney = $this->getGoodsMoney($goods, $agency, ['sku' => $params['sku']]);
//			var_dump($goodsMoney); die;
			if($goodsMoney == -1) {
				exception('商品规格错误，请刷新页面后重试');
			}

			// 3，验证商品库存
			if($goods['type'] == 'alone'){
				if($goods['is_sku'] == 0){
					$stockNum = $goods['stock'];
				}
				if($goods['is_sku'] == 1){
					$stockNum = db::name('stock')->field('id')->where(['goods_id' => $params['goods_id'], 'sku' => $params['sku']])->whereNull('sale_time')->count();
				}
			}
			if($goods['type'] == 'fixed'){
				if($goods['is_sku'] == 1){
					$stockNum = db::name('stock')->where(['goods_id' => $params['goods_id'], 'sku' => $params['sku']])->value('num');
				}
				if($goods['is_sku'] == 0){
					$stockNum = db::name('stock')->where(['goods_id' => $params['goods_id']])->value('num');
				}
			}
			if($goods['type'] == 'invented'){
				if($goods['is_sku'] == 0){
					$stockNum = db::name('stock')->where(['goods_id' => $params['goods_id']])->value('num');
				}
				if($goods['is_sku'] == 1){
					$stockNum = db::name('stock')->where(['goods_id' => $params['goods_id'], 'sku' => $params['sku']])->value('num');
				}
			}
			if($params['num'] > $stockNum) {
				exception('库存不足');
			}
			// 4，验证优惠券

			// 写入订单
			$orderMoney = $params['num'] * $goodsMoney;
			$out_trade_no = Trade::generateTradeNo();
			$order_insert = [
				'out_trade_no' => $out_trade_no,
				'goods_id' => $params['goods_id'],
				'user_id' => empty($this->user['id']) ? null : $this->user['id'],
				'goods_name' => $goods['name'],
				'goods_cover' => $goods['cover'],
				'goods_type' => $goods['type'],
				'create_time' => $this->timestamp,
				'pay_time' => $this->timestamp,
				'goods_money' => $goodsMoney,
				'goods_num' => $params['num'],
				'money' => $orderMoney,
				'attach' => empty($params['attach']) ? null : json_encode($params['attach']),
				'pay_type' => empty($params['pay_type']) ? null : $params['pay_type'],
			];
			if($goods['is_sku']){
				$order_insert['sku_name'] = empty($goods['sku_name']) ? '类型' : $goods['sku_name'];
				$order_insert['sku'] = $params['sku'];
			}
			db::name('goods_order')->insert($order_insert); //写入订单

			if($orderMoney == 0){
				$result = $this->notifyGoodsSuccess($goods, $out_trade_no);
			}else{
				if($params['pay_type'] == 'balance'){
					if($orderMoney > $this->user['money']) {
						exception('余额不够用啦，先去充值吧！');
					}
					db::name('user')->where(['id' => $this->user['id']])->setDec('money', $orderMoney);
					$result = $this->notifyGoodsSuccess($goods, $out_trade_no);
				}else{
					// 发起支付
					$pay_type = ucfirst($params['pay_type']);
					$usePay = "app\\pay\\controller\\{$pay_type}";
					$payObj = new $usePay();
					$result = $payObj->test();
				}

			}

			db::commit();
		}catch (\Exception $e){
			db::rollback();
			return json(['code' => 400, 'msg' => $e->getMessage()]);
			return json(['code' => 400, 'msg' => $e->getMessage(). ' - ' . $e->getLine()]);
		}

		if($result == true){
			return json(['code' => 201, 'msg' => '购买成功']);
		}else{
			return json(['code' => 400, 'msg' => '购买失败']);
		}

        print_r($params);die;
    }

	/**
	 * 购买商品的支付回调
	 */
	public function notifyGoods(){

	}

	/**
	 * 执行购买商品的回调操作
	 */
	protected function notifyGoodsSuccess($goods, $out_trade_no){
		$order = db::name('goods_order')->where(['out_trade_no' => $out_trade_no])->find();

		if($goods['type'] == 'alone'){ //更新库存表并写入发货表
			if($goods['is_sku'] == 0){
				$stock = db::name('stock')->field('id, content')->where(['goods_id' => $goods['id']])->whereNull('sale_time')->whereNull('sku')->limit($order['goods_num'])->select();
			}
			if($goods['is_sku'] == 1){
				$stock = db::name('stock')->field('id, content')->where(['goods_id' => $goods['id'], 'sku' => $order['sku']])->whereNull('sale_time')->limit($order['goods_num'])->select();
			}
			$stock_ids = array_column($stock, 'id');
			db::name('stock')->whereIn('id', $stock_ids)->update(['sale_time' => $this->timestamp]); //更新库存表
			$deliver = [];
			foreach($stock as $val){
				$deliver[] = [
					'content' => $val['content'],
					'order_id' => $order['id'],
					'create_time' => $this->timestamp
				];
			}
			db::name('deliver')->insertAll($deliver);
		}
		if($goods['type'] == 'fixed'){ //更新库存表并写入发货表
			if($goods['is_sku'] == 0){
				$stock = db::name('stock')->where(['goods_id' => $goods['id']])->whereNull('sku')->limit($order['goods_num'])->find();
			}
			if($goods['is_sku'] == 1){
				$stock = db::name('stock')->where(['goods_id' => $goods['id'], 'sku' => $order['sku']])->limit($order['goods_num'])->find();
			}
			$deliver = [];
			for($i = 0; $i < $order['goods_num']; $i++){
				$deliver[] = [
					'content' => $val['content'],
					'create_time' => $this->timestamp,
					'order_id' => $order['id']
				];
			}
			db::name('deliver')->insertAll($deliver); //写入发货表
			db::name('stock')->where(['id' => $stock['id']])->setDec('num', $order['goods_num']); //更新库存表
		}
		if($goods['type'] == 'invented'){
			if($goods['is_sku'] == 0){
				$stock = db::name('stock')->where(['goods_id' => $goods['id']])->whereNull('sku')->find();
			}
			if($goods['is_sku'] == 1){
				$stock = db::name('stock')->where(['goods_id' => $goods['id'], 'sku' => $order['sku']])->find();
			}
			db::name('stock')->where(['id' => $stock['id']])->setDec('num', $order['goods_num']); //更新库存表
		}
		db::name('goods')->where(['id' => $goods['id']])->setDec('stock', $order['goods_num']); //更新商品库存字段
		db::name('goods')->where(['id' => $goods['id']])->setInc('sales', $order['goods_num']); //更新商品销量字段
		db::name('goods_order')->where(['id' => $order['id']])->update(['pay_time' => $this->timestamp]); //更新订单状态
		return true;
	}



}
