<?php namespace Phpcmf\Model;

// 订单状态 0关闭 1已下单 2已付款 3已退货 4申请退货 5申请换货 9 已完成
class Order extends \Phpcmf\Model
{
    private $zk;

    // 购物车下单获取商品
    public function my_cart_items($ids) {
        return $this->db->table(SITE_ID.'_cart')->whereIn('id', $ids)->where('uid', $this->uid)->get()->getResultArray();
    }

    // 订单购物车表的商品信息
    public function my_order_cart_items($cid) {
        return $this->db->table(SITE_ID.'_order_cart')->where('cid', $cid)->where('uid', $this->uid)->get()->getRowArray();
    }

    // 我的购物车信息
    public function my_order_cart_info($id) {
        return $this->db->table(SITE_ID.'_order_cart')->where('id', $id)->where('uid', $this->uid)->get()->getRowArray();
    }

    // 删除购物车数据
    public function delete_order_cart($id) {
        $this->db->table(SITE_ID.'_order_cart')->where('id', $id)->delete();
    }

    // 加入到订单购物车表
    public function add_my_order_cart($cid) {
        return $this->table_site('order_cart')->insert([
            'uid' => $this->uid,
            'cid' => $cid,
        ]);
    }

    // 订单下的单个商品信息
    public function item($id) {

        $data = $this->table_site('order_goods')->where('id', $id)->getRow();
        if (!$data) {
            return [];
        }

        $data['yuan'] = floatval($data['yuan']);
        $data['p_info'] = $data['promotion_info'];
        $data['p_name'] = $data['promotion_name'];
        $data['content'] = dr_string2array($data['content']);

        return $data;
    }

    // 订单下的商品信息
    public function goods($id) {

        $data = $this->table_site('order_goods')->where('oid', $id)->getAll();
        if (!$data) {
            return [];
        }

        foreach ($data as $i => $t) {
            $data[$i]['yuan'] = floatval($t['yuan']);
            $data[$i]['p_info'] = $t['promotion_info'];
            $data[$i]['p_name'] = $t['promotion_name'];
            $data[$i]['content'] = dr_string2array($t['content']);
        }

        return $data;
    }

    // 订单下的商品售后服务信息
    public function service($id) {

        $data = $this->table_site('order_service')->where('cid', $id)->getRow();
        if (!$data) {
            return [];
        }

        $data['images'] = dr_string2array($data['images']);
        $data['system'] = dr_string2array($data['system']);
        $data['myinfo'] = dr_string2array($data['myinfo']);

        return $data;
    }
    // 订单下的商品售后服务信息
    public function service_id($id) {

        $data = $this->table_site('order_service')->where('id', $id)->getRow();
        if (!$data) {
            return [];
        }

        $data['images'] = dr_string2array($data['images']);
        $data['system'] = dr_string2array($data['system']);
        $data['myinfo'] = dr_string2array($data['myinfo']);

        return $data;
    }

    // 提交售后申请
    public function post_service($item, $data) {

        $data['images'] = dr_array2string($data['images']);
        $data['oid'] = $item['oid'];
        $data['uid'] = $item['uid'];
        $data['username'] = $this->member['username'];
        $data['cid'] = $item['id'];
        $data['title'] = $item['title'];
        $data['thumb'] = $item['thumb'];
        $data['url'] = $item['url'];
        $data['money'] = 0;
        $data['status'] = 1;
        $data['system'] = '';
        $data['myinfo'] = '';
        $data['inputtime'] = SYS_TIME;

        $rt = $this->table_site('order_service')->insert($data);
        if (!$rt['code']) {
            return $rt;
        }

        // 通知商家


        return $rt;
    }

    // 平台分成金额
    private function _income($data) {

        if ($data['money'] > 0) {
            // 计算平台分成
            $bl = intval(\Phpcmf\Service::C()->mall_info['income']);
            if ($bl) {
               return $data['money'] * ($bl/100);
            }
        }

        return 0;
    }

