<?php

namespace app\appapi\controller\v1;

use app\appapi\ApiController;
use think\facade\Db;
use asc\line\LinePay;

use app\common\shipping\ShippingStrategy;
use app\common\User;

class Order extends ApiController
{

	/**
	 * 添加訂單
	 * @author wayne <wwayne.hsu@gmail.com>
	 * @param string  
	 * 
	 * @return json
	 */
	public function add()
	{
		$data = input('post.');
		
		//檢查參數
		//取得用戶資料
		if ($this->user_id) {
			$user_info = User::getUserInfo($this->user_id);
		} else {
			$user_info['real_name'] = '';
			$user_info['mobile_phone'] = '';
			$user_info['email'] = '';
		}

		//檢查優惠券
		$update_bonus = false;
		if (isset($data['bonus_sn']) && strlen($data['bonus_sn']) == 10) {
			$bonus = Db::name('bonus')
				->where('bonus_sn', $data['bonus_sn'])
				->find();

			if ($bonus['remain_number'] == 0) {
				return $this->Error('優惠券已用完');
			}

			Db::name('bonus')
				->where('bonus_sn', $data['bonus_sn'])
				->dec('remain_number')
				->update();

			$update_bonus = true;
		}

		//加入訂單
		$order = [
			'order_sn'		 	=>	get_order_sn(),
			'user_id'         	=> 	$this->user_id ? $this->user_id : 0,
			'order_type'		=>  $data['type'],
			'table_no'			=>  $data['table_no'],
			'order_status'    	=> 	1,
			'shipping_status' 	=> 	0,
			'pay_status'      	=> 	0,
			'shipping_id'     	=>  0,
			'shipping_name'     =>  '',
			'address'			=>  '',
			'pay_id'          	=> intval($data['payment']['pay_id']),
			'pay_name'          => ($data['payment']['pay_id'] != 0) ? Db::name('payment')->where('pay_id', $data['payment']['pay_id'])->value('pay_name') : '貨到付款',
			'shipping_fee'		=>  0,
			'pay_fee'			=> floatval($data['payment']['pay_fee']),
			'goods_amount'    	=> intval($data['goods_amount']),
			'order_amount'    	=> intval($data['order_amount']),
			'discount'        	=> intval($data['discount']),
			'consignee'       	=> 	$user_info['real_name'],
			'mobile'			=> 	$user_info['mobile_phone'],
			'email'				=> 	$user_info['email'],
			'add_time'        	=> 	time(),
			'extension_code'	=> 	isset($data['extension_code']) ? $data['extension_code'] : '',
		];

		$order_id = Db::name('order_info')
			->insertGetId($order);

		$is_main_goods = 0;
		//加入訂單商品項
		foreach ($data['goodsItems'] as $key => $val) {
			$goods_data = [
				'order_id' 		=> $order_id,
				'goods_id' 		=> $val['goods_id'],
				'goods_sn' 		=> $val['goods_sn'],
				'goods_name' 	=> $val['goods_name'],
				'goods_price' 	=> $val['goods_price'],
				'goods_number' 	=> $val['goods_number'],
				'add_info'		=> isset($val['add_info']) ? $val['add_info'] : ''
			];
			Db::name('order_goods')
				->insert($goods_data);

			// if($val['goods_id']==1){
			// 	$is_main_goods = 1;
			// }
		}

		//如果有主商品，則加入主商品額外屬性
		// if($is_main_goods){
		// 	$main_goods_data = [
		// 		'order_id' 		=> $order_id,
		// 		'goods_id' 		=> 1,
		// 		'goods_name' 	=> '主商品額外屬性',
		// 		'goods_price' 	=> 0,
		// 		'goods_number' 	=> 1
		// 	];

		// 	Db::name('order_info')
		// 	->where('order_id',$order_id)
		// 	->update($main_goods_data);
		// }
		if ($update_bonus) {
			Db::name('user_bonus')
				->insert([
					'bonus_id' => $bonus['bonus_id'],
					'bonus_sn' => $bonus['bonus_sn'],
					'user_id' => $this->user_id,
					'used_time' => time(),
					'order_id' => $order_id
				]);
		}

		// if ($data['shipping']['shipping_code'] == 'ecpay' && $data['payment']['pay_code'] == 'cod') {
		// 	//串接綠界物流
		// 	$rtn = \app\common\shipping\Shipping::createShipping('ecpay', $order['order_sn']);
		// 	if ($rtn['code'] != 200) {
		// 		return $this->Error($rtn['msg']);
		// 	}
		// }

		// 資料後處理
		// 清空購物車
		$db_rtn = Db::name('cart');

		if ($this->uid > 0) {
			$db_rtn->where('user_id', $this->uid)
				->where('session_id', $this->SessionId);
		} else {
			$db_rtn->where('session_id', $this->SessionId);
		}

		$db_rtn->delete();

		// 使用payment_id取得pay_code
		// $pay_code = Db::name('payment')->where('pay_id', $order['pay_id'])->value('pay_code');

		return $this->Success(['order_sn' => $order['order_sn'], 'pay_code' => $data['payment']['pay_code']]);
	}

	//取得訂單列表
	public function list()
	{
		if (!$this->uid) {
			return $this->Error('請先登入');
		}

		$status = input('status');

		$do = Db::name('order_info')
			->field('order_id,order_sn,order_status,shipping_status,pay_status,consignee,mobile,order_amount,pay_id,add_time')
			->where('user_id', $this->user_id)
			->order('order_id', 'desc');

		if ($status != -1) {
			$do->where('order_status', $status);
		}
		$result = $do->select()->toArray();

		$SName = getStatusName();

		foreach ($result as $key => $val) {
			$result[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
			$result[$key]['goods_items'] = Db::name('order_goods')
				->field('goods_id,goods_name,goods_price,goods_number')
				->where('order_id', $val['order_id'])
				->select()
				->toArray();

			$ss_status = $val['shipping_status'];
			$os_status = $val['order_status'];
			$ps_status = $val['pay_status'];

			$status = '';

			if ($os_status == 0) {
				$status = '未確認';
			} elseif ($os_status == 2) {
				$status = '已取消';
			} elseif ($os_status == 3) {
				$status = '無效';
			} elseif ($os_status == 7) {
				$status = '已完成';
			} elseif ($os_status == 1) {
				if ($ps_status == 1) {
					$status = '待付款';
				} else {
					if ($ss_status <> 0 && $ss_status <> 4 && $ss_status <> 7) {
						$status = '待出貨';
					} elseif ($ss_status == 7) {
						$status = '已達指定門市';
					} else {
						if ($val['pay_id'] == 0) {
							$status = '待出貨';
						} else {
							$status = '未付款';
						}
					}
				}
			}




			$result[$key]['status'] = $status;
		}

		return $this->Success($result);
	}
}
