<?php

namespace app\common\service;

use think\Cache;
use think\Model;
use app\common\model\User;
use app\admin\model\transaction\Record;
use app\common\service\UserService;
use app\admin\model\Order as OrderModel;
use app\admin\model\order\Detail;
use app\admin\model\Goods;
use think\Config;
use think\Db;

/**
 * 订单服务服务
 */
class OrderService
{
	/**
	 * 批量写入付款记录
	 * [productPayRecord description]
	 * @param  [type] $warehouse_id [description]
	 * @return [type]               [description]
	 */
	public function productPayRecord($warehouse_id, $time = 0){
		$time = $time ? $time : time();
	
		$order = Db::name('order')
                        ->field('user_id,sum(actual_amount) as pay_amount')
               			->whereTime('createtime', 'today')
                       ->where('warehouse_id', $warehouse_id)
                       ->whereIn('status', [0,3])
                       ->group('user_id')
                       ->select();
                                           
        $buyer_order = [];
        $seller_order = [];
        foreach ($order as $key => $value) {
            if ($value['pay_amount'] > 0) {
                $seller_order[] = $value;
            } elseif  ($value['pay_amount'] < 0)  {
                $buyer_order[] = $value;
            }
        }
		$pay_record = [];
		foreach ($seller_order as $seller) {
			if ($seller['pay_amount'] <= 0) {
                   continue;
            }
            foreach ($buyer_order as $key => $buyer) {
            	if ($seller['pay_amount'] >= abs($buyer['pay_amount'])) {
	               $pay_record[] = [
	                       'payer_id' => $buyer['user_id'],
	                       'payee_id' => $seller['user_id'],
	                       'amount' => abs($buyer['pay_amount']),
	                       'createtime' => $time,
	                       'warehouse_id' => $warehouse_id,
	                       'date' => date("Y-m-d", $time),
	               ];
	              	$seller['pay_amount'] = $seller['pay_amount'] + $buyer['pay_amount'];
	                unset($buyer_order[$key]);
	          	} else {
	               $pay_record[] = [
	                      'payer_id' => $buyer['user_id'],
	                       'payee_id' => $seller['user_id'],
	                       'amount' => $seller['pay_amount'],
	                       'createtime' => $time,
	                       'warehouse_id' => $warehouse_id,
	                       'date' => date("Y-m-d", $time),
	               ];
	               $buyer['pay_amount'] = $buyer['pay_amount'] + $seller['pay_amount'];
	               $seller['pay_amount'] = 0;
	            }
            }
			
		}
		// echo "<pre>";
		// print_r($pay_record);
		// exit();
		unset($seller);
		$ret = Db::name('income_expend')->insertAll($pay_record);
		return $ret;

	}
	/**
	 * 取消订单
	 * [cancelOrder description]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function cancelOrder($id){
		$order = OrderModel::where('id', $id)->find();
        if (!$order) {
            $this->error("订单不存在");
        }
        $info = OrderModel::where('id', $id)->update(['status' => -1,'cancel_time' => time()]);
        if ($info === false) {
            $this->error("取消失败");
        }
        $detail = Detail::where("order_id", $id)->find();
        //上架商品
        Goods::where('id', $detail['goods_id'])->update(['status' => 'normal', "updatetime" => time()]);
        //分佣给买家上级
        $site = Config::get("site");
        $commission = bcmul($order['order_amount'], $site['primary_distribution'] * 0.01, 2);
        $obj = new UserService();
        $obj->userCommission(1, $this->auth->getUserinfo(), $order['order_sn'], -$commission);

        return true;
	}
	
}