    // 下单
    public function checkout($data, $goods, $cart) {

        if (!$this->uid) {
            return dr_return_data(0, dr_lang('你未登录'));
        }

        $order = [

            'sn' => $data['sn'],
            'mid' => $data['mid'],
            'uid' => $this->member['uid'],
            'username' => $this->member['username'],
            'money' => $data['money'], //订单总金额
            'freight' => $data['freight'], // 运费
            'discount' => abs($data['discount']), // 优惠折扣金额
            'coupon' => (int)$data['coupon'], // 优惠卷id
            'give_score' => $data['give_score'], // 赠送积分
            'give_money' => $data['give_money'], // 赠送金额

            'income_money' => $this->_income($data), // 平台分成金额

            'source' => $data['source'], // 来源

            // 店铺信息
            'mall_cid' => $data['mall']['id'],
            'mall_url' => dr_url_prefix($data['mall']['url'], 'mall', SITE_ID),
            'mall_name' => $data['mall']['title'],
            'sell_uid' => $data['mall']['uid'],
            'sell_username' => $data['mall']['author'],

            'name' => $data['name'],
            'email' => $this->member['email'],
            'phone' => $data['phone'],
            'address' => $data['address'],

            'pay_id' => 0, // 付款ID
            'pay_time' => 0, // 付款时间
            'pay_type' => $data['pay_type'], // 付款方式
            'pay_status' => 0, // 付款状态 付款状态 1已付款 2已退款　0未付款

            'deliver_id' => 0, // 发货ID
            'deliver_time' => 0, // 发货时间
            'deliver_status' => 0, // 发货状态 0未发货 1发货 2确认收货 3退货成功 4换货成功

            'receipt_time' => 0, // 收货时间

            'comment' => 0, // 是否评论
            'comment_time' => 0, // 评论时间

            'promotion_name' => $data['promotion_name'], // 订单折扣名称
            'promotion_info' => $data['promotion_info'], // 定制折扣详情

            'remark' => $data['remark'], // 订单备注
            'status' => 1, //   订单状态 0关闭 1已下单 2已付款 3已退货 4申请退货 5申请换货 9 已完成
            'inputtime' => SYS_TIME, //下单时间

        ];

        $rt = $this->table_site('order')->insert($order);
        if (!$rt['code']) {
            return $rt;
        }

        $order['id'] = $rt['code'];
        foreach ($goods as $t) {
            $content = $t['data'];
            if (isset($t['data']['tableid'])) {
                $data2 = $this->table($t['table'].'_data_'.$t['data']['tableid'])->get($t['data']['id']);
                $data2 && $content = $content + $data2;
            }
            $content['thumb'] = dr_get_file($t['thumb']);
            $rt = $this->table_site('order_goods')->insert([
                'uid' => $this->uid,
                'oid' => $order['id'],
                'mid' => $t['mid'],
                'num' => $t['num'],
                'price' => $t['price'],
                'total' => $t['total'],
                'yuan' => $t['yuan'],
                'promotion_name' => $t['p_name'],
                'promotion_info' => $t['p_info'],
                'sn' => (string)$t['sn'],
                'sku_name' => dr_array2string($t['sku_name']),
                'sku_value' => $t['sku_value'],
                'title' => $t['title'],
                'thumb' => $content['thumb'],
                'url' => $t['url'],
                'status' => 0,
                'table' => $t['table'],
                'content' => dr_array2string($content),
            ]);
            if (!$rt['code']) {
                $this->db->table(SITE_ID.'_order')->where('id', $order['id'])->delete();
                $this->db->table(SITE_ID.'_order_goods')->where('oid', $order['id'])->delete();
                return $rt;
            }
        }

        if ($cart) {
            $this->db->table(SITE_ID.'_cart')->whereIn('id', $cart['cid'])->delete();
            $this->db->table(SITE_ID.'_order_cart')->where('id', $cart['id'])->delete();
        }

        // 创建日志
        $this->add_log($order, dr_lang('创建订单成功'));

        // 下单提醒
        \Phpcmf\Service::L('Notice')->send_notice('order_status_1', $order);
        $order['uid'] = $order['sell_uid'];
        $order['username'] = $order['sell_username'];
        \Phpcmf\Service::L('Notice')->send_notice('order_status_1', $order);

        return dr_return_data($order['id'], 'ok');
    }

    // 订单评论信息
    public function comment($mid, $id) {

        $data = $this->table_site($mid.'_comment')->where('orderid', $id)->getAll();
        if (!$data) {
            return [];
        }

        $rt = [];
        foreach ($data as $i => $t) {
            $t['image'] = dr_string2array($t['image']);
            $rt[$t['cid']] = $t;
        }

        return $rt;
    }


