<?php

# 支付

namespace Mshop\Lib;

use Dever;

class Buy
{
    # 1是门店,2是仓库,3是工厂,1,2,3是查看采购人的订单,11,12,13是查看供货商的订单
    public $type = 1;
    # 1是列表,2是详情
    public $view = 1;
    # 获取配置
    public $config = array();
    # table
    public $table = 'shop/buy_order';

    public function __construct()
    {
        $this->config = Dever::db($this->table)->config;
    }

    # 设置订单的类型
    public function set($type, $view)
    {
        $this->type = $type;
        $this->view = $view;

        return $this;
    }


    # 获取公共的where
    public function where($id)
    {
        $where = array();
        if ($this->type > 10) {
            $type = $this->type - 10;
            $where['source_type'] = $type;
            $where['source_id'] = $id;
        } else {
            $where['type'] = $this->type;
            $where['type_id'] = $id;
        }
        
        if (!$where) {
            Dever::alert('参数错误');
        }

        return $where;
    }

    # 更新导出状态
    public function setOutStatus($id, $type = 1)
    {
        if ($type == 1) {
            $data['out_status'] = 2;
            $data['out_date'] = time();
        } else {
            $data['source_out_status'] = 2;
            $data['source_out_date'] = time();
        }

        $data['where_id'] = $id;
        Dever::db('shop/buy_order')->update($data);
    }

    # 获取订单列表
    public function getList($id, $status = false)
    {
        $result = array();
        $where = $this->where($id);
        $status = Dever::input('status', $status);
        if ($status) {
            if ($status == 'refund') {
                $where['refund_status'] = 2;
            } else {
                $where['status'] = $status;
            }
        }

        $order_num = Dever::input('order_num');
        if ($order_num) {
            $where['order_num'] = $order_num;
        }

        $refund_status = Dever::input('refund_status');
        if ($refund_status) {
            $where['refund_status'] = $refund_status;
        }

        $result['search_value'] = $where;
        $result['search_value']['day'] = $day = Dever::input('day');
        if ($day) {
            if ($this->type > 10) {
                $where['start_o'] = Dever::maketime($day . ' 00:00:00');
                $where['end_o'] = Dever::maketime($day . ' 23:59:59');
            } elseif ($this->type == 2) {
                $where['start_f'] = Dever::maketime($day . ' 00:00:00');
                $where['end_f'] = Dever::maketime($day . ' 23:59:59');
            } else {
                $where['start'] = Dever::maketime($day . ' 00:00:00');
                $where['end'] = Dever::maketime($day . ' 23:59:59');
            }
        }

        $result['search_value']['start'] = $start = Dever::input('start');
        $result['search_value']['end'] = $end = Dever::input('end');
        if ($start && $end) {
            if ($this->type > 10) {
                $where['start_o'] = Dever::maketime($start);
                $where['end_o'] = Dever::maketime($end);
            } elseif ($this->type == 2) {
                $where['start_f'] = Dever::maketime($start);
                $where['end_f'] = Dever::maketime($end);
            } else {
                $where['start'] = Dever::maketime($start);
                $where['end'] = Dever::maketime($end);
            }
        }

        $type = Dever::input('type');
        if ($type) {
            $where['type'] = $type;
        }
        $source_type = Dever::input('source_type');
        if ($source_type) {
            $where['source_type'] = $source_type;
        }
        $parent_type = Dever::input('parent_type');
        if ($parent_type) {
            $where['parent_type'] = $parent_type;
        }
        $out_status = Dever::input('out_status');
        if ($out_status) {
            $where['out_status'] = $out_status;
        }
        $source_out_status = Dever::input('source_out_status');
        if ($source_out_status) {
            $where['source_out_status'] = $source_out_status;
        }

        $excel = Dever::input('excel', 1);
        if ($excel == 2) {
            $result['order'] = Dever::db($this->table)->getData($where);
        } else {
            $result['order'] = Dever::db($this->table)->getAll($where);
        }

        if ($result['order']) {
            foreach ($result['order'] as $k => $v) {
                $result['order'][$k] = $this->getInfo($v);
            }
        }

        $result['search'] = array();
        $result['search']['status'] = array
        (
            array('value' => 1, 'name' => '待支付'),
            array('value' => 2, 'name' => '待审核'),
            array('value' => 3, 'name' => '待发货'),
            array('value' => 4, 'name' => '待收货确认'),
            array('value' => 5, 'name' => '已完成'),
            array('value' => 6, 'name' => '已完成(有退款)'),
            array('value' => '7,8,11', 'name' => '已取消'),
        );

        $result['config'] = Dever::db('main/manage_config')->find();

        return $result;
    }

    # 查看详情
    public function getView($id, $order_id, $show = true)
    {
        $where = $this->where($id);
        $where['id'] = $order_id;

        $result = Dever::db($this->table)->find($where);

        if (!$result) {
            Dever::alert('订单不存在');
        }

        if ($show) {
            $result = $this->getInfo($result, true);
        }

        $result['config'] = Dever::db('main/manage_config')->find();

        return $result;
    }

    # 查看退款详情
    public function getRefund($id, $order_id)
    {
        $data = $this->getView($id, $order_id, false);

        $data['refund'] = Dever::db('shop/buy_order_refund')->select(array('order_id' => $info['id']));

        return $data;
    }

    # 获取订单详细信息
    public function getInfo($info, $view = false)
    {
        if ($info['status'] == 1) {
            # 15分钟内支付,900秒
            $m = 900;
            # 支付倒计时
            $info['time'] = time() - $info['cdate'];
            if ($info['time'] >= $m) {
                # 已过期,自动取消
                $info['time'] = -1;
                Dever::db($this->table)->update(array('where_id' => $info['id'], 'status' => 11));
                $info['status'] = 11;
            } else {
                $info['time'] = $m - $info['time'];
            }
        }

        $info['status_name'] = $this->config['status'][$info['status']];

        $info['goods'] = Dever::db('shop/buy_order_goods')->select(array('order_id' => $info['id']));
        if ($info['type'] == 1) {
            $info['type_info'] = Dever::db('shop/info')->find($info['type_id']);
        } elseif ($info['type'] == 2) {
            $info['type_info'] = Dever::db('store/info')->find($info['type_id']);
        } elseif ($info['type'] == 3) {
            $info['type_info'] = Dever::db('factory/info')->find($info['type_id']);
        }

        if ($info['source_type'] == 1) {
            $info['source_info'] = Dever::db('shop/info')->find($info['source_id']);
        } elseif ($info['source_type'] == 2) {
            $info['source_info'] = Dever::db('store/info')->find($info['source_id']);
        } elseif ($info['source_type'] == 3) {
            $info['source_info'] = Dever::db('factory/info')->find($info['source_id']);
        }
        
        $info['cdate_day'] = date('Y-m-d', $info['cdate']);
        $info['cdate'] = date('Y-m-d H:i', $info['cdate']);
        
        if ($info['operdate']) {
            $info['operdate_day'] = date('Y-m-d', $info['operdate']);
            $info['operdate'] = date('Y-m-d H:i', $info['operdate']);
            
        } else {
            $info['operdate_day'] = $info['cdate_day'];
            $info['operdate'] = $info['cdate'];
            
        }
        $goods_status = Dever::db('shop/buy_order_goods')->config['status'];
        $goods_process = Dever::db('shop/buy_order_refund')->config['process'];
        if ($view || $this->view == 2) {
            foreach ($info['goods'] as $k => $v) {
                $info['goods'][$k]['info'] = Dever::load('goods/lib/info')->getPayInfo($v['goods_id'], $v['sku_id']);
                $info['goods'][$k]['status_name'] = $goods_status[$v['status']];

            }
        } else {
            foreach ($info['goods'] as $k => $v) {
                $goods = Dever::db('goods/info')->one($v['goods_id']);
                $info['goods'][$k]['name'] = $goods['name'];
                $info['goods'][$k]['cover'] = $goods['cover'];
                $info['goods'][$k]['status_name'] = $goods_status[$v['status']];
            }
        }

        if (!$info['refund_cash']) {
            $info['refund_cash'] = 0;
        }

        # 配送信息
        $info['ps_info'] = Dever::db('shop/buy_order_ps')->find(array('order_id' => $info['id']));
        if ($info['ps_info']) {
            $info['ps_info']['service'] = Dever::array_decode($info['ps_info']['service']);
            $info['ps_info']['cdate_day'] = date('Y-m-d', $info['ps_info']['cdate']);
            $info['ps_info']['cdate'] = date('Y-m-d H:i', $info['ps_info']['cdate']);
            
            $info['ps_info']['ydate_day'] = '-';
            if ($info['ps_info']['ydate']) {
                $info['ps_info']['ydate_day'] = date('Y-m-d', $info['ps_info']['ydate']);
                $info['ps_info']['ydate'] = date('Y-m-d H:i', $info['ps_info']['ydate']);
                
            }

            $status = Dever::db('shop/buy_order_ps')->config['status'];
            $info['ps_info']['status_name'] = $status[$info['ps_info']['status']];
            
            if ($info['ps_info']['service']) {
                if (isset($info['ps_info']['service']['serivce'])) {
                    $info['ps_info']['service'] = $info['ps_info']['service']['service'];
                }
                foreach ($info['ps_info']['service'] as $k => $v) {
                    if (isset($v['order_num']) && $v['order_num']) {
                        $info['ps_info']['service'][$k]['service_name'] = '供应商自送';
                        if (isset($v['service_id']) && $v['service_id'] > 0) {
                            $service = Dever::db('shop/service')->find($v['service_id']);
                            if ($service) {
                                $info['ps_info']['service'][$k]['service_name'] = $service['name'];
                            } else {
                                $info['ps_info']['service'][$k]['service_name'] = '';
                            }
                            
                        }
                    } else {
                        unset($info['ps_info']['service'][$k]);
                    }
                }
            }
        }

        $info = $this->refund_button($info);

        return $info;
    }

    # 是否可以退款
    public function refund_button($info)
    {
        $info['refund_button'] = 1;
        # 是否显示退款按钮
        $manage_config = Dever::db('main/manage_config')->find();

        $refund_time = $manage_config['buy_refund_day']*86400;

        if ($refund_time > 0 && ($info['status'] == 5 || $info['status'] == 6)) {
            $cur = time();
            if (strstr($info['fdate'], '-')) {
                $info['fdate'] = Dever::maketime($info['fdate']);
            }
            if ($cur - $info['fdate'] < $refund_time) {
                # 可以退款
                $info['refund_button'] = 1;
            } else {
                # 不可以退款
                $info['refund_button'] = 2;
            }
        }
        return $info;
    }

