<?php namespace Place_order\Lib\Source;
use Dever;
use Place;
class Order
{
    # 获取订单信息
    public function getInfo($info, $view = false)
    {
        if ($info['status'] == 1) {
            $m = 3600;
            # 支付倒计时
            $info['time'] = time() - $info['cdate'];
            if ($info['time'] >= $m) {
                # 已过期，自动取消
                $info['time'] = -1;
                $this->cancel($info);
                $info['status'] = 9;
            } else {
                $info['time'] = $m - $info['time'];
            }
        }
        $info['scash'] = $info['cash'];
        $info['cash'] = $info['cash'];
        $info['detail'] = $this->getDetail($info['id']);
        $info['info'] = '共' . intval($info['num']) . '件商品';
        if ($view) {
            $this->getView($info);
        }
        return $info;
    }

    # 获取订单里每个商品
    public function getDetail($id)
    {
        $result = Dever::db('source_detail', 'place_order')->select(array('order_id' => $id), array('col' => 'id,name,pic,sku_name,sku_id,cash,num'));
        if ($result) {
            foreach ($result as &$v) {
                $v['cash'] = Dever::load('price', 'place')->getText($v['cash'], 3);
            }
        }
        return $result;
    }

    # 获取订单详情
    public function getView(&$info)
    {
        # 收货地址
        $info['address'] = Dever::load('address', 'place')->getInfo($info['address_id'], $info['uid']);
        # 运费
        $info['yun'] = Dever::load('price', 'place')->getText(0, 3);
        if (in_array($info['status'], array(3,4,5))) {
            $info = Dever::load('express', 'goods')->getInfo($info, $info['address_id']);
            $info['status_name'] = Dever::db('order', 'goods')->value('status', $info['status']);
        }
        $info['status_list'] = array
        (
            1 => array
            (
                'selected' => false,
                'name' => '待付款',
                'time' => $info['cdate_str'],
            ),
            2 => array
            (
                'selected' => false,
                'name' => '待发货',
                'time' => $info['pdate_str'] ?? '',
            ),
            3 => array
            (
                'selected' => false,
                'name' => '待签收',
                'time' => $info['ddate_str'] ?? '',
            ),
            4 => array
            (
                'selected' => false,
                'name' => '待收货',
                'time' => $info['qdate_str'] ?? '',
            ),
            5 => array
            (
                'selected' => false,
                'name' => '已完成',
                'time' => $info['fdate_str'] ?? '',
            ),
        );
        foreach ($info['status_list'] as $k => &$status_list) {
            if ($info['status'] >= $k) {
                $status_list['selected'] = true;
            }
        }
        if ($info['status'] == 1) {
            $info['status_msg'] = '下单成功，待支付';
        } elseif ($info['status'] == 2) {
            $info['status_msg'] = '支付成功，待发货';
        } elseif ($info['status'] == 3) {
            $info['status_msg'] = '配送中，等待签收';
        } elseif ($info['status'] == 4) {
            $info['status_msg'] = '已签收，等待确认';
        } elseif ($info['status'] == 5 || $info['status'] == 6) {
            $info['status_msg'] = '订单已完成';
        } elseif ($info['status'] > 6) {
            $info['status_msg'] = '订单已取消';
        }
        
        $info['refund'] = false;
        $info['refund_list'] = Dever::db('order_refund', 'goods')->select(array('order_id' => $info['id']));
        if ($info['refund_list']) {
            foreach ($info['refund_list'] as $k => $v) {
                if ($v['status'] < 4) {
                    $info['refund'] = $v;
                }
            }
        }
        if ($info['refund']) {
            if ($info['refund']['status'] > 2) {
                $info['refund'] = Dever::load('express', 'goods')->getInfo($info['refund'], $info['address_id'], 2);
            }
            $info['refund']['cdate_str'] = date('Y-m-d H:i:s', $info['refund']['cdate']);
            if (isset($info['refund']['sdate']) && $info['refund']['sdate']) {
                $info['refund']['sdate_str'] = date('Y-m-d H:i:s', $info['refund']['sdate']);
            }
            if (isset($info['refund']['ddate']) && $info['refund']['ddate']) {
                $info['refund']['ddate_str'] = date('Y-m-d H:i:s', $info['refund']['ddate']);
            }
            if (isset($info['refund']['fdate']) && $info['refund']['fdate']) {
                $info['refund']['fdate_str'] = date('Y-m-d H:i:s', $info['refund']['fdate']);
            }
            if ($info['refund']['type'] == 1) {
                $info['refund_status_list'] = array
                (
                    1 => array
                    (
                        'selected' => false,
                        'name' => '退货退款',
                        'time' => $info['refund']['cdate_str'],
                    ),
                    2 => array
                    (
                        'selected' => false,
                        'name' => '已审核',
                        'time' => $info['refund']['sdate_str'] ?? '',
                    ),
                    3 => array
                    (
                        'selected' => false,
                        'name' => '买家已发货',
                        'time' => $info['refund']['ddate_str'] ?? '',
                    ),
                    4 => array
                    (
                        'selected' => false,
                        'name' => '已完成',
                        'time' => $info['refund']['fdate_str'] ?? '',
                    ),
                );
            }
            if ($info['refund']['type'] == 2) {
                $info['refund_status_list'] = array
                (
                    1 => array
                    (
                        'selected' => false,
                        'name' => '仅退款',
                        'time' => $info['cdate_str'],
                    ),
                    2 => array
                    (
                        'selected' => false,
                        'name' => '已审核',
                        'time' => $info['sdate_str'] ?? '',
                    ),
                    4 => array
                    (
                        'selected' => false,
                        'name' => '已完成',
                        'time' => $info['fdate_str'] ?? '',
                    ),
                );
            }
            foreach ($info['refund_status_list'] as $k => $v) {
                if ($info['refund']['status'] >= $k) {
                    $info['refund_status_list'][$k]['selected'] = true;
                }
            }
        }
    }