    // 回滚评论
    public function call_comment($call) {

        if (!$call) {
            return;
        }

        foreach ($call as $t) {
            if ($t['mid']) {
                $this->db->table(SITE_ID.'_'.$t['mid'].'_comment')->where('id', (int)$t['eid'])->delete();
                $this->db->table(SITE_ID.'_'.$t['mid'].'_comment_index')->where('id', (int)$t['eid'])->delete();
            }
        }
    }

    // 完成评论操作
    public function save_comment($id) {
        $this->table_site('order')->update($id, [
            'comment' => 1,
            'comment_time' => SYS_TIME,
        ]);
    }

    // 订单信息
    public function info($id) {

        $order = $this->table_site('order')->get($id);

        return $order;
    }

    // 创建订单日志记录
    public function add_log($order, $log) {
        $this->table_site('order_log')->insert([
            'oid' => (int)$order['id'],
            'uid' => (int)$this->uid,
            'username' => (string)$this->member['username'],
            'log' => (string)$log,
            'status' => (int)$order['status'],
            'pay_status' => (int)$order['pay_status'],
            'deliver_status' => (int)$order['deliver_status'],
            'inputtime' => SYS_TIME
        ]);
    }

    // 订单操作日志信息
    public function log($id) {
        return $this->table_site('order_log')->where('oid', $id)->getAll();
    }

    // 获取发货物流公司
    public function get_delivery_corp() {

        $value = $this->table('mall_delivery_corp')->where('disabled', 0)->order_by('displayorder asc,id desc')->getAll();
        if (!$value) {
            return [];
        }

        $data = [];
        foreach ($value as $t) {
            $data[$t['id']] = $t;
        }

        return $data;
    }
 
    // 订单执行发货记录
    public function deliver_info($id) {

        if (!$id) {
            return [];
        }

        $sql = 'select a.*,b.code as deliver_code,b.url as deliver_url from `'.$this->dbprefix(SITE_ID.'_order_deliver_goods').'` as a left join  `'.$this->dbprefix('mall_delivery_corp').'` as b on a.deliver_id=b.id where a.`id`='.$id;
        return $this->db->query($sql)->getRowArray();
    }

    // 订单执行发货记录
    public function service_deliver_info($id) {

        if (!$id) {
            return [];
        }

        $sql = 'select b.name as deliver_name,b.code as deliver_code,b.url as deliver_url from  `'.$this->dbprefix('mall_delivery_corp').'` as b  where b.`id`='.$id;
        return $this->db->query($sql)->getRowArray();
    }