    # 发起支付
    public function action($uid, $type, $type_id, $name, $num, $goods, $price, $info, $refer = '', $area = '',$method=false)
    {
        $openid = false;
        if ($uid > 0) {
            $wechat = Dever::db('passport/wechat')->one(array('uid' => $uid, 'type' => 1, 'system_id' => 2));

            if (!$wechat) {
                Dever::alert('错误的用户信息');
            }

            $openid = $wechat['openid'];
        }

        $order_data['type'] = $type;
        $order_data['type_id'] = $type_id;
        if ($area) {
            $order_data['area'] = $area . ',' . $type_id;
        }
        
        $order_data['name'] = $name;
        $order_data['num'] = $num;
        $order_data['info'] = $info;
        $order_data['price'] = $price;

        $time = time();
        $order_data_where = $order_data;
        $order_data_where['start'] = $time - 60;
        $order_data_where['end'] = $time;
        $order_data_where['option']['start'] = array('yes-cdate', '>=');
        $order_data_where['option']['end'] = array('yes-cdate', '<=');

        $info = Dever::db('shop/buy_order')->find($order_data_where);

        $order_data['order_num'] = $this->getOrderId();
        $order_data['refund_cash'] = 0;
        $order_data['refund_p_cash'] = 0;

        
        if (!$info) {
            $id = Dever::db('shop/buy_order')->insert($order_data);
        } else {
            return array
            (
                'order' => '',
                'order_num' => $info['order_num'],
                'order_id' => $info['id'],
                'type' => 'test',
            );
        }

        if($id && isset($method) &&  $method && isset($method['method']) && $method['method'] == 1){
           if($method && isset($method['price']) && $method['price'] && $method['yue']>=0){
                $shop = Dever::db('shop/info')->find($type_id);
                $record = Dever::load('shop/lib/record')->pingtai($type_id,$shop['sid'],4,$id,$method['price'],$method['yue']);
                if($method['type'] ==1){
                    $record_cash = $method['price'];
                }elseif($method['type'] == 2){
                    $record_cash = $shop['price'];
                }
                Dever::db('shop/buy_order')->update(array('where_id'=>$id,'set_record_cash'=>$record_cash));
           } 
        }

        if (!$id) {
            Dever::alert('支付失败');
        }

        foreach($goods as $k => $v) {
            $data['order_id'] = $id;
            $data['goods_id'] = $v['id'];
            $data['sku_id'] = $v['sku_id'];
            $data['price'] = $v['price'];
            $data['num'] = $v['buy_num'];

            Dever::db('shop/buy_order_goods')->insert($data);
        }

        // return  'ok';
        if ($price <= 0) {

            $param['pay_product_id'] = $id;
            $param['pay_order_id'] = $order_data['order_num'];
            $param['pay_status'] = 2;
            $param['pay_cash'] = $price;
            $param['pay_msg'] = '';
            $this->success($param);
            return array
            (
                'order' => '',
                'order_num' => $order_data['order_num'],
                'order_id' => $id,
                'type' => 'test',
            );
        }

        $param = array
        (
            'project_id' => 2,
            'channel_id' => 1,
            'system_source' => 5,
            'account_id' => 7,
            'uid' => $uid,
            'name' => $order_data['name'],
            'openid' => $openid,
            'cash' => $price,
            'product_id' => $id,
            'order_id' => $order_data['order_num'],
            'refer' => $refer,
        );

        $receipt = Dever::input('receipt');
        if ($receipt) {
            $param['receipt'] = $receipt;
        }

        $result = Dever::load('pay/api.pay', $param);
        //$result['type'] = 'test';
        //$result['order'] = '';

        $result['order_num'] = $order_data['order_num'];
        $result['order_id'] = $id;
        return $result;
    }

    # 再次发起支付
    public function raction($id, $refer = '')
    {
        $order = Dever::db('shop/buy_order')->find($id);

        if (!$order) {
            Dever::alert('订单信息错误');
        }

        if ($order['status'] > 1) {
            Dever::alert('订单已支付或已取消');
        }

        $param = array
        (
            'project_id' => 2,
            'channel_id' => 1,
            'system_source' => 5,
            'account_id' => 7,
            'uid' => -1,
            'name' => $order['name'],
            'cash' => $order['price'],
            'product_id' => $id,
            'order_id' => $order['order_num'],
            'refer' => $refer,
        );

        $receipt = Dever::input('receipt');
        if ($receipt) {
            $param['receipt'] = $receipt;
        }

        $result = Dever::load('pay/api.pay', $param);
        $result['order_num'] = $order['order_num'];
        $result['order_id'] = $id;

        return $result;
    }

    # 查询是否支付
    public function cpay($id, $system_source = 5, $refer = '')
    {
        $order = Dever::db('shop/buy_order')->find($id);

        if (!$order) {
            Dever::alert('订单信息错误');
        }

        $result['order_num'] = $order['order_num'];
        $result['order_id'] = $id;

        if ($order['status'] > 1 && $order['status'] <= 6) {
            # 已支付
            $result['status'] = 1;
        } else {
            # 待支付
            $result['status'] = 2;
        }

        return $result;
    }

    # 支付成功回调 安全加密 设置token
    public function success_secure_api_token()
    {
        $project_id = Dever::input('pay_project_id');
        $info = Dever::db('pay/project')->one($project_id);
        if ($info) {
            return $info['key'];
        }
        return 'shop_buy_dever_2020';
    }

    # 支付成功回调 安全加密
    public function success_secure_api($param = array())
    {
        $this->success($param);
    }

    # 支付成功回调
    public function success($param = array())
    {
        $send = $param ? $param : Dever::preInput('pay_');
        $product_id = $send['pay_product_id'];
        $order_id = $send['pay_order_id'];
        $status = $send['pay_status'];
        $cash = $send['pay_cash'];
        $msg = $send['pay_msg'];

        $order = Dever::db('shop/buy_order')->one(array('id' => $product_id, 'time' => time()));
        if ($order && $order['status'] == 1 && $status == 2) {
            $update['status'] = 2;
            $update['where_id'] = $order['id'];
            Dever::db('shop/buy_order')->update($update);

            # 生成结算单
            Dever::load('cash/lib/order')->up($order, 1, 1);
        }

        return 'ok';
    }

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

    # 添加配送信息
    public function updatePs($order, $status = 1)
    {
        $where['order_id'] = $order['id'];
        $data = Dever::db('shop/buy_order_ps')->find($where);

        if ($data) {
            $update['where_id'] = $data['id'];
            $update['status'] = $status;
            $update['ydate'] = time();
            Dever::db('shop/buy_order_ps')->update($update);
        }
    }

    # 确认收货
    public function finish($id, $order_id)
    {
        $data = $this->getView($id, $order_id, false);
        if ($data['status'] <= 4) {
            if ($data['refund_cash'] > 0) {
                $status = 6;
            } else {
                $status = 5;
            }
            $state = Dever::db('shop/buy_order')->update(array('where_id' => $data['id'], 'status' => $status, 'fdate' => time()));
            if ($state) {
                $this->updatePs($data, 3);
                # 增加库存
                $where['order_id'] = $data['id'];
                $where['status'] = 1;
                $goods = Dever::db('shop/buy_order_goods')->select($where);
                if ($goods) {
                    Dever::load('shop/lib/goods')->oper($data, 1, 1, $goods);
                }

                # 生成结算单
                Dever::load('cash/lib/order')->up($data, 1, 2);
            }

            return 'ok';
        } else {
            Dever::alert('您没有权限');
        }
    }

    # 取消订单
    public function cancel($id, $order_id)
    {
        $data = $this->getView($id, $order_id, false);
        if ($data['status'] == 1) {
            $state = Dever::db('shop/buy_order')->update(array('where_id' => $data['id'], 'status' => 7, 'operdate' => time()));
            # 生成结算单
            if ($state) {
                
                if (isset($data['record_cash']) && $data['record_cash'] && $data['record_cash'] > 0) {
                    # 还原钱包
                    $shop = Dever::db('shop/info')->find($data['type_id']);
                    if ($shop) {
                        Dever::load('shop/lib/record')->pingtai($shop['id'], $shop['sid'],3, $data['id'], $data['record_cash'], round($shop['price'] + $data['record_cash'], 2), '订单退货返还');

                        //Dever::load('cash/lib/order')->up($data, 1, 3);
                    }
                }
            }
            return 'ok';
        } else {
            Dever::alert('当前订单状态不允许取消');
        }
    }

    # 查看订单状态
    public function orderStatus($id)
    {
        $config = Dever::db('shop/buy_order')->config;

        $info = Dever::db('shop/buy_order')->one($id);
        $tk = Dever::db('shop/buy_order_refund')->find(array('order_id' => $info['id'], 'process' => 1));
        $status = $config['status'][$info['status']];

        if ($tk) {
            $status = '申请退款中';
        }
        return $status;
    }

    # 后台审核退款
    public function refund_commit_api()
    {
        $id = Dever::input('id');
        $process = Dever::input('process');
        return Dever::load('shop/lib/refund')->set('buy')->action($id, $process, false);
    }

    # 货物未发出,仅退款
    public function refund_apply_commit_api()
    {
        $order_id = Dever::input('order_id');
        $type = Dever::input('type');
        $type_id = Dever::input('type_id');
        $desc = Dever::input('desc');
        $pic = Dever::input('pic');

        return Dever::load('shop/lib/refund')->set('buy')->apply($type, $type_id, $order_id, false, 3, 0, $desc, $pic, 2);
    }

    # 货物已收到 全部退款 报损 需要审核
    public function refund_apply_info_commit_api()
    {
        $order_id = Dever::input('order_id');
        $status = Dever::input('status');
        $desc = Dever::input('desc');
        $pic = Dever::input('pic');
        $type = Dever::input('type');
        $type_id = Dever::input('type_id');

        return Dever::load('shop/lib/refund')->set('buy')->apply($type, $type_id, $order_id, false, $status, 0, $desc, $pic, 1);
    }

    # 部分退款信息 报损
    public function refund_apply_info_one_info()
    {
        $order_id = Dever::input('order_id');
        $order_goods_id = Dever::input('order_goods_id');
        $type = Dever::input('type');
        $type_id = Dever::input('type_id');

        return Dever::load('shop/lib/refund')->set('buy')->getInfo($type, $type_id, $order_id, $order_goods_id);
    }

    # 部分退款 报损
    public function refund_apply_info_one_commit_api()
    {
        $order_id = Dever::input('order_id');
        $order_goods_id = Dever::input('order_goods_id');
        $num = Dever::input('num', 0);
        $status = Dever::input('status');
        $desc = Dever::input('desc');
        $pic = Dever::input('pic');
        $type = Dever::input('type');
        $type_id = Dever::input('type_id');

        return Dever::load('shop/lib/refund')->set('buy')->apply($type, $type_id, $order_id, $order_goods_id, $status, $num, $desc, $pic, 1);
    }

    # 展示订单详情
    public function show()
    {
        $id = Dever::input('order_id');

        $type = 1;
        $type = Dever::input('search_option_type', $type);
        $type = Dever::input('type', $type);

        $noprice = Dever::input('noprice', 2);
        if ($type == 3) {
            $noprice = 1;
        }

        $info = Dever::db('shop/buy_order')->one($id);

        if (!$info) {
            return '无订单信息';
        }

        $result = array();

        $type_info = $this->show_base($info, $result, $type);

        $parent_order = $this->show_address($info, $result, $type, $type_info);

        $button = $this->show_button($info, $type, $parent_order, $noprice);

        $audit = Dever::input('audit');
        if ($audit == 1) {
            # 审核信息
            $this->show_audit($info, $result);
        } else {
            # 退款信息
            $this->show_refund($info, $result, $type);
            
            # 配送信息
            $this->show_ps($info, $result);

            # 商品信息
            $this->show_goods($info, $result, $type, $noprice);

            # 对账信息
            $this->show_dz($info, $result, $noprice);
        }

        $head = array
        (
            'name' => '基本信息',
            'btn' => $button,
        );
        $html = Dever::show($head, $result);

        return $html;
    }

