<?php

namespace Cash\Lib;

use Dever;

class Order
{
	# 更新结算单
    public function up($order, $jstype = 1, $audit = 1, $refund_id = -1)
    {
        if (!$order) {
            return false;
        }
        if ($audit == 2) {
            $status = 2;
        } else {
            $status = 1;
        }
        if ($jstype == 1) {
            $audit_type = 1;
        } else {
            $audit_type = 2;
        }
        $where['source_order_id'] = $order['id'];
        $where['jstype'] = $jstype;
        $where['refund_id'] = $refund_id;

        $info = Dever::db('cash/order')->find($where);

        $update = $where;
        $update['type'] = $order['type'];
        $update['type_id'] = $order['type_id'];
        if ($order['source_type']) {
            $update['source_type'] = $order['source_type'];
            $update['source_id'] = $order['source_id'];
        }
        
        $update['status'] = $status;
        $update['audit'] = $audit;
        $update['audit_type'] = $audit_type;

        if ($update['status'] == 2) {
        	$update['operdate'] = time();
        }
        if ($info) {
        	$update['where_id'] = $info['id'];
        	Dever::db('cash/order')->update($update);
        } else {
            $update['source_order_num'] = $order['order_num'];
            $update['num'] = $order['num'];

            if ($audit == 2) {
                $order['price'] -= $order['refund_cash'];
                $order['p_price'] -= $order['refund_p_cash'];
            }
            $update['cash'] = $order['price'];
            $update['p_cash'] = $order['p_price'];
            if ($jstype == 2) {
                $update['cash'] = -1*$update['cash'];
                $update['p_cash'] = -1*$update['p_cash'];
            }
        
        	$update['order_num'] = $this->getOrderId();
        	Dever::db('cash/order')->insert($update);
        }
    }

    # 生成订单号
    public function getOrderId()
    {
        $where['order_num'] = Dever::order('JS');
        $state = Dever::db('cash/order')->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderId();
        }
    }
}