    // 订单执行发货操作 发货类型发0换1
    public function add_deliver_goods($tid, $order, $data) {

        $save = [
            'tid' => (int)$tid,
            'oid' => $order['id'],
            'sn' => $order['sn'],
            'uid' => $order['uid'],
            'username' => $order['username'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'address' => $data['address'],
            'note' => $data['note'],
            'deliver_id' => (int)$data['id'],
            'deliver_sn' => $data['sn'],
            'deliver_name' => $data['deliver_name'],
            'admin_uid' => $this->uid,
            'admin_username' => $this->member['username'],
            'inputtime' => SYS_TIME
        ];
        $rt = $this->table_site('order_deliver_goods')->insert($save);
        if (!$rt['code']) {
            return $rt;
        }
        $save['id'] = $rt['code'];

        // 发货处理
        $rt = $this->delivery($order, $save);
        if ($rt && !$rt['code']) {
            // 删除发货记录
            $this->table_site('order_deliver_goods')->delete($save['id']);
            return $rt;
        }

        return dr_return_data($save['id'], 'ok');
    }

    // 获取商品优化价格及活动
    public function get_goods_info($id, $field, $num, $sku) {

        // 获取付款价格
        $rt = \Phpcmf\Service::M('Pay')->get_pay_info($id, $field, $num, $sku);
        if (isset($rt['code']) && !$rt['code']) {
            return dr_return_data(0, $rt['msg']);
        }

        // 活动信息
        $rt['yuan'] = '';
        $rt['p_name'] = '';
        $rt['p_info'] = '';
        $rt['give_money'] = 0;
        $rt['give_score'] = 0;

        // 商品折扣信息
        list($table, $cid) = explode('-', $rt['mid']);
        if ($table == SITE_ID.'_goods') {
            // 计算折扣价格
            $p = $this->get_goods_discount($cid, $rt['price'], $rt['data']['uid']);
            if ($p['promotion']) {
                $rt['yuan'] = $rt['price'];
                $rt['price'] = $p['price'];
                $rt['p_name'] = $p['promotion']['title'];
                $rt['p_info'] = $p['info'];
                $rt['total'] = $rt['price'] * $rt['num'];
                $rt['give_money'] = $p['promotion']['type'] == 4 ? $p['promotion']['value'] : 0;
                $rt['give_score'] = $p['promotion']['type'] == 5 ? $p['promotion']['value'] : 0;
            }
        }

        // 计算总价
        $rt['total'] = max(0, $rt['total']);

        return $rt;
    }

    /**
     * 获取商品优惠信息
     */
    public function get_goods_discount($cid, $price, $sell_uid) {

        if (floatval($price) == 0) {
            return [];
        }

        // 查询折扣数据
        if (!isset($this->zk[$cid]) || !$this->zk[$cid]) {
            $this->zk[$cid] = $this->table(SITE_ID.'_goods_promotion')->where('uid='.(int)$sell_uid.' and stime < '.SYS_TIME.' and etime > '.SYS_TIME.' and id IN (select pid from `'.$this->dbprefix(SITE_ID).'_goods_promotion_item` where cid='.$cid.')')->getRow();
        }

        if (!$this->zk[$cid]) {
            return [];
        }


        $p = $this->zk[$cid];

        // 计算价格
        $value = floatval($p['value']);
        switch ($p['type']) {
            case '1':
                //折扣
                $price = $price * ($value/100);
                $info = dr_lang('折扣价¥%s元', number_format($price, 2));
                break;
            case '2':
                //减价
                $price = max(0, $price - $value);
                $info =  dr_lang('减价到¥%s元', number_format($value, 2));
                break;
            case '3':
                //固定价
                $info = dr_lang('特价¥%s元', number_format($value, 2));
                break;
            case '4':
                //返现金
                $info = dr_lang('返现金¥%s元', number_format($value, 2));
                break;
            case '5':
                //返金币
                $info = dr_lang('返%s%s', SITE_SCORE, $value);
                break;

            default:
                return [
                    'price' => $price,
                    'info' => dr_lang('无优惠'),
                    'promotion' => $p
                ];
                break;
        }

        return [
            'price' => $price,
            'info' => $info,
            'promotion' => $p
        ];
    }

    /**
     * 获取订单优惠信息
     */
    public function get_order_discount($price, $sell_uid, $member) {

        $rows = $this->table(SITE_ID.'_order_promotion')->where('uid='.(int)$sell_uid.' and money< '.floatval($price).' and stime < '.SYS_TIME.' and etime > '.SYS_TIME.'')->getAll();
        if (!$rows) {
            return [];
        }
        foreach ($rows as $t) {
            if (!$t['member']) {
                break;
            } elseif (array_intersect($t['member'], $member['groupid'])) {
                break;
            }
        }
        if (!$t) {
            return [];
        }

        // 计算价格
        $value = floatval($t['value']);
        $t['jian'] = 0;
        switch ($t['type']) {
            case '1':
                //折扣
                $t['jian'] = $price - $price * ($value/100);
                $info = dr_lang('优惠 ¥%s元', number_format($t['jian'], 2));
                break;
            case '2':
                //减价
                $t['jian'] = $value;
                $info =  dr_lang('减价¥%s元', number_format($value, 2));
                break;
            case '4':
                //返现金
                $info = dr_lang('返现金¥%s元', number_format($value, 2));
                break;
            case '5':
                //返金币
                $info = dr_lang('返%s%s', SITE_SCORE, $value);
                break;

            default:
                return [];
                break;
        }


        $t['info'] = $info;
        $t['price'] = $price;

        return $t;
    }

    /**
     * 获取商品的物流信息
     */
    public function get_shipping_info($shipping, $city) {

        $free = dr_string2array($shipping['free']); #包邮策略
        $freight = dr_string2array($shipping['freight']); #运费策略
        unset($shipping['free'], $shipping['freight']);

        // 所选城市id
        $info = dr_linkage(FC_ADDRESS_CITY, $city);
        if (!$info) {
            log_message('error', '无法计算运费：城市ID:'.$city.'不存在（'.FC_NOW_URL.'）');
            return [[], []];
        }

        // 城市的父级全部id
        $city = explode(',', $info['pids'].','.$info['ii']);
        if (!$city[0]) {
            unset($city[0]);
        }

        // 包邮策略
        $free_value = $value = $default = [];
        if ($free) {
            foreach ($free as $t) {
                if ($t['city']) {
                    // 单独城市规则
                    if (in_array($t['city'], $city)) {
                        $value = $t;
                        break;
                    }
                } else {
                    // 全国策略
                    $default = $t;
                }
            }
            $free_value = $value ? $value : $default;
            if ($free_value) {
                $free_value['value'] = $free_value[$free_value['type']];
                unset($free_value[1], $free_value[2], $free_value[3]);
            }
        }


        // 按地区获取运费信息
        $value = [];
        $default = $freight['default'];
        unset($freight['default']);

        if ($freight) {
            foreach ($freight as $t) {
                if ($t['city']) {
                    if (in_array($t['city'], $city)) {
                        $value = $t;
                        break;
                    }
                } else {
                    $default = $t;
                }
            }
        }

        $freight_value = $value ? $value : $default;

        return [$free_value, $freight_value];
    }

    /**
     * 计算运费
     * @param   城市id
     * @param   当前商品数据
     * @goods   总价和订单的价
     */
    public function get_freight_price($city, $goods) {

        if (!$city) {
            return 0;
        } else if (!\Phpcmf\Service::C()->mall_info['shipping']) {
            return 0;
        }

        $price = 0;
        foreach ($goods as $t) {
            if (!$t['data']['shipping'] || !\Phpcmf\Service::C()->mall_info['shipping'][$t['data']['shipping']]) {
                log_message('error', '无法计算运费：城市ID:'.$city.'不存在（'.FC_NOW_URL.'）');
                continue;
            }

            $yunfei = 0;
            $shipping_param = dr_string2array($t['data']['shipping_param']);
            if (!isset($shipping_param['value']) || !$shipping_param['value']) {
                log_message('error', '无法计算运费：没有设置商品运输参数（'.FC_NOW_URL.'）');
                continue;
            }

            list($free, $freight) = $this->get_shipping_info(\Phpcmf\Service::C()->mall_info['shipping'][$t['data']['shipping']], $city);

            if ($freight['start']) {
                switch ($shipping_param['param']) {
                    case 1: // 按数量
                        // 首数量内容的价格
                        $yunfei+= $freight['postage'];
                        // 购买数量超过规定是首数量时计算续费价格
                        $t['num'] > $freight['start'] && $yunfei+= floor(($t['num'] - $freight['start']) / $freight['plus']) * $freight['postageplus'];
                        if ($free) {
                            switch ($free['type']) {
                                case 1:
                                    // 满x件包邮
                                    $t['num'] >= $free['value'] && $yunfei = 0;
                                    break;
                                case 2:
                                    // 满x元包邮
                                    $t['total'] - $free['value'] >= 0 && $yunfei = 0;
                                    break;
                                case 3:
                                    // 满x件， 满x元包邮
                                    $t['num'] >= $free['value']['dw'] && $t['total'] - $free['value']['price'] >= 0 && $yunfei = 0;
                                    break;
                            }
                        }
                        break;
                    case 2: // 按重量
                        // 首重量内的价格
                        $yunfei+= $freight['postage'];
                        // 购买重量超过规定是首重量时计算续费价格
                        $v = $t['num'] * $shipping_param['value']; // 总重量
                        $v > $freight['start'] && $yunfei+= floor(($v - $freight['start']) / $freight['plus']) * $freight['postageplus'];
                        if ($free) {
                            switch ($free['type']) {
                                case 1:
                                    // 在xkg内包邮
                                    $v >= $free['value'] && $yunfei = 0;
                                    break;
                                case 2:
                                    // 满x元包邮
                                    $t['total'] - $free['value'] >= 0 && $yunfei = 0;
                                    break;
                                case 3:
                                    // 在xkg内， 满x元包邮
                                    $v >= $free['value']['dw'] && $t['total'] - $free['value']['price'] >= 0 && $yunfei = 0;
                                    break;
                            }
                        }
                        break;
                    case 3: // 按体积
                        // 首体积内的价格
                        $yunfei+= $freight['postage'];
                        // 购买体积超过规定是首体积时计算续费价格
                        $v = $t['num'] * $shipping_param['value']; // 总重量
                        $v > $freight['start'] && $yunfei+= floor(($v - $freight['start']) / $freight['plus']) * $freight['postageplus'];

                        if ($free) {
                            switch ($free['type']) {
                                case 1:
                                    // 在x m³内包邮
                                    $v >= $free['value'] && $yunfei = 0;
                                    break;
                                case 2:
                                    // 满x 元包邮
                                    $t['total'] - $free['value'] >= 0 && $yunfei = 0;
                                    break;
                                case 3:
                                    // 在x m³内， 满x元包邮
                                    $v >= $free['value']['dw'] && $t['total'] - $free['value']['price'] >= 0 && $yunfei = 0;
                                    break;
                            }
                        }
                        break;
                }
            }


            $price+= $yunfei;

        }

        return $price;
    }

    // 获取账号店铺信息
    public function get_mall_info($uid) {

        $rt = $this->db->table(SITE_ID.'_mall')->where('uid', $uid)->get()->getRowArray();
        if (!$rt) {
            return [];
        } elseif ($rt['status'] == 9) {
            return $rt;
        } else {
            return [];
        }
    }

    // 获取店铺信息
    public function get_mall_info_id($cid) {

        $rt = $this->db->table(SITE_ID.'_mall')->where('id', $cid)->get()->getRowArray();
        if (!$rt) {
            return [];
        } elseif ($rt['status'] == 9) {
            return $rt;
        } else {
            return [];
        }
    }



    //=======================订单状态变更处理


    // 付款成功
    // 付款状态 付款状态 1付清 2已收定金　0未付款
    public function pay($id, $pay_id, $pay_type = '') {

        if (!$id) {
            log_message('error', '订单付款回调失败：id值不存在（'.FC_NOW_URL.'）');
            return;
        }

        $order = $this->table_site('order')->get($id);
        if (!$order) {
            log_message('error', '订单付款回调失败：订单（'.$id.'）不存在（'.FC_NOW_URL.'）');
            return;
        }

        $order['pay_id'] = $pay_id;
        $order['pay_time'] = SYS_TIME;
        $order['pay_status'] = 1;
        $order['pay_type'] = $pay_type ? $pay_type : $order['pay_type'];

        // 付款状态
        $order['status'] = 2;

        $rt = $this->table_site('order')->update($id, [
            'pay_id' => $order['pay_id'],
            'pay_type' => $order['pay_type'],
            'pay_time' => $order['pay_time'],
            'pay_status' => $order['pay_status'],
            'status' => $order['status'],
        ]);
        if (!$rt['code']) {
            log_message('error', '订单（'.$id.'）付款回调失败：'.$rt['msg'].'（'.FC_NOW_URL.'）');
            return;
        }

        // 减少库存量
        $goods = $this->table_site('order_goods')->where('oid', $id)->getAll();
        if (!$goods) {
            log_message('error', '订单（'.$id.'）库存计算失败：没有找到订单对应的商品（'.FC_NOW_URL.'）');
        } else {
            foreach ($goods as $t) {
                list($table, $cid) = explode('-', $t['mid']);
                $data = $this->table($table)->get($cid);
                if ($data) {
                    // 找到商品
                    $update = [];
                    if ($t['sku_value']) {
                        $data['price_sku'] = dr_string2array($data['price_sku']);
                        if (!isset($data['price_sku']['value'][$t['sku_value']]) || !$data['price_sku']['value'][$t['sku_value']]) {
                            log_message('error', '订单（'.$id.'）库存计算失败：sku信息查询失败（'.FC_NOW_URL.'）');
                        } else {
                            // sku库存值
                            $data['price_sku']['value'][$t['sku_value']]['quantity'] = max(0, $data['price_sku']['value'][$t['sku_value']]['quantity'] - $t['num']);
                            $update = [
                                'price_sku' => dr_array2string($data['price_sku']),
                                'price_quantity' => max($data['price_quantity'] - $t['num'], 0),
                            ];
                        }
                    }
                    !$update && $update = [
                        'price_quantity' => max($data['price_quantity'] - $t['num'], 0),
                    ];
                    // 销量
                    isset($data['volume']) && $update['volume'] = (int)$data['volume'] + $t['num'];
                    $this->db->table($table)->where('id', $cid)->update($update);
                }
            }
        }

        // 创建日志
        $this->add_log($order, dr_lang('付款成功'));

        // 付款成功后的交易流程
        switch ((int)\Phpcmf\Service::C()->mall_info['order']['buy_step']) {
            case 1:
                //付款→收货→完成
                $this->delivery($order, '付款后自动发货');
                break;
            /*case 2:
                //付款→发货→完成
                break;*/
            case 3:
                //付款→完成
                $this->receipt($order, '付款后自动完成订单');
                break;
            /*default:
                // 付款→发货→收货→完成
                break;*/
        }



        // 付款提醒
        \Phpcmf\Service::L('Notice')->send_notice('order_status_2', $order);
        
        $order['uid'] = $order['sell_uid'];
        $order['username'] = $order['sell_username'];
        \Phpcmf\Service::L('Notice')->send_notice('order_status_2', $order);

        // 通知用户充值消息
        return dr_return_data($order['id'], 'ok');
    }

    // 发货成功
    // 发货状态 0未发货 1发货 2确认收货 3退货成功 4换货成功
    public function delivery($order, $info) {

        $order['deliver_id'] = $info['id'];
        $order['deliver_time'] = SYS_TIME;
        $order['deliver_status'] = 1;

        $rt = $this->table_site('order')->update($order['id'], [
            'deliver_id' => $order['deliver_id'],
            'deliver_time' => $order['deliver_time'],
            'deliver_status' => $order['deliver_status'],
        ]);
        if (!$rt['code']) {
            return $rt;
        }

        // 创建日志
        $this->add_log($order, $info['note']);

        // 发货提醒
        \Phpcmf\Service::L('Notice')->send_notice('order_deliver_status_1', $order);

        if ((int)\Phpcmf\Service::C()->mall_info['order']['buy_step'] == 2) {
            // 发货→完成
            $this->receipt($order, '发货后自动完成订单');
        }

        // 通知用户发货消息
        return dr_return_data($order['id'], 'ok');
    }

    // 签收成功
    // 发货状态 0未发货 1发货 2确认收货 3退货成功 4换货成功
    public function receipt($order, $note) {

        $order['status'] = 9; // 订单交易完成
        $order['deliver_status'] = 2;
        $order['receipt_time'] = SYS_TIME;

        $rt = $this->table_site('order')->update($order['id'], [
            'status' => $order['status'],
            'deliver_status' => $order['deliver_status'],
            'receipt_time' => $order['receipt_time'],
        ]);
        if (!$rt['code']) {
            return $rt;
        }

        // 表示交易成功
        $sjje = $order['money'] - $order['income_money'] - $order['give_money'];

        if ($sjje > 0) {
            // 为商家增加钱
            \Phpcmf\Service::M('Pay')->add_money($order['sell_uid'], $sjje);
            // 增加一条记录
            \Phpcmf\Service::M('Pay')->add_paylog([
                'uid' => $order['sell_uid'],
                'username' => $order['sell_username'],
                'touid' => '0',
                'tousername' => '',
                'mid' => 'order',
                'title' => dr_lang('交易成功'),
                'value' => $sjje,
                'type' => 'system',
                'status' => 1,
                'result' => '订单编号：'.$order['sn'],
                'paytime' => SYS_TIME,
                'inputtime' => SYS_TIME,
            ]);
        }

        // 赠送金币和返现
        if ($order['give_score'] > 0) {
            \Phpcmf\Service::M('member')->add_score($order['uid'], $order['give_score'], dr_lang('订单['.$order['sn'].']赠送'));
        }
        if ($order['give_money'] > 0 && $sjje >= $order['give_money']) {
            // 为买家增加钱
            \Phpcmf\Service::M('Pay')->add_money($order['uid'], $order['give_money']);
            // 增加一条记录
            \Phpcmf\Service::M('Pay')->add_paylog([
                'uid' => $order['uid'],
                'username' => $order['username'],
                'touid' => '0',
                'tousername' => '',
                'mid' => 'order',
                'title' => dr_lang('订单['.$order['sn'].']返现'),
                'value' => $order['give_money'],
                'type' => 'system',
                'status' => 1,
                'result' => '订单编号：'.$order['sn'],
                'paytime' => SYS_TIME,
                'inputtime' => SYS_TIME,
            ]);
        }

        // 店铺销量
        if ($order['mall_cid']) {
            $this->db->table(SITE_ID.'_mall')->where('id', intval($order['mall_cid']))->set('volume', 'volume+1', FALSE)->update();
        }

        // 商品表状态
        $this->db->table(SITE_ID.'_order_goods')->where('oid', $order['id'])->update([
            'status' => 1,
        ]);

        // 创建日志
        $this->add_log($order, $note);

        // 通知提醒
        \Phpcmf\Service::L('Notice')->send_notice('order_status_9', $order);
        $order['uid'] = $order['sell_uid'];
        $order['username'] = $order['sell_username'];
        \Phpcmf\Service::L('Notice')->send_notice('order_status_9', $order);

        // 通知用户发货消息
        return dr_return_data($order['id'], 'ok');
    }

    // 交易关闭
    public function close($order, $note) {

        if ($order['status'] == 0) {
            return dr_return_data(0, dr_lang('订单已经关闭')); // 已经关闭
        }

        // 判断是否满足退款条件

        // 变更状态
        $rt = $this->table_site('order')->update($order['id'], [
            'status' => 0,
            'pay_status' => $order['pay_status'] == 1 ? 2 : $order['pay_status'],
        ]);
        if (!$rt['code']) {
            return $rt;
        }

        $order['status'] = 0;

        // 创建日志
        $this->add_log($order, $note);

        // 关闭提醒
        \Phpcmf\Service::L('Notice')->send_notice('order_status_0', $order);

        // 退钱操作
        // 退款到买家
        if ($order['money'] > 0 && $order['pay_status'] == 1) {
            $rt = $this->query('update `'.$this->dbprefix('member').'` set `money`=`money`+'.$order['money'].',`freeze`=`spend`-'.$order['money'].' where id='.$order['uid']);
            if ($rt['code']) {
                \Phpcmf\Service::M('pay')->add_paylog([
                    'mid' => 'order',
                    'uid' => $order['uid'],
                    'username' => $order['username'],
                    'touid' => 0,
                    'tousername' => '',
                    'title' => '订单退款',
                    'value' => $order['money'],
                    'type' => 'finecms',
                    'url' => dr_member_url('order/home/show', ['id' => $order['id']]),
                    'status' => 1,
                    'result' => '订单号：'.$order['sn'],
                    'paytime' => SYS_TIME,
                ]);
            }
        }

        // 通知用户发货消息
        return dr_return_data($order['id'], 'ok');
    }

    // 退款订单
    public function refund($order, $note) {

        if ($order['status'] != 2) {
            return dr_return_data(0, dr_lang('订单状态不符合退款'));
        } elseif ($order['pay_status'] == 2) {
            return dr_return_data(0, dr_lang('订单已经退款'));
        }

        // 变更状态
        $rt = $this->table_site('order')->update($order['id'], [
            'status' => 0,
            'pay_status' => 2,
        ]);
        if (!$rt['code']) {
            return $rt;
        }

        // 退款到买家
        if ($order['money'] > 0) {
            $rt = $this->query('update `'.$this->dbprefix('member').'` set `money`=`money`+'.$order['money'].',`freeze`=`spend`-'.$order['money'].' where id='.$order['uid']);
            if ($rt['code']) {
                \Phpcmf\Service::M('pay')->add_paylog([
                    'mid' => 'order',
                    'uid' => $order['uid'],
                    'username' => $order['username'],
                    'touid' => 0,
                    'tousername' => '',
                    'title' => '订单退款',
                    'value' => $order['money'],
                    'type' => 'finecms',
                    'url' => dr_member_url('order/home/show', ['id' => $order['id']]),
                    'status' => 1,
                    'result' => '订单号：'.$order['sn'],
                    'paytime' => SYS_TIME,
                ]);
            }
        }

        // 创建日志
        $this->add_log($order, $note);

        return dr_return_data($order['id'], 'ok');

    }
}