<?php

namespace Cash\Lib;

use Dever;

class Order
{
	# 更新结算单
    public function up($order, $jstype = 1, $audit = 1, $refund = false)
    {
        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;
        if (!$refund) {
            $where['refund_id'] = -1;
        } else {
            $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();
            $update['fdate'] = $update['operdate'];
            if (isset($order['fdate']) && $order['fdate'] && ($order['status'] == 5 || $order['status'] == 6)) {
                $update['fdate'] = $order['fdate'];
            }
        }
        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 ($refund) {
                $update['cash'] = $refund['cash'];
                $update['p_cash'] = isset($refund['p_cash']) ? $refund['p_cash'] : 0;
            } else {
                $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();
        }
    }
}