    private function show_base($info, &$result, $type)
    {
        $config = Dever::db('shop/buy_order')->config;

        $status = $config['status'][$info['status']];

        $cdate = date('Y-m-d H:i', $info['cdate']);

        if ($info['operdate']) {
            $operdate = date('Y-m-d H:i', $info['operdate']);
        } else {
            $operdate = '';
        }

        if ($info['fdate']) {
            $fdate = date('Y-m-d H:i', $info['fdate']);
        } else {
            $fdate = '';
        }

        if ($type == 2 || $info['type'] == 2) {
            $info['price'] = $info['p_price'];
        }

        if ($info['refund_status'] == 2 && $info['status'] != 8) {
            $status .= '[申请报损中]';
        }

        $time = array();
        if ($type == 1) {
            $time[] = array('下单时间', $cdate);
            $time[] = array('订货时间', $operdate);
        } else {
            $time[] = array('订货时间', $operdate);
        }

        if ($fdate) {
            $time[] = array('完成时间', $fdate);
        }

        if ($info['type'] == 1) {
            $type_info = Dever::db('shop/info')->find($info['type_id']);
        } elseif ($info['type'] == 2) {
            $type_info = Dever::db('store/info')->find($info['type_id']);
        } elseif ($info['type'] == 3) {
            $type_info = Dever::db('store/info')->find($info['type_id']);
        }

        $result[$info['order_num']] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array('订单状态', $status),
                ),