    # 取消订单
    public function cancel($order, $status = 9)
    {
        if ($order['status'] == 1) {
            $state = Dever::db('order', 'goods')->update($order['id'], array('status' => $status, 'fdate' => time()));
            if ($state) {
                # 恢复库存
                $this->resell($order['id']);
            }
            return 'ok';
        }
    }

    # 支付成功
    public function success($order, $status)
    {
        if ($status == 1) {
            $update['status'] = 2;
            $msg = '支付成功';
            
        } else {
            $update['status'] = 7;
            $msg = '支付失败';
        }
        $update['pdate'] = time();
        $state = Dever::db('order', 'goods')->update($order['id'], $update);
        Dever::load('log', 'goods')->up(1, $order['uid'], $data['order_id'], $msg);
        if ($state && $update['status'] == 7) {
            # 恢复库存
            $this->resell($order['id']);
        }
        return $state;
    }

    # 确认收货
    public function finish_commit(){}
    public function finish($type = 1, $order)
    {
        if ($order['status'] >= 3 && $order['status'] <= 6) {
            if ($type == 1) {
                $uid = $order['uid'];
            } else {
                $uid = '';
            }
            # 检查有没有退款
            $refund = Dever::db('order_refund', 'goods')->find(array('order_id' => $order['id'], 'refund_status' => 1));
            $status = 5;
            if ($refund) {
                $status = 6;
            }
            Dever::db('order', 'goods')->update($order['id'], array('status' => $status, 'fdate' => time()));
            Dever::load('log', 'goods')->up($type, $uid, $order['id'], '确认收货，订单完成');
        }
    }

    # 恢复库存
    public function resell($id)
    {
        $result = Dever::db('order_detail', 'goods')->select(array('order_id' => $id));
        if ($result) {
            foreach ($result as $v) {
                $state = Dever::load('stock', 'goods')->sell($v['info_id'], $v['sku_id'], $v['num']*-1);
            }
        }  
    }