                $time,
            )
        );

        return $type_info;
    }

    private function show_address($info, &$result, $type, $type_info)
    {
        
        $parent_order = array();
        if ($info['parent_type'] == 2) {
            $parent_order = Dever::db('shop/sell_order')->find($info['parent_order_id']);
        } elseif ($info['parent_type'] == 3) {
            $parent_order = Dever::db('agent/dh_order')->find($info['parent_order_id']);
        }
        if ($parent_order && isset($parent_order['uid']) && $parent_order['uid']) {
            if ($parent_order['address_id']) {
                $address = Dever::load('passport/address')->getOne($parent_order['uid'], $parent_order['address_id']);

                $result[$info['order_num']]['content'][] = array
                (
                    array('收件人', $address['contact']),
                    array('收件人手机', $address['mobile']),
                );
                $result[$info['order_num']]['content'][] = array
                (
                    array('收货地址', $address['address_info']),
                    array('门牌号', $address['house_number']),
                );
            } else {
                $user = Dever::db('passport/user')->find($parent_order['uid']);
                $result[$info['order_num']]['content'][] = array
                (
                    array('收件人', $user['username']),
                    array('收件人手机', $user['mobile']),
                );
            }
        } elseif ($parent_order && isset($parent_order['mid']) && $parent_order['mid']) {
            if ($parent_order['address_id']) {
                $address = Dever::load('agent/address')->getOne($parent_order['mid'], $parent_order['address_id']);

                $result[$info['order_num']]['content'][] = array
                (
                    array('收件人', $address['contact']),
                    array('收件人手机', $address['mobile']),
                );
                $result[$info['order_num']]['content'][] = array
                (
                    array('收货地址', $address['address_info']),
                    array('门牌号', $address['house_number']),
                );
            } else {
                $user = Dever::db('agent/member')->find($parent_order['mid']);
                $result[$info['order_num']]['content'][] = array
                (
                    array('收件人', $user['mid']),
                    array('收件人手机', $user['mobile']),
                );
            }
        } else {
            $result[$info['order_num']]['content'][] = array
            (
                array('配送至', $type_info['name']),
                array('配送地址', $type_info['address']),
            );
            $result[$info['order_num']]['content'][] = array
            (
                array('联系人', $type_info['truename']),
                array('联系电话', $type_info['mobile']),
                array('订单备注', $info['info']),
            );
            $result[$info['order_num']]['content'][] = array
            (
                array('资金账户抵扣', $info['record_cash']),
                
            );
        }


        if ($type == 1 && $info['source_id'] > 0) {
            if ($info['source_type'] == 2) {
                # 仓库
                $source_info = Dever::db('store/info')->find($info['source_id']);
            } elseif ($info['source_type'] == 3) {
                # 工厂
                $source_info = Dever::db('factory/info')->find($info['source_id']);
            }

            $result[$info['order_num']]['content'][] = array
            (
                array('供应商', $source_info['name']),
                array('联系人', $source_info['truename']),
                array('联系电话', $source_info['mobile']),
            );
        }

        return $parent_order;
    }

    private function show_button($info, $type, $parent_order, $noprice)
    {
        $button = array();
        if ($type == 2) {
            $config = Dever::load('factory/admin/auth.config');
            
            if ($info['status'] < 5) {
                $button[] = array
                (
                    'type' => 'link',
                    'link' => Dever::url('admin/order.print?id=' . $info['id'] . '&type=1', 'factory'),
                    'name' => '打印货单',
                );
            }
            if ($info['status'] == 3) {
                $button[] = array
                (
                    'type' => 'edit',
                    'link' => Dever::url('order_send?id=' . $info['id'], 'factory'),
                    'name' => '配送发货',
                );
                if ($parent_order && (isset($parent_order['uid']) && $parent_order['uid'] || isset($parent_order['mid']) && $parent_order['mid'])) {
                } else {
                    $button[] = array
                    (
                        'type' => 'cancel',
                        'link' => Dever::url('lib/buy.refund_apply_commit?json=1&order_id=' . $info['id'] . '&type_id=' . $info['source_id'], 'mshop'),
                        'name' => '取消订单',
                    );
                }
            }
            $config['phone'] = '您的专属客服:' . $config['kf_name'] . ',联系电话:' . $config['phone'];
            $button[] = array
            (
                'type' => 'alert',
                'content' => $config['phone'],
                'name' => '联系平台',
            );
        } elseif ($type != 1 && $noprice == 1) {
            $config = Dever::load('factory/admin/auth.config');

            $button[] = array
            (
                'type' => 'link',
                'link' => Dever::url('admin/order.print?id=' . $info['id'] . '&type=2', 'store'),
                'name' => '打印货单',
            );

            /*
            if ($info['type'] == 2 && $info['source_type'] != 2 && in_array($info['status'], array(5,6,8))) {
                $button[] = array
                (
                    'type' => 'link',
                    'link' => Dever::url('lib/buy.excel_one?type='.$info['type'].'&type_id='.$info['type_id'].'&id='.$info['id'], 'mshop'),
                    'name' => '导出货单',
                );
            }
            */

            $store_type = Dever::input('store_type');
            if ($info['status'] == 3 && $store_type == 1) {
                $button[] = array
                (
                    'type' => 'edit',
                    'link' => Dever::url('order_send?id=' . $info['id'] . '&type=2', 'store'),
                    'name' => '配送发货',
                );

                if ($parent_order && ((isset($parent_order['uid']) && $parent_order['uid']) || (isset($parent_order['mid']) && $parent_order['mid']))) {
                } else {
                    $button[] = array
                    (
                        'type' => 'cancel',
                        'link' => Dever::url('lib/buy.refund_apply_commit?json=1&order_id=' . $info['id'] . '&type_id=' . $info['source_id'], 'mshop'),
                        'name' => '取消订单',
                    );
                }
            }
            if ($info['status'] == 4 && $store_type != 1 && $info['type'] == 2) {
                $button[] = array
                (
                    'type' => 'action',
                    'link' => Dever::url('admin/factory_order.action_commit?order_id='.$info['id'], 'store'),
                    'name' => '确认收货',
                );
            }
            $config['phone'] = '您的专属客服:' . $config['kf_name'] . ',联系电话:' . $config['phone'];
            $button[] = array
            (
                'type' => 'alert',
                'content' => $config['phone'],
                'name' => '联系平台',
            );
        }

        return $button;
    }

    public function getSelect($source, $source_id, $goods_id)
    {
        if ($goods_id) {
            $name = 'audit';
            $id = 'audit_' . $goods_id;
        } else {
            $name = 'audit_set';
            $id = 'audit';
        }
        $select = '<select class="'.$name.'" id="'.$id.'">';
        foreach ($source as $k => $v) {
            $yes = '';
            if ($source_id && $v['id'] == $source_id) {
                $yes = 'selected';
            }
            $value = $v['type'] . '_' . $v['id'];
            $select .= '<option value="'.$value.'" '.$yes.'>'.$v['name'].'</option>';
        }
        $select .= '</select>';

        return $select;
    }

    private function show_audit($info, &$result)
    {
        $info['type'] = 1;

        $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $info['id'], 'status' => 1));

        $shop = Dever::db('shop/info')->find($info['type_id']);

        list($data, $source) = $this->assign($goods, $info, $shop, true);

        if ($info) {

            $head = array('序号', '商品编号', '商品名称', '供货商', '订货总数量', '商品计量单位', '订货单总金额');
            $body = array();
            $i = 0;
            if ($data) {
                foreach ($data as $k => $v) {
                    foreach ($v as $v1) {
                        $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v1['goods_id'], $v1['sku_id']);
                        if (isset($goods_info['sku'])) {
                            $sku = '[' . $goods_info['sku']['string'] . ']';
                        } else {
                            $sku = '';
                        }
                        $d = array
                        (
                            $i+1,
                            $goods_info['code'],
                            $goods_info['name'] . $sku,
                            $this->getSelect($source, $v1['source_id'], $v1['order_goods_id']),
                            $v1['num'],
                            $goods_info['unit'],
                            $v1['p_price'] * $v1['num'],
                        );

                        $body[] = $d;

                        $i++;
                    }
                }
            }
            
            if ($goods) {
                foreach ($goods as $k => $v) {
                    $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
                    if (isset($goods_info['sku'])) {
                        $sku = '[' . $goods_info['sku']['string'] . ']';
                    } else {
                        $sku = '';
                    }
                    $d = array
                    (
                        $i+1,
                        $goods_info['code'],
                        $goods_info['name'] . $sku,
                        $this->getSelect($source, false, $v['id']),
                        $v['num'],
                        $goods_info['unit'],
                        $v['p_price'] * $v['num'],
                    );

                    $body[] = $d;

                    $i++;
                }
            }

            $btn = array();
            $btn[] = array(
                'type' => 'click',
                'content' => 'setAudit()',
                'name' => '全部调整<script>function setAudit(){layer.confirm(\'确定进行此项操作吗?\', function(){var audit = $(\'.audit_set\').val();$(\'.audit\').each(function(){$(this).val(audit);layui.form.render();layer.closeAll()})})}</script>'
            );
            $result['商品拆单'] = array
            (
                'type' => 'table',
                'head' => array('name' => '供货商:' . $this->getSelect($source, false, false), 'btn' => $btn),
                'content' => array
                (
                    'head' => $head,
                    'body' => $body,
                )
            );

            $url = Dever::url('lib/buy.audit_set_commit?json=1&order_id=' . $info['id'], 'mshop');
            $result['审核结果'] = array
            (
                'type' => 'html',
                'content' => '<script>function saveAudit(){var goods = [];var audit = 1; var audit_text = $(".update_audit_text").val();$(".update_audit").each(function(){if ($(this).get(0).checked){audit = $(this).val()}});$(\'.audit\').each(function(){var v = $(this).val();var id = $(this).attr("id");goods.push(v + "_" + id);});layer.confirm(\'确定进行此项操作吗?\', function(){layui.form.render();var send = {};send.goods = goods.join(",");send.audit = audit;send.audit_text = audit_text;console.info(send);$.post("'.$url.'", send, function(t){t = JSON.parse(t);showYes(t)})})}</script><style>.layui-form-radio{padding-right: 0px;margin: 0px 0px 0 0;margin-left:40px}</style><div class="layui-form-item  show_input"><div classs="layui-col-lg6"><div><label style="font-size:14px;font-weight:bold;" class="">审核状态</label><div style="display:inline" class="am-btn-group"><input update_type="checked" class="checkbox-checkall-0_update_audit update_audit update_value validate[required]" type="radio" name="update_audit[]" value="2" checked="" show_id="audit" autocomplete="off" id="form-validation-field-1"> 审核通过 &nbsp;&nbsp;<input update_type="checked" class="autoload checkbox-checkall-0_update_audit update_audit update_value validate[required]" type="radio" name="update_audit[]" value="3" autocomplete="off" id="form-validation-field-0"> 审核未通过 &nbsp;&nbsp;</div></div></div></div><div class="layui-form-item" style="display: block;"><div classs="layui-col-lg6"><div><label style="font-size:14px;font-weight:bold;" class="">审核备注</label></div><div><textarea style="height:100px;" update_type="value" class="update_value update_audit_text form-control layui-input validate[required]" name="update_desc"></textarea></div></div></div> <div style="text-align:left" class="layui-layer-btn layui-layer-btn-"><a class="layui-btn layui-btn-primary" onclick="saveAudit()">保存</a><a class="layui-layer-btn1" style="display:none">取消</a></div>',
            );
        }
    }

    private function show_refund($info, &$result, $type)
    {
        $tk = Dever::db('shop/buy_order_refund')->find(array('order_id' => $info['id'], 'type' => 1));
        $url = Dever::url('lib/buy.refund_commit?json=1', 'mshop');
        if (!$info['refund_cash']) {
            $info['refund_cash'] = 0;
        }

        if ($info['refund_cash'] > 0 && $tk) {
            
            if ($type == 2) {
                $info['refund_cash'] = $info['refund_p_cash'];
            }
            if ($tk['process'] == 1) {
                $process = '<a href="javascript:;" onclick="audit('.$tk['id'].', 2, \''.$url.'\')" class="layui-btn layui-btn-primary">通过</a><a href="javascript:;" onclick="audit('.$tk['id'].', 3, \''.$url.'\')" class="layui-btn layui-btn-danger">驳回</a>';
            } else {
                $tk_process = Dever::db('shop/buy_order_refund')->config['process'];
                $process = $tk_process[$tk['process']];
            }
            $desc = array();
            $desc['退款原因'] = $tk['desc'];
            $desc['退款图片'] = '暂无';
            if ($tk['pic']) {
                $pic = explode(',', $tk['pic']);
                $tk['pic'] = '';
                foreach ($pic as $k => $v) {
                    $tk['pic'] .= '<a href="'.$v.'" target="_blank"><img src="'.$v.'" width="100"/></a>';
                }
            }
;
            $tk['cdate'] = date('Y-m-d H:i', $tk['cdate']);
            $result['退款信息'] = array
            (
                'type' => 'info',
                'content' => array
                (
                    array
                    (
                        array('退款金额', $info['refund_cash']),
                        array('数量', $info['num']),
                        array('退款进度', $process),
                    ),

                    array
                    (
                        array('申请时间', $tk['cdate']),
                        array('申请原因', $tk['desc']),
                        array('图片', $tk['pic']),
                    ),
                ),
            );
        }
    }

    # 获取配送信息
    private function show_ps($info, &$result)
    {
        $info['ps_info'] = Dever::db('shop/buy_order_ps')->find(array('order_id' => $info['id']));
        if ($info['ps_info']) {
            $info['ps_info']['service'] = Dever::array_decode($info['ps_info']['service']);
            $info['ps_info']['cdate'] = date('Y-m-d H:i', $info['ps_info']['cdate']);
            if ($info['ps_info']['ydate']) {
                $info['ps_info']['ydate'] = date('Y-m-d H:i', $info['ps_info']['ydate']);
            } else {
                $info['ps_info']['ydate'] = '无';
            }

            $status = Dever::db('shop/buy_order_ps')->config['status'];
            $info['ps_info']['status_name'] = $status[$info['ps_info']['status']];
            
            $service = array();
            if ($info['ps_info']['service']) {
                if (isset($info['ps_info']['service']['serivce'])) {
                    $info['ps_info']['service'] = $info['ps_info']['service']['service'];
                }
                foreach ($info['ps_info']['service'] as $k => $v) {
                    if (isset($v['order_num']) && $v['order_num']) {
                        $info['ps_info']['service'][$k]['service_name'] = '供应商自送';
                        if (isset($v['service_id']) && $v['service_id'] > 0) {
                            $service_info = Dever::db('shop/service')->find($v['service_id']);
                            if ($service_info) {
                                $info['ps_info']['service'][$k]['service_name'] = $service_info['name'];
                            }
                        }

                        $service[] = array
                        (
                            array('名称', $info['ps_info']['service'][$k]['service_name']),
                            array('单号', isset($v['order_num']) ? $v['order_num'] : ''),
                        );
                    }
                }
            }

            $result['物流信息'] = array
            (
                'type' => 'info',
                'content' => array
                (
                    array
                    (
                        array('发货时间', $info['ps_info']['cdate']),
                        array('收货时间', $info['ps_info']['ydate']),
                        array('查单', '<a href="https://www.kuaidi100.com/?from=openv" target="_blank">点此手动查单</a>'),
                    ),
                ),
            );
            $result['物流信息']['content'] = array_merge($result['物流信息']['content'], $service);
        }
    }

    # 获取商品清单
    private function show_goods($info, &$result, $type, $noprice)
    {
        $body = array();
        $body_total = array();
        $body_total['price'] = 0;
        $body_total['num'] = 0;
        $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $info['id']));
        $goods_status = Dever::db('shop/buy_order_goods')->config['status'];
        $tk_status = Dever::db('shop/buy_order_refund')->config['status'];

        $refund_body = array();
        $refund_body_total = array();
        $refund_body_total['price'] = 0;
        $refund_body_total['num'] = 0;
        $url = Dever::url('lib/buy.refund_commit?json=1', 'mshop');
        foreach ($goods as $k => $v) {
            if ($type == 2) {
                $v['price'] = $v['p_price'];
            }
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
            $status = $goods_status[$v['status']];

            $tk = Dever::db('shop/buy_order_refund')->find(array('order_id' => $info['id'], 'order_goods_id' => $v['id'], 'type' => 2));
            if ($tk && $tk['process'] == 1) {
                if ($type == 1) {
                    $status = '申请' . $tk_status[$tk['status']];
                } else {
                    $status = '已上报';
                }

                if ($type == 1) {
                    $desc = array();
                    $desc['退款原因'] = $tk['desc'];
                    $desc['退款图片'] = '暂无';
                    if ($tk['pic']) {
                        $desc['退款图片'] = '';
                        $pic = explode(',', $tk['pic']);
                        foreach ($pic as $k1 => $v1) {
                            $desc['退款图片'] .= '<a href="'.$v1.'" target="_blank"><img src="'.$v1.'" width="100"/></a>';
                        }
                    }
                    $status .= '<div style="width:300px"><table><tr><td><a href="javascript:showAlert($(\'#desc_content\').html());">点此查看原因</a><span id="desc_content" style="display:none">'.Dever::table($desc).'</span><td>';

                    $status .= '<td><button href="javascript:;" style="width:80px" onclick="audit('.$tk['id'].', 2, \''.$url.'\')" class="layui-btn layui-btn-primary">通过</button></td><td><button href="javascript:;" onclick="audit('.$tk['id'].', 3, \''.$url.'\')"  style="width:80px" class="layui-btn layui-btn-danger">驳回</button></td></tr></table></div>';
                }
            } elseif ($type > 1 && (!$tk || ($tk && $tk['process'] == 3))) {

                //$tui = Dever::url('lib/buy.refund_apply_info_one_commit?json=1', 'mshop');
                if ($type == 2) {
                    $tui = Dever::url('order_tui?order_goods_id=' . $v['id'] . '&order_id=' . $info['id'] . '&type=13&type_id=' . $info['source_id'], 'factory');
                } else {
                    if ($info['source_type'] == 3) {
                        $tui = Dever::url('order_tui?order_goods_id=' . $v['id'] . '&order_id=' . $info['id'] . '&type=13&type_id=' . $info['source_id'], 'store');
                    } else {
                        $tui = Dever::url('order_tui?order_goods_id=' . $v['id'] . '&order_id=' . $info['id'] . '&type=12&type_id=' . $info['source_id'], 'store');
                    }
                    
                }

                $info = $this->refund_button($info);
                if ($info['refund_button'] == 1) {
                    if ($info['status'] == 3) {
                        $status = '<a href="javascript:;" onclick="fastEdit($(this), \''.$tui.'\', \'缺货退款\', \'\', 1)" class="layui-btn">缺货退款</a>';
                    } elseif ($info['status'] == 4) {
                        $status = '<a href="javascript:;" onclick="fastEdit($(this), \''.$tui.'\', \'报损退款\', \'\', 1)" class="layui-btn">报损退款</a>';
                    }
                }
            }

            if (isset($goods_info['sku'])) {
                $sku = '[' . $goods_info['sku']['string'] . ']';
            } else {
                $sku = '';
            }

            $d = array
            (
                'pic' => $goods_info['cover'],
                'name' => $goods_info['name'],
                'sku' => $sku,
                'price' => $v['price'],
                'num' => $v['num'] . $goods_info['unit'],
                'status' => $status,
            );

            if ($goods_info['price_type'] > 2) {
                $d['goods'] = $goods_info['goods'];
            }

            if ($tk && $v['status'] == 3 && $tk['status'] != 3) {
                $d['status'] = $tk_status[$tk['status']];
                if ($noprice == 1) {
                    unset($d['price']);
                }
                $refund_body[] = $d;
                $price = $v['price']*$v['num'];
                $refund_body_total['price'] += $price;
                $refund_body_total['num'] += $v['num'];
            } else {
                if ($noprice == 1) {
                    unset($d['price']);
                }
                $body[] = $d;
                $price = $v['price']*$v['num'];
                $body_total['price'] += $price;
                $body_total['num'] += $v['num'];
            }
        }

        if ($body) {

            if ($refund_body_total['price']) {
                $body_total['set_price'] = $body_total['price'] - $refund_body_total['price'];
            }
            if ($refund_body_total['num']) {
                $body_total['set_num'] = $body_total['num'] - $refund_body_total['num'];
            }

            if ($noprice == 1) {
                unset($body_total['price']);
                unset($body_total['set_price']);
            }
            
            $result['商品清单'] = array
            (
                'type' => 'list',
                'content' => $body,
                'total' => $body_total,
            );
        }

        if ($refund_body) {

            if ($noprice == 1) {
                unset($refund_body_total['price']);
            }

            $result['缺货与报损商品'] = array
            (
                'type' => 'list',
                'content' => $refund_body,
                'total' => $refund_body_total,
            );
        }
    }

    # 获取对账清单
    private function show_dz($info, &$result, $noprice)
    {
        $cash_type = Dever::input('cash', 1);
        $search_option_type = Dever::input('search_option_type');
        if ($cash_type == 1) {
            if ($search_option_type == 1) {
                # 门店结算单
                $cash_order = Dever::db('cash/order')->select(array('type' => $info['type'], 'type_id' => $info['type_id'], 'source_order_id' => $info['id']));

                $col = 'cash';

            } elseif ($search_option_type == 2) {
                # 工厂结算单
                $cash_order = Dever::db('cash/order')->select(array('source_type' => $info['source_type'], 'source_id' => $info['source_id'], 'source_order_id' => $info['id']));

                $col = 'p_cash';
            } elseif ($search_option_type == 3) {
                # 仓库结算单
                $cash_order = Dever::db('cash/order')->select(array('source_type' => $info['source_type'], 'source_id' => $info['source_id'], 'source_order_id' => $info['id']));

                $col = 'num';
            }
        }
        

        if (isset($cash_order) && $cash_order) {
            $head = array('序号', '结算单号', '数量', '金额', '结算类型', '入账状态', '审核状态', '结算时间', '审核备注', '管理');

            if ($search_option_type == 3 || $noprice == 1) {
                unset($head[3]);
            }

            $body = array();
            $config = Dever::db('cash/order')->config;
            foreach ($cash_order as $k => $v) {
                $cdate = date('Y-m-d H:i', $v['cdate']);
                $fdate = $v['fdate'] ? date('Y-m-d H:i', $v['fdate']) : '';
                $operdate = $v['operdate'] ? date('Y-m-d H:i', $v['operdate']) : '';
                $cash = $v[$col];

                $url = Dever::url('project/database/list?project=shop&table=buy_order_goods&order_id='.$v['source_order_id'].'&page_type=1', 'manage');
                $v['source_order_num'] = '<a href="'.$url.'" style="color:blue">'.$v['source_order_num'].'</a>';

                $m = '';
                if ($v['audit'] == 1 && $v['audit_type'] == 2) {
                    $url = Dever::url('project/database/update?project=cash&table=order&where_id='.$v['id'].'&col=audit,desc', 'manage');
                    $m = '<a href="javascript:;" onclick="fastEdit($(this), \''.$url.'\', \'审核\', \'\', 1)" class="layui-btn">审核</a>';
                }

                $d = array
                (
                    $k+1,
                    $v['order_num'],
                    $v['num'],
                    $cash,
                    $config['config_jstype'][$v['jstype']],
                    $config['config_status'][$v['status']],
                    $config['config_audit'][$v['audit']],
                    $operdate,
                    $v['desc'],
                    $m,
                );

                if ($search_option_type == 3 || $noprice == 1) {
                    unset($d[3]);
                }
                $body[] = $d;
            }

            $result['对账清单'] = array
            (
                'type' => 'table',
                'content' => array
                (
                    'head' => $head,
                    'body' => $body,
                )
            );
        }
    }

    # 发货
    /*
    public function send_commit()
    {
        $order_id = Dever::input('order_id');
        $order = Dever::db('shop/buy_order')->find($order_id);

        if (!$order || ($order && $order['status'] != 3)) {
            Dever::alert('当前订单状态无法发货');
        }

        $state = Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'status' => 4));

        if ($state) {
            $this->updatePs($order, 1);
        }

        return 'reload';
    }*/

    # 采购订单审核 拆单
    /*
    public function audit_commit()
    {
        $order_id = Dever::input('order_id');
        $order = Dever::db('shop/buy_order')->find($order_id);

        if (!$order || ($order && $order['status'] != 2)) {
            Dever::alert('当前订单状态无法拆单');
        }

        if ($order['type'] != 1) {
            Dever::alert('这不是门店的订单');
        }

        $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $order_id));

        $shop = Dever::db('shop/info')->find($order['type_id']);

        # 获取门店分配的仓库和工厂
        $shop_store = Dever::db('shop/store')->select(array('shop_id' => $shop['id']));
        $store = array();
        $distance = array();

        # 按照距离排序
        if ($shop_store) {
            foreach ($shop_store as $k => $v) {
                $info = Dever::db('store/info')->find($v['store_id']);
                if ($info && $info['status'] == 1) {
                    $distance[] = $info['distance'] = Dever::distance($shop['lng'], $shop['lat'], $info['lng'], $info['lat']);
                    $store[] = $info;
                }
            }

            if ($store) {
                array_multisort($distance, SORT_ASC, SORT_NUMERIC, $store);
            }
        }

        $shop_factory = Dever::db('shop/factory')->select(array('shop_id' => $shop['id']));
        $factory = array();
        $distance = array();

        # 按照距离排序
        if ($shop_factory) {
            foreach ($shop_factory as $k => $v) {
                $info = Dever::db('factory/info')->find($v['factory_id']);
                if ($info && $info['status'] == 1) {
                    $distance[] = $info['distance'] = Dever::distance($shop['lng'], $shop['lat'], $info['lng'], $info['lat']);
                    $factory[] = $info;
                }
            }


            if ($factory) {
                array_multisort($distance, SORT_ASC, SORT_NUMERIC, $factory);
            }
        }

        if (!$factory && !$store) {
            Dever::alert('未分配仓库或者未分配工厂');
        }

        $this->order_num = 0;
        $this->order_id = array();
        $delete = array();
        $yes = array();
        
        foreach ($goods as $k => $v) {
            # 开始找仓库
            $find = $this->store($order['id'], $order['order_num'] . '_' . $this->order_num, $shop, $store, $v);
            if (!$find[1]) {
                # 仓库没有,找厂家
                if ($factory) {
                    $find = $this->factory($order['id'], $order['order_num'] . '_' . $this->order_num, $shop, $factory, $v);
                }
            }

            if ($find[1]) {
                $delete[$v['id']] = $v;
            } else {
                $yes[$v['id']] = $v;
            }
        }

        $num = count($this->order_id);
        if ($num > 0) {
            if ($num == 1) {
                $key = array_keys($this->order_id);
                $key = $key[0];
                Dever::db('shop/buy_order')->delete($key);
                $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $key));

                $p_price = 0;
                foreach ($goods as $k => $v) {
                    $goods_info = Dever::db('shop/buy_order_goods')->find(array('order_id' => $order['id'], 'goods_id' => $v['goods_id']));

                    if ($goods_info) {

                        Dever::db('shop/buy_order_goods')->update(array('where_id' => $goods_info['id'], 'set_p_price' => $v['p_price']));
                        $p_price += $v['p_price'];
                    }
                }

                Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'status' => 3, 'source_type' => $this->order_id[$key][0], 'source_id' =>  $this->order_id[$key][1], 'p_price' => $p_price, 'operdate' => time()));

                Dever::db('shop/buy_order_goods')->delete(array('order_id' => $key));

                $this->order_id[$order['id']] = array($this->order_id[$key][0], $this->order_id[$key][1]);
                unset($this->order_id[$key]);

            } else {
                if (!$yes) {
                    Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'state' => 2));
                    Dever::load('cash/lib/order')->up($order, 1, 3);
                } else {
                    $price = 0;
                    $num = 0;
                    foreach ($delete as $k => $v) {
                        Dever::db('shop/buy_order_goods')->delete(array('id' => $v['id']));
                        $price += $v['price'];
                        $num += $v['num'];
                    }

                    $order['price'] = $order['price'] - $price;
                    $order['num'] = $order['num'] - $num;
                    Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'price' => $order['price'], 'num' => $order['num']));
                    Dever::load('shop/lib/refund')->set('buy')->apply(1, $shop['id'], $order_id, false, 3, 0, '供货商库存不足');
                    Dever::load('cash/lib/order')->up($order, 1, 3);
                }
            }
        } else {
            # 没有找到,退款
            Dever::alert('供货商库存不足,请联系供货商备货');
            //Dever::load('shop/lib/refund')->set('buy')->apply(1, $shop['id'], $order_id, false, 3, 0, '供货商库存不足');
        }

        if ($this->order_id) {
            foreach ($this->order_id as $k => $v) {
                $this->sendMsg($v[0], $v[1], $k);

                if ($k != $order['id']) {
                    $order_info = Dever::db('shop/buy_order')->find($k);
                    Dever::load('cash/lib/order')->up($order_info, 1, 1);
                }
            }
        }

        return 'ok';
    }
    */
    # 采购订单审核 手动拆单
    public function audit_set_commit_api()
    {
        Dever::config('base')->hook = true;
        //{goods: "2_4_audit_615,2_4_audit_614,-1_-1_audit_617,-1_-1_audit_616,-1_-1_audit_613", audit: "1", audit_text: "1231"}

        $id = Dever::input('order_id');
        $goods = Dever::input('goods');
        $audit = Dever::input('audit');
        $audit_text = Dever::input('audit_text');

        $info = Dever::db('shop/buy_order')->one($id);
        if ($audit > 1 && $info && $info['status'] == 2) {

            $shop = Dever::db('shop/info')->find($info['type_id']);

            if ($audit == 2 && $goods) {
                Dever::db('shop/buy_order')->update(array('where_id' => $info['id'], 'audit' => $audit, 'audit_desc' => $audit_text));
                # 成功
                if (strstr($info['order_num'], '_')) {
                    $temp = explode('_', $info['order_num']);
                    $info['order_num'] = $temp[0];
                    $info['order_index'] = $temp[1];
                } else {
                    $info['order_index'] = 0;
                }
                $goods = explode(',', $goods);
                $data = $other = array();
                foreach ($goods as $k => $v) {
                    list($source_type, $source_id, $name, $goods_id) = explode('_', $v);
                    $gv = Dever::db('shop/buy_order_goods')->find($goods_id);
                    if ($source_id > 0) {
                        $key = $source_type . '_' . $source_id;
                        $data[$key][] = array
                        (
                            'area' => $shop['area'],
                            'order_id' => $info['id'],
                            'order_type' => 1,
                            'order_num' => $info['order_num'],
                            'order_index' => $info['order_index'],
                            'type' => 1,
                            'type_id' => $shop['id'],
                            'source_type' => $source_type,
                            'source_id' => $source_id,
                            'order_goods_id' => $gv['id'],
                            'goods_id' => $gv['goods_id'],
                            'sku_id' => $gv['sku_id'],
                            'price' => $gv['price'],
                            'p_price' => $gv['price'],
                            'num' => $gv['num'],
                        );
                    } else {
                        $other[] = $gv;
                    }
                }

                $this->audit_action($data, $other, $info, $shop, 1);
            } else {
                
                # 退款
                if ($goods) {
                    Dever::db('shop/buy_order')->update(array('where_id' => $info['id'], 'audit' => $audit, 'audit_desc' => $audit_text));

                    $shop = Dever::db('shop/info')->find($info['type_id']);
                    Dever::load('shop/lib/refund')->set('buy')->apply(1, $shop['id'], $id, false, 3, 0, '未通过审核');
                } else {
                    Dever::db('shop/buy_order')->update(array('where_id' => $info['id'], 'audit' => $audit, 'audit_desc' => $audit_text, 'status' => 7));
                }
            }
        }

        return Dever::url('project/database/list&project=shop&table=buy_order&menu=shop&search_option_state=1&search_option_type=1&menu_id=84', 'manage');
    }

    # 采购订单审核 拆单
    public function audit_commit()
    {
        $order_id = Dever::input('order_id');
        $order = Dever::db('shop/buy_order')->find($order_id);

        if (!$order || ($order && $order['status'] != 2)) {
            Dever::alert('当前订单状态无法拆单');
        }

        if ($order['type'] != 1) {
            Dever::alert('这不是门店的订单');
        }

        $order['type'] = 1;

        $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $order['id']));

        $shop = Dever::db('shop/info')->find($order['type_id']);

        $data = $this->assign($goods, $order, $shop);
        
        $this->audit_action($data, $goods, $order, $shop);

        return 'ok';
    }

    private function audit_action($data, $goods, $order, $shop, $state = 2)
    {
        $send = array();

        if ($data) {
            # 开始生成订单
            $num = count($data);
            if (!$goods && $num == 1) {
                foreach ($data as $k => $v) {
                    $k = explode('_', $k);

                    $p_price = 0;
                    foreach ($v as $k1 => $v1) {
                        Dever::db('shop/buy_order_goods')->update(array('where_id' => $v1['order_goods_id'], 'set_p_price' => $v1['p_price']));
                        $p_price += ($v1['p_price'] * $v1['num']);
                        $send[$order['id']] = $v1;
                    }
                    Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'status' => 3, 'source_type' => $k[0], 'source_id' =>  $k[1], 'p_price' => $p_price, 'operdate' => time()));
                }
            } elseif ($num >= 1) {
                $i = $order['order_index'];
                $price = 0;
                $num = 0;
                foreach ($data as $k => $v) {
                    foreach ($v as $k1 => $v1) {
                        $v1['order_num'] .= '_' . $i;

                        $state = $this->createOrder($v1);
                        $send[$state] = $v1;

                        Dever::db('shop/buy_order_goods')->delete(array('id' => $v1['order_goods_id'], 'clear' => true));
                        $price += ($v1['price'] * $v1['num']);
                        $num += $v1['num'];
                    }
                    $i++;
                }

                $price = $order['price'] - $price;
                $num = $order['num'] - $num;
                if ($num >= 0) {
                    Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'price' => $price, 'num' => $num, 'audit' => 1, 'order_num' => $order['order_num'] . '_' . $i, 'clear' => true));
                } else {
                    Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'state' => 2));
                    Dever::load('cash/lib/order')->up($order, 1, 3);
                }
            }
        } else {
            Dever::db('shop/buy_order')->update(array('where_id' => $order['id'], 'audit' => 1));
            if ($state == 1) {
                Dever::alert('未选择供货商,该订单进入重新审核状态');
            } else {
                Dever::alert('供货商库存不足,请联系供货商备货,该订单进入重新审核状态');
            }
            
        }

        if ($send) {
            foreach ($send as $k => $v) {
                $this->sendMsg($v['source_type'], $v['source_id'], $k);

                if ($k != $order['id']) {
                    $order_info = Dever::db('shop/buy_order')->find(array('id' => $k, 'clear' => true));
                    Dever::load('cash/lib/order')->up($order_info, 1, 1);
                }
            }
        }

        if ($goods) {
            $send = array();
            foreach ($goods as $k => $v) {
                $send[$v['order_id']] = $v;
            }

            if ($send) {
                foreach ($send as $k => $v) {
                    $order_info = Dever::db('shop/buy_order')->find(array('id' => $k, 'clear' => true));
                    Dever::load('cash/lib/order')->up($order_info, 1, 1);
                }
            }
        }
    }

    public function assign(&$goods, &$order, $shop, $state = false)
    {
        if (strstr($order['order_num'], '_')) {
            $temp = explode('_', $order['order_num']);
            $order['order_num'] = $temp[0];
            $order['order_index'] = $temp[1];
        } else {
            $order['order_index'] = 0;
        }
        # 获取门店分配的仓库和工厂
        $data = $source = array();

        $source[] = array
        (
            'type' => -1,
            'id' => -1,
            'name' => '未分配供货商',
        );

        $this->assign_store($data, $goods, $source, $order, $shop);
        $this->assign_factory($data, $goods, $source, $order, $shop);

        if ($state) {
            return array($data, $source);
        }

        return $data;
    }

    private function assign_store(&$data, &$goods, &$source, $order, $shop)
    {
        $shop_store = Dever::db('shop/store')->select(array('shop_id' => $shop['id']));
        $store = array();
        $distance = array();

        # 按照距离排序
        if ($shop_store) {
            foreach ($shop_store as $k => $v) {
                $info = Dever::db('store/info')->find($v['store_id']);
                if ($info && $info['status'] == 1) {
                    $distance[] = $info['distance'] = Dever::distance($shop['lng'], $shop['lat'], $info['lng'], $info['lat']);
                    $store[] = $info;
                }
            }

            if ($store) {
                array_multisort($distance, SORT_ASC, SORT_NUMERIC, $store);

                foreach ($store as $k => $v) {
                    $store[$k]['type'] = 2;
                    $source[] = $store[$k];
                    if ($goods) {
                        foreach ($goods as $gk => $gv) {
                            $where = array();
                            $where['store_id'] = $v['id'];
                            $where['goods_id'] = $gv['goods_id'];
                            $where['sku_id'] = ($gv['sku_id'] && $gv['sku_id'] > 0) ? $gv['sku_id'] : -1;
                            $sku = Dever::db('store/goods_sku')->getOne($where);
                            if ($sku) {
                                if ($gv['num'] <= $sku['total']) {
                                    # 库存符合
                                    $data['2_' . $v['id']][] = array
                                    (
                                        'area' => $shop['area'],
                                        'order_id' => $order['id'],
                                        'order_type' => $order['type'],
                                        'order_num' => $order['order_num'],
                                        'order_index' => $order['order_index'],
                                        'type' => 1,
                                        'type_id' => $shop['id'],
                                        'source_type' => 2,
                                        'source_id' => $v['id'],
                                        'source_name' => $v['name'],
                                        'order_goods_id' => $gv['id'],
                                        'goods_id' => $where['goods_id'],
                                        'sku_id' => $where['sku_id'],
                                        'price' => $gv['price'],
                                        'p_price' => $gv['price'],
                                        'num' => $gv['num'],
                                    );
                                    unset($goods[$gk]);
                                }
                            }
                        }
                    }
                }
            }
            return $store;
        }
        return false;
    }

    private function assign_factory(&$data, &$goods, &$source, $order, $shop)
    {
        $shop_factory = Dever::db('shop/factory')->select(array('shop_id' => $shop['id']));
        $factory = array();
        $distance = array();

        # 按照距离排序
        if ($shop_factory && $goods) {
            foreach ($shop_factory as $k => $v) {
                $info = Dever::db('factory/info')->find($v['factory_id']);
                if ($info && $info['status'] == 1) {
                    $distance[] = $info['distance'] = Dever::distance($shop['lng'], $shop['lat'], $info['lng'], $info['lat']);
                    $factory[] = $info;
                }
            }

            if ($factory) {
                array_multisort($distance, SORT_ASC, SORT_NUMERIC, $factory);

                foreach ($factory as $k => $v) {
                    $factory[$k]['type'] = 3;
                    $source[] = $factory[$k];
                    if ($goods) {
                        foreach ($goods as $gk => $gv) {
                            $where = array();
                            $where['factory_id'] = $v['id'];
                            $where['goods_id'] = $gv['goods_id'];
                            $where['sku_id'] = ($gv['sku_id'] && $gv['sku_id'] > 0) ? $gv['sku_id'] : -1;
                            $sku = Dever::db('factory/goods_sku')->getOne($where);
                            if ($sku) {
                                $data['3_' . $v['id']][] = array
                                (
                                    'area' => $shop['area'],
                                    'order_id' => $order['id'],
                                    'order_type' => $order['type'],
                                    'order_num' => $order['order_num'],
                                    'order_index' => $order['order_index'],
                                    'type' => 1,
                                    'type_id' => $shop['id'],
                                    'source_type' => 3,
                                    'source_id' => $v['id'],
                                    'source_name' => $v['name'],
                                    'order_goods_id' => $gv['id'],
                                    'goods_id' => $where['goods_id'],
                                    'sku_id' => $where['sku_id'],
                                    'price' => $gv['price'],
                                    'p_price' => $sku['p_price'],
                                    'num' => $gv['num'],
                                );
                                unset($goods[$gk]);
                            }
                        }
                    }
                }
            }
            return $factory;
        }

        return false;
    }

    /*
    private function store($order_id, $order_num, $shop, $store, $goods, $state = 2)
    {
        $find = array();
        $type_id = array();
        $id = array();
        if (!$store) {
            return array(2, $type_id, $id);
        }
        foreach ($store as $k => $v) {
            $where['store_id'] = $v['id'];
            $where['goods_id'] = $goods['goods_id'];
            $where['sku_id'] = ($goods['sku_id'] && $goods['sku_id'] > 0) ? $goods['sku_id'] : -1;
            $sku = Dever::db('store/goods_sku')->getOne($where);

            if ($sku) {
                if ($goods['num'] <= $sku['total']) {
                    # 如果库存符合,直接下单即可,生成仓库订单
                    $state = $this->createOrder($order_id, $order_num, 1, $shop['id'], 2, $where['store_id'], $goods['price'], $goods['price'], $goods['num'], $where['goods_id'], $where['sku_id']);
                    if ($state) {
                        $type_id[] = $where['store_id'];
                        $id[] = $state;
                        $this->order_id[$state] = array(2, $where['store_id']);
                        break;
                    }
                } elseif ($state == 1 && $sku['total'] > 0) {
                    # 如果库存不够,从这个仓库扣下一部分,剩余的从另外仓库处理
                    $goods['num'] = $goods['num'] - $sku['total'];
                    # 生成仓库订单
                    $state = $this->createOrder($order_id, $order_num, 1, $shop['id'], 2, $where['store_id'], $goods['price'], $goods['price'], $sku['total'], $where['goods_id'], $where['sku_id']);
                    if (!$state) {
                        $goods['num'] = $goods['num'] + $sku['total'];
                    } else {
                        $type_id[] = $where['store_id'];
                        $id[] = $state;
                        $this->order_id[$state] = array(2, $where['store_id']);
                    }
                    continue;

                } else {
                    # 直接切换到下一个仓库处理
                    continue;
                }
            }
        }

        return array(2, $type_id, $id);
    }

    private function factory($order_id, $order_num, $shop, $factory, $goods)
    {
        $find = array();
        $type_id = array();
        $id = array();
        if (!$factory) {
            return array(3, $type_id, $id);
        }

        foreach ($factory as $k => $v) {
            $where['factory_id'] = $v['id'];
            $where['goods_id'] = $goods['goods_id'];
            $where['sku_id'] = ($goods['sku_id'] && $goods['sku_id'] > 0) ? $goods['sku_id'] : -1;
            $sku = Dever::db('factory/goods_sku')->getOne($where);

            if ($sku && $sku['p_price'] > 0) {
                $state = $this->createOrder($order_id, $order_num, 1, $shop['id'], 3, $where['factory_id'], $goods['price'], $sku['p_price'], $goods['num'], $where['goods_id'], $where['sku_id']);
                if ($state) {
                    $type_id[] = $where['factory_id'];
                    $id[] = $state;
                    $this->order_id[$state] = array(3, $where['factory_id']);
                    break;
                }
            } else {
                continue;
            }
        }

        return array(3, $type_id, $id);
    }
    */

    # 发送消息
    public function sendMsg($source_type, $source_id, $id)
    {
        if (Dever::project('message')) {
            $msg_param['type'] = 1;//消息类型1是订单消息
            $msg_param['id'] = $id;
            $msg_param['source_id'] = $source_id;
            $msg_param['source_type'] = $source_type;
            $msg_param = Dever::json_encode($msg_param);
            $project = $source_type + 1;
            $msg = '您有一个新的订货单,请及时处理。';
            Dever::load('message/lib/data')->push(-1, $source_id, '订货通知', $msg, 2, $project, false, $msg_param);
        }
    }

    # 生成拆单的订单
    /*
    private function createOrder($order_id, $order_num, $type, $type_id, $source_type, $source_id, $price, $p_price, $num, $goods_id, $sku_id)
    {
        $where['parent_order_id'] = $order_id;
        $where['type'] = $type;
        $where['type_id'] = $type_id;
        $where['source_type'] = $source_type;
        $where['source_id'] = $source_id;
        $where['r'] = $goods_id . '_' . microtime() . '_' . mt_rand(1, 10000);
        $info = Dever::db('shop/buy_order')->find($where);
        if (!$info) {
            $this->order_num++;
            $data = $where;
            $data['name'] = $order_id;
            $data['order_num'] = $order_num;
            $data['operdate'] = time();
            $data['status'] = 3;
            $data['price'] = $price * $num;
            $data['p_price'] = $p_price * $num;
            $data['num'] = $num;
            $data['refund_cash'] = 0;
            $data['refund_p_cash'] = 0;
            $id = $state = Dever::db('shop/buy_order')->insert($data);
        } else {
            $id = $info['id'];

            $data['where_id'] = $id;
            $data['price'] = $info['price'] + ($price * $num);
            $data['p_price'] = $info['p_price'] + ($p_price * $num);
            $data['num'] = $info['num'] + $num;
            $state = Dever::db('shop/buy_order')->update($data);
        }

        if ($state && $id > 0) {
            $goods_info = Dever::db('shop/buy_order_goods')->find(array('order_id' => $id));
            if (!$goods_info) {
                $goods['order_id'] = $id;
                $goods['goods_id'] = $goods_id;
                $goods['sku_id'] = $sku_id;
                $goods['price'] = $price;
                $goods['p_price'] = $p_price;
                $goods['num'] = $num;
                Dever::db('shop/buy_order_goods')->insert($goods);
            }

            $state = $this->updateSell($source_type, $source_id, $goods_id, $sku_id, $num);

            return $id;
        }

        return false;
    }
    */
    public function createOrder($data, $order_cdate = false)
    {
        $where['parent_type'] = $data['order_type'];
        $where['parent_order_id'] = $data['order_id'];
        $where['type'] = $data['type'];
        $where['type_id'] = $data['type_id'];
        $where['source_type'] = $data['source_type'];
        $where['source_id'] = $data['source_id'];
        $where['clear'] = true;
        $info = Dever::db('shop/buy_order')->find($where);

        $goods_info = array();
        $goods['goods_id'] = $data['goods_id'];
        $goods['sku_id'] = $data['sku_id'];
        $goods['clear'] = true;

        if (!$info) {
            $insert = $where;
            if (isset($data['area'])) {
                $insert['area'] = $data['area'] . ',' . $where['type_id'];
            }
            $insert['name'] = $data['order_id'];
            $insert['order_num'] = $data['order_num'];
            $insert['operdate'] = time();
            $insert['status'] = 3;
            $insert['price'] = $data['price'] * $data['num'];
            $insert['p_price'] = $data['p_price'] * $data['num'];
            $insert['num'] = $data['num'];
            $insert['refund_cash'] = 0;
            $insert['refund_p_cash'] = 0;
            if ($order_cdate) {
                $insert['cdate'] = $order_cdate;
            }
            $id = $state = Dever::db('shop/buy_order')->insert($insert);
            if ($id) {
                $goods['order_id'] = $id;
                $goods_info = Dever::db('shop/buy_order_goods')->find($goods);
            }
            
        } else {
            $id = $info['id'];
            $goods['order_id'] = $id;
            $goods_info = Dever::db('shop/buy_order_goods')->find($goods);
            $state = false;
            if (!$goods_info) {
                $update['where_id'] = $id;
                $update['price'] = $info['price'] + ($data['price'] * $data['num']);
                $update['p_price'] = $info['p_price'] + ($data['p_price'] * $data['num']);
                $update['num'] = $info['num'] + $data['num'];
                $state = Dever::db('shop/buy_order')->update($update);
            }
        }

        if ($state && $id > 0 && !$goods_info) {
            $goods['price'] = $data['price'];
            $goods['p_price'] = $data['p_price'];
            $goods['num'] = $data['num'];
            Dever::db('shop/buy_order_goods')->insert($goods);

            $state = $this->updateSell($data['source_type'], $data['source_id'], $data['goods_id'], $data['sku_id'], $data['num']);

            return $id;
        }

        return false;
    }

    # 减少库存,增加销量
    public function updateSell($source_type, $source_id, $goods_id, $sku_id, $num)
    {
        if ($source_type == 2) {
            $data['store_id'] = $source_id;
            $data['goods_id'] = $goods_id;
            $data['sku_id'] = $sku_id;
            $data['num'] = $num;
            return Dever::load('store/lib/goods')->oper($source_id, 1, 2, array($data));
        } else {
            $up = array();
            $up['where_factory_id'] = $source_id;
            $up['where_goods_id'] = $goods_id;
            $up['sell_num'] = $num;
            $state = Dever::db('factory/goods')->incSell($up);

            if ($state) {
                if ($sku_id > 0) {
                    
                } else {
                    $sku_id = -1;
                }
                $upSku = $up;
                $upSku['where_sku_id'] = $sku_id;
                $state = Dever::db('factory/goods_sku')->incSell($upSku);
            }

            return $state;
        }
    }

    # 打印订单单
    public function printer($user)
    {
        $id = Dever::input('id');
        $type = Dever::input('type', 1);

        $factory_config = Dever::db('main/factory_config')->find();
        $main_config = Dever::db('main/config')->find();

        $config = Dever::db('shop/buy_order')->config;

        $info = Dever::db('shop/buy_order')->one($id);

        //$source_info = Dever::db('factory/info')->find($info['source_id']);
        if ($type == 2) {
            # 仓库
            $member = Dever::db('store/member')->find($user['id']);
            $name = '仓库名称';
        } else {
            # 工厂
            $member = Dever::db('factory/member')->find($user['id']);
            $name = '工厂名称';
        }

        if ($info['type'] == 1) {
            $type_info = Dever::db('shop/info')->find($info['type_id']);
        } elseif ($info['type'] == 2) {
            $type_info = Dever::db('store/info')->find($info['type_id']);
        } elseif ($info['type'] == 3) {
            $type_info = Dever::db('factory/info')->find($info['type_id']);
        }

        if ($info['source_type'] == 1) {
            $source_info = Dever::db('shop/info')->find($info['source_id']);
        } elseif ($info['source_type'] == 2) {
            $source_info = Dever::db('store/info')->find($info['source_id']);
        } elseif ($info['source_type'] == 3) {
            $source_info = Dever::db('factory/info')->find($info['source_id']);
        }

        $cdate = date('Y-m-d H:i', $info['cdate']);
        if ($info['operdate']) {
            $operdate = date('Y-m-d H:i', $info['operdate']);
        } else {
            $operdate = '';
        }

        if ($info['fdate']) {
            $fdate = date('Y-m-d H:i', $info['fdate']);
        } else {
            $fdate = '';
        }

        $status = $config['status'][$info['status']];

        $info['ps_info'] = Dever::db('shop/buy_order_ps')->find(array('order_id' => $info['id']));
        if ($info['ps_info']) {
            $info['ps_info']['service'] = Dever::array_decode($info['ps_info']['service']);
            $info['ps_info']['cdate'] = date('Y-m-d H:i', $info['ps_info']['cdate']);
            if ($info['ps_info']['ydate']) {
                $info['ps_info']['ydate'] = date('Y-m-d H:i', $info['ps_info']['ydate']);
            } else {
                $info['ps_info']['ydate'] = '无';
            }

            $ps_status = Dever::db('shop/buy_order_ps')->config['status'];
            $info['ps_info']['status_name'] = $status[$info['ps_info']['status']];
        }

        $pdf = Dever::load('pdf/lib/base')->init();

        $pdf->hr('-', $main_config['name']);

        $pdf->br()->font(20)->center('订货单号:' . $info['order_num']);
        $pdf->font(10);
        $pdf->br();

        if ($type == 2 && $info['type'] == 2 && $info['source_type'] != 2) {
            $pdf->br()->left($name . ':' . $type_info['name'], 80)->left('制单人:' . $member['name'], 60)->left('制单时间:' . date('Y-m-d H:i'), 40);

            $pdf->hr();

            $pdf->br()->left('订单状态:' . $status, 140)->left('订货时间:' . $operdate, 40);

            $pdf->hr();

            if (!$info['ps_info']) {
                $pdf->left('发货供应商:' . $source_info['name']);
            } else {
                //$pdf->br()->left('发货供应商:' . $source_info['name'], 140)->left('发货时间:' . $info['ps_info']['cdate'], 40);

                $pdf->br()->left('发货供应商:' . $source_info['name'], 80)->left('发货时间:' . $info['ps_info']['cdate'], 60)->left('收货时间:' . $info['ps_info']['ydate'], 40);
            }
            
            if ($info['ps_info'] && $info['ps_info']['service']) {
                if (isset($info['ps_info']['service']['serivce'])) {
                    $info['ps_info']['service'] = $info['ps_info']['service']['service'];
                }
                foreach ($info['ps_info']['service'] as $k => $v) {
                    if (isset($v['order_num']) && $v['order_num']) {
                        $info['ps_info']['service'][$k]['service_name'] = '供应商自送';
                        if (isset($v['service_id']) && $v['service_id'] > 0) {
                            $service = Dever::db('shop/service')->find($v['service_id']);
                            if ($service) {
                                $info['ps_info']['service'][$k]['service_name'] = $service['name'];
                            }
                            
                        }

                        $pdf->br()->left('物流信息:' . $info['ps_info']['service'][$k]['service_name'], 80)->left('物流单号:' . $info['ps_info']['service'][$k]['order_num'], 40);
                    }
                }
            }

            $pdf->hr();

        } else {
            $pdf->br()->left($name . ':' . $source_info['name'], 80)->left('制单人:' . $member['name'], 60)->left('制单时间:' . date('Y-m-d H:i'), 40);

            $pdf->hr();

            $pdf->br()->left('订单状态:' . $status, 80)->left('订货时间:' . $operdate, 80);

            $pdf->hr();
            
            $parent_order = array();
            if ($info['parent_type'] == 2) {
                $parent_order = Dever::db('shop/sell_order')->find($info['parent_order_id']);
            } elseif ($info['parent_type'] == 3) {
                $parent_order = Dever::db('agent/dh_order')->find($info['parent_order_id']);
            }
            if ($parent_order && isset($parent_order['uid']) && $parent_order['uid']) {
                if ($parent_order['address_id']) {
                    $address = Dever::load('passport/address')->getOne($parent_order['uid'], $parent_order['address_id']);

                    $pdf->br()->left('收件人:' . $address['contact'], 80)->left('收件人手机:' . $address['mobile'], 80);

                    $pdf->left('收件地址:' . $address['address_info'] . ',' . $address['house_number']);

                } else {
                    $user = Dever::db('passport/user')->find($parent_order['uid']);

                    $pdf->br()->left('收件人:' . $user['username'], 80)->left('收件人手机:' . $user['mobile'], 80);
                }
            } elseif ($parent_order && isset($parent_order['mid']) && $parent_order['mid']) {
                if ($parent_order['address_id']) {
                    $address = Dever::load('agent/address')->getOne($parent_order['mid'], $parent_order['address_id']);

                    $pdf->br()->left('收件人:' . $address['contact'], 80)->left('收件人手机:' . $address['mobile'], 80);

                    $pdf->left('收件地址:' . $address['address_info'] . ',' . $address['house_number']);

                } else {
                    $user = Dever::db('agent/member')->find($parent_order['mid']);

                    $pdf->br()->left('收件人:' . $user['name'], 80)->left('收件人手机:' . $user['mobile'], 80);
                }
            } else {
                $pdf->br()->left('配送至:' . $type_info['name'], 80)->left('联系方式:' . $type_info['truename'] . ',' . $type_info['mobile'], 80);

                $pdf->left('配送地址:' . $type_info['address']);
            }

            $pdf->hr();

            if ($info['ps_info'] && $info['ps_info']['service']) {
                if (isset($info['ps_info']['service']['serivce'])) {
                    $info['ps_info']['service'] = $info['ps_info']['service']['service'];
                }
                $pdf->br()->left('发货时间:' . $info['ps_info']['cdate'], 80)->left('收货时间:' . $info['ps_info']['ydate'], 80);

                foreach ($info['ps_info']['service'] as $k => $v) {
                    if (isset($v['order_num']) && $v['order_num']) {
                        $info['ps_info']['service'][$k]['service_name'] = '供应商自送';
                        if (isset($v['service_id']) && $v['service_id'] > 0) {
                            $service = Dever::db('shop/service')->find($v['service_id']);
                            if ($service) {
                                $info['ps_info']['service'][$k]['service_name'] = $service['name'];
                            }
                            
                        }

                        $pdf->br()->left('物流信息:' . $info['ps_info']['service'][$k]['service_name'], 80)->left('物流单号:' . $info['ps_info']['service'][$k]['order_num'], 80);
                    }
                }
                /*
                $pdf->br()->left('发货时间:' . $info['ps_info']['cdate'], 80)->left('配货员:' . $info['ps_info']['phy'], 70)->left('打包员:' . $info['ps_info']['dby'], 40);

                if ($info['ps_info']['zl'] && $info['ps_info']['tj']) {
                    $pdf->br()->left('包裹重量:' . $info['ps_info']['zl'] . '克', 80)->left('包裹体积:' . $info['ps_info']['tj'] . '立方厘米', 70)->left('包裹数量:' . $info['ps_info']['num'], 40);
                } elseif (!$info['ps_info']['zl'] && $info['ps_info']['tj']) {
                    $pdf->br()->left('包裹体积:' . $info['ps_info']['tj'] . '立方厘米', 150)->left('包裹数量:' . $info['ps_info']['num'], 40);
                } elseif ($info['ps_info']['zl'] && !$info['ps_info']['tj']) {
                    $pdf->br()->left('包裹重量:' . $info['ps_info']['zl'] . '克', 150)->left('包裹数量:' . $info['ps_info']['num'], 40);
                } else {
                    $pdf->left('包裹数量:' . $info['ps_info']['num']);
                }

                $pdf->br()->left('物流信息:' . $info['ps_info']['service_name'], 40);

                if ($info['ps_info']['order_num']) {
                    $pdf->left('物流单号:' . $info['ps_info']['order_num'], 70);
                }

                if ($info['ps_info']['ydate']) {
                    $pdf->left('到货确认时间:' . $info['ps_info']['ydate']);
                }
                */

                $pdf->hr();
            }
        }

        $body = array();
        $body_total = array();
        $body_total['price'] = 0;
        $body_total['num'] = 0;
        $goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $info['id']));
        $goods_status = Dever::db('shop/buy_order_goods')->config['status'];

        $refund_body = array();
        $refund_body_total = array();
        $refund_body_total['price'] = 0;
        $refund_body_total['num'] = 0;
        foreach ($goods as $k => $v) {
            if ($type == 1) {
                $v['price'] = $v['p_price'];
            }
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
            $status = $goods_status[$v['status']];

            $tk = Dever::db('shop/buy_order_refund')->find(array('order_id' => $info['id'], 'order_goods_id' => $v['id'], 'type' => 2));

            if (isset($goods_info['sku'])) {
                $sku = $goods_info['sku']['string'];
            } else {
                $sku = '无';
            }

            if ($goods_info['price_type'] > 2 && isset($goods_info['goods']) && is_array($goods_info['goods'])) {
                    
                foreach ($goods_info['goods'] as $v2) {
                    $p = $v2['price'];
                    if (is_numeric($v2['num']) && is_numeric($v2['price'])) {
                        $p = $v2['price']*$v2['num'];
                    }
                    $d = array
                    (
                        $v2['id'],
                        $v2['name'],
                        $sku,
                        $v2['price'],
                        'x ' . $v2['num'],
                    );
                    if ($type == 2) {
                        unset($d[3]);
                    }
                    if ($tk && $v['status'] == 3 && $tk['status'] != 3) {

                        $refund_body[] = $d;
                        $price = $v['price']*$v['num'];
                        $refund_body_total['price'] += $price;
                        $refund_body_total['num'] += $v['num'];
                    } else {
                        $body[] = $d;
                        $price = $v['price']*$v['num'];
                        $body_total['price'] += $price;
                        $body_total['num'] += $v['num'];
                    }
                }
            } else {
                $d = array
                (
                    $goods_info['id'],
                    $goods_info['name'],
                    $sku,
                    $v['price'],
                    'x ' . $v['num'],
                );
                if ($type == 2) {
                    unset($d[3]);
                }
                if ($tk && $v['status'] == 3 && $tk['status'] != 3) {

                    $refund_body[] = $d;
                    $price = $v['price']*$v['num'];
                    $refund_body_total['price'] += $price;
                    $refund_body_total['num'] += $v['num'];
                } else {
                    $body[] = $d;
                    $price = $v['price']*$v['num'];
                    $body_total['price'] += $price;
                    $body_total['num'] += $v['num'];
                }
            }
        }

        $head = array(array('商品编号', 40), array('商品名称', 60), array('商品属性', 40), array('单价', 40), array('数量', 20));
        if ($type == 2) {
            unset($head[3]);
            $head[1][1] = 70;
            $head[2][1] = 60;
        }
        if ($body) {
            $pdf->center('订单商品');
            $pdf->br();
            foreach ($head as $k => $v) {
                $pdf->left($v[0], $v[1]);
            }

            foreach ($body as $k => $v) {
                $pdf->br();
                foreach ($head as $k1 => $v1) {
                    $pdf->left($v[$k1], $v1[1]);
                }
            }
            $pdf->br();
            if ($type == 2) {
                $pdf->right('共'.$body_total['num'].'件商品');
            } else {
                $pdf->right('共'.$body_total['num'].'件商品,合计金额¥' . $body_total['price'] . '元');
            }
            
            $pdf->hr();
        }

        if ($refund_body) {
            $pdf->center('缺货与报损商品');
            $pdf->br();
            foreach ($head as $k => $v) {
                $pdf->left($v[0], $v[1]);
            }

            foreach ($refund_body as $k => $v) {
                $pdf->br();
                foreach ($head as $k1 => $v1) {
                    $pdf->left($v[$k1], $v1[1]);
                }
            }
            $pdf->br();
            if ($type == 2) {
                $pdf->right('共'.$refund_body_total['num'].'件商品');
            } else {
                $pdf->right('共'.$refund_body_total['num'].'件商品,合计金额¥' . $refund_body_total['price'] . '元');
            }
            
            $pdf->hr();
            
        }
        $pdf->br(1);
        
        $pdf->right('如遇任何问题请致电客服');
        $pdf->br();

        $pdf->font(20);
        $pdf->left($main_config['name'], 160);

        $pdf->font(10);
        $pdf->right('电话:' . $factory_config['phone'], 30);

        $pdf->br();

        $pdf->left($main_config['site'], 160);

        $pdf->font(10);
        $pdf->right($main_config['worktime'], 30);

        $pdf->out('订货单');
    }

    # 导出单个订单
    public function excel_one_api()
    {
        $this->type = Dever::input('type');
        $id = Dever::input('id');
        $type_id = Dever::input('type_id');
        $data = $this->getView($type_id, $id);
        $this->excel(array($data));
    }

    # 导出订单
    public function excel($data)
    {
        if (!$data) {
            Dever::alert('无导出数据');
        }
        $file = '入库订单';
        $type = Dever::input('search_option_type', $this->type);

        $header = array('所属仓库', '订单号', '商品来源', '发货日期', '商品名称', '商品规格属性', '商品数量', '报损退款状态', '订单状态');

        $table = 'store/info';
        if ($type == 1) {
            $header[0] = '所属门店';
            $table = 'shop/info';
        }

        $body = array();
        foreach ($data as $k => $v) {
            if (!is_array($v)) {
                continue;
            }
            foreach ($v['goods'] as $k1 => $v1) {

                $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v1['goods_id'], $v1['sku_id']);
                if (isset($goods_info['sku'])) {
                    $sku = $goods_info['sku']['string'];
                } else {
                    $sku = '';
                }

                if ($goods_info['price_type'] > 2 && isset($goods_info['goods']) && is_array($goods_info['goods'])) {
                    
                    foreach ($goods_info['goods'] as $v2) {
                        $d = array
                        (
                            $v['type_info']['name'],
                            $v['order_num'],
                            $v['source_info']['name'],
                            $v['cdate'],
                            $v2['name'],
                            $sku,
                            $v2['num'],
                            $v1['status_name'],
                            $v['status_name'],
                        );

                        $body[] = $d;
                    }
                } else {
                    $d = array
                    (
                        $v['type_info']['name'],
                        $v['order_num'],
                        $v['source_info']['name'],
                        $v['cdate'],
                        $goods_info['name'],
                        $sku,
                        $v1['num'],
                        $v1['status_name'],
                        $v['status_name'],
                    );

                    $body[] = $d;
                }
            }
        }

        Dever::excelExport($body, $header, $file);
    }
}