    # 后台详情页
    public function showManageView($page)
    {
        # 这里获取基本信息
        $db = Dever::db('order', 'goods');
        $address = Dever::load('address', 'place')->getInfo($page->info['address_id'], $page->info['uid']);
        $user = Dever::db('member', 'place')->find($page->info['uid']);
        $desc = '';
        $status = $db->value('status', $page->info);
        if ($page->info['info']) {
            $desc = '备注：' . $page->info['info'];
        }
        $timeline = array();
        $page->info['cdate_str'] = date('Y-m-d H:i:s', $page->info['cdate']);
        if (isset($page->info['pdate']) && $page->info['pdate']) {
            $page->info['pdate_str'] = date('Y-m-d H:i:s', $page->info['pdate']);
        }
        if (isset($page->info['ddate']) && $page->info['ddate']) {
            $page->info['ddate_str'] = date('Y-m-d H:i:s', $page->info['ddate']);
        }
        if (isset($page->info['qdate']) && $page->info['qdate']) {
            $page->info['qdate_str'] = date('Y-m-d H:i:s', $page->info['qdate']);
        }
        if (isset($page->info['fdate']) && $page->info['fdate']) {
            $page->info['fdate_str'] = date('Y-m-d H:i:s', $page->info['fdate']);
        }
        $this->getView($page->info);

        foreach ($page->info['status_list'] as $k => $v) {
            $v['name'] = '['.$v['name'].']';
            if ($k == 1) {
                $v['name'] .= ' 下单人：' . $user['name'] . '（'.$user['mobile'].'）' . ' 付款：' . $page->info['cash'] . '元 '. $desc;
            } elseif ($k == 2) {
                $v['name'] .= ' 收货地址：' . $address['full'];
            } elseif ($k == 3) {
                if (isset($page->info['express'])) {
                    $v['name'] .= ' 已发货：' . $page->info['express']['name'] . ',' . $page->info['express']['number'];
                }
            } elseif ($k == 4) {
                if (isset($page->info['express']['log'][0])) {
                    $v['name'] .= ' ' . $page->info['express']['log'][0]['status'];
                }
            } elseif ($k == 5 && $page->info['status'] > 6) {
                $v['name'] .= ' 订单'.$status.'';
            }
            if ($v['selected']) {
                $v['hollow'] = true;
                $v['color'] = '#0bbd87';
                $v['type'] = 'primary';
                $v['size'] = 'large';
            }
            $timeline[] = $v;
        }

        $button = array();

        if ($page->info['status'] == 2) {
            $button[] = array
            (
                'name' => '修改收货信息',
                'type' => 'fastedit',
                'path' => 'sector_place_order/goods_order_address',
                'row' => array
                (
                    'id' => $page->info['id'],
                ),
            );
            $button[] = array
            (
                'name' => '发货',
                # fastedit、fastadd、oper、api、link、route
                'type' => 'fastadd',
                'path' => 'sector_place_order/goods_order_express',
                'row' => array
                (
                    'id' => $page->info['id'],
                ),
                'param' => array
                (
                    'order_id' => $page->info['id'],
                ),
            );
        } elseif ($page->info['status'] == 3 && isset($express)) {
            $button[] = array
            (
                'name' => '修改快递单号',
                # fastedit、fastadd、oper、api、link、route
                'type' => 'fastedit',
                'path' => 'sector_place_order/goods_order_express',
                'row' => array
                (
                    'id' => $express['id'],
                ),
                'param' => array
                (
                    'order_id' => $page->info['id'],
                ),
            );
        }
        if (!$page->info['refund'] && $page->info['status'] >= 2 && $page->info['status'] < 7) {
            $button[] = array
            (
                'name' => '退款',
                'type' => 'fastadd',
                'path' => 'sector_place_order/goods_order_refund',
                'row' => array
                (
                    'id' => $page->info['id'],
                ),
                'param' => array
                (
                    'order_id' => $page->info['id'],
                ),
            );
        }
        $desc = '';
        if ($page->info['refund']) {
            $desc = '[退款中]';
            $refund = array();
            foreach ($page->info['refund_status_list'] as $k => $v) {
                $v['name'] = '['.$v['name'].']';
                if ($k == 1) {
                    $v['name'] .= ' 申请原因：' . Dever::db('order_refund', 'goods')->value('desc_type', $page->info['refund']['desc_type']) . ' 申请说明：' . $page->info['refund']['desc'];
                } elseif ($k == 2) {
                    $v['name'] .= ' 审核备注：' . $page->info['refund']['audit_desc'];
                } elseif ($k == 3) {
                    if (isset($page->info['refund']['express'])) {
                        $v['name'] .= ' 已发货：' . $page->info['refund']['express']['name'] . ',' . $page->info['refund']['express']['number'];
                    }
                }
                if ($v['selected']) {
                    $v['hollow'] = true;
                    $v['color'] = 'red';
                    $v['type'] = 'primary';
                    $v['size'] = 'large';
                }
                $refund[] = $v;
            }
            $content[] = array
            (
                'name' => '退款进度',
                'type' => 'timeline',
                'content' => $refund,
            );
            $button = array();
            if ($page->info['refund']['status'] == 1) {
                $button[] = array
                (
                    'name' => '退款审核',
                    'type' => 'fastedit',
                    'path' => 'sector_place_order/goods_order_refund_audit',
                    'row' => array
                    (
                        'id' => $page->info['refund']['id'],
                    ),
                    'param' => array
                    (
                        'order_id' => $page->info['id'],
                    ),
                );
            }
        }

        $content[] = array
        (
            'name' => '订单进度' . $desc,
            'type' => 'timeline',
            'content' => $timeline,
        );

        $info[] = array
        (
            # 类型，desc描述 table表格，表格有head和body即可
            'type' => 'desc',
            'name' => $page->info['order_num'],
            # 每行展示数量
            'column' => 1,
            # 是否有边框
            'border' => true,
            # 排列方向：horizontal横向 vertical纵向
            'direction' => 'horizontal',
            # 右侧按钮
            'button' => $button,
            # 具体内容
            'content' => $content,
        );

        $detail = Dever::db('order_detail', 'goods')->select(array('order_id' => $page->info['id']));
        if ($detail) {
            foreach ($detail as &$v) {
                $v['status'] = '正常';
            }
        }

        $log = Dever::load('log', 'goods')->getList($page->info['id']);
        
        $tab = array
        (
            'active' => 't1',
            'content' => array
            (
                't1' => array
                (
                    'name' => '商品清单',
                    'type' => 'table',
                    'border' => true,
                    #'height' => '200',
                    'head' => array
                    (
                        array
                        (
                            'key' => 'name',
                            'name' => '名称',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'sku_name',
                            'name' => '规格',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'cash',
                            'name' => '金额',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'num',
                            'name' => '数量',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'status',
                            'name' => '状态',
                            'fixed' => 'fixed',
                        ),
                    ),
                    'button' => array(),
                    'body' => $detail,
                ),

                't2' => array
                (
                    'name' => '操作记录',
                    'type' => 'table',
                    'border' => true,
                    #'height' => '200',
                    'head' => array
                    (
                        array
                        (
                            'key' => 'type',
                            'name' => '身份',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'name',
                            'name' => '名称',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'mobile',
                            'name' => '联系电话',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'desc',
                            'name' => '详情',
                            'fixed' => 'fixed',
                        ),
                        array
                        (
                            'key' => 'cdate_str',
                            'name' => '时间',
                            'fixed' => 'fixed',
                        ),
                    ),
                    'button' => array(),
                    'body' => $log,
                ),
            )
        );
        
        return array('info' => $info, 'tab' => $tab);
    }
}