<?php

# 支付

namespace Card\Lib;

use Dever;

class Buy
{
    # 1是列表，2是详情
    public $view = 1;
    # 获取配置
    public $config = array();
    # table
    public $table = 'card/order';

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

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

        return $this;
    }


    # 获取公共的where
    public function where($id)
    {
        if (!$id) {
            Dever::alert('参数错误');
        }
        $where = array();
        $where['uid'] = $id;

        return $where;
    }

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

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

        $result['search_value'] = $where;
        $result['search_value']['day'] = $day = Dever::input('day');
        if ($day) {
            $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) {
            $where['start'] = Dever::maketime($start);
            $where['end'] = Dever::maketime($end);
        }

        $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'] = $this->config['status'];

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

        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);

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

        return $result;
    }

    # 获取订单详细信息
    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' => 5));
                $info['status'] = 5;
            } else {
                $info['time'] = $m - $info['time'];
            }
        }

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

        $info['card'] = Dever::db('card/order_card')->select(array('order_id' => $info['id']));
        
        $info['cdate'] = date('Y-m-d H:i', $info['cdate']);

        foreach ($info['card'] as $k => $v) {
            $info['card'][$k]['info'] = Dever::db('card/info')->find($v['card_id']);
            $info['card'][$k]['type'] = Dever::db('card/type')->find($info['card'][$k]['info']['type_id']);
        }

        # 配送信息
        $info['ps_info'] = Dever::db('card/order_ps')->find(array('order_id' => $info['id']));
        if ($info['ps_info']) {
            $info['ps_info']['service_name'] = '平台配送';
            $info['ps_info']['cdate'] = date('Y-m-d H:i', $info['ps_info']['cdate']);
            if ($info['ps_info']['qu_date']) {
                $info['ps_info']['qu_date'] = date('Y-m-d H:i', $info['ps_info']['qu_date']);
            }
            if ($info['ps_info']['qs_date']) {
                $info['ps_info']['qs_date'] = date('Y-m-d H:i', $info['ps_info']['qs_date']);
            }

            $status = Dever::db('card/order_ps')->config['status'];
            $info['ps_info']['status_name'] = $status[$info['ps_info']['status']];
            
            if ($info['ps_info']['service_id'] > 0) {
                $service = Dever::db('shop/service')->find($info['ps_info']['service_id']);
                $info['ps_info']['service_name'] = $service['name'];
            }
        }

        if ($info['address_id']) {
            $info['address'] = Dever::db('passport/address')->find($info['address_id']);
        }

        return $info;
    }

    public function getCard(&$data)
    {
        $card_id = Dever::input('card_id');
        if (!$card_id) {
            Dever::alert('请传入礼品卡');
        }
        $card_id = explode(',', $card_id);
        
        $num = Dever::input('num');
        if (!$num) {
            Dever::alert('请传入数量');
        }
        $num = explode(',', $num);

        $city = Dever::input('city');
        if (!$city) {
            Dever::alert('请传入城市');
        }
        $city = explode(',', $city);

        $data['price'] = 0;
        $data['num'] = 0;
        $data['name'] = array();
        $data['type'] = $data['list'] = array();

        # 计算总价格
        foreach ($card_id as $k => $v) {
            $c = isset($city[$k]) ? $city[$k] : -1;
            $n = isset($num[$k]) && $num[$k] >= 0 ? $num[$k] : 1;
            $info = Dever::db('card/info')->find($v);
            if (!$info) {
                continue;
            }
            $type = Dever::db('card/type')->find($info['type_id']);
            if (!isset($data['type'][$info['type_id']])) {
                $data['type'][$info['type_id']] = $type;
            }
            $data['type'][$info['type_id']]['list'][$k] = $info;
            $data['type'][$info['type_id']]['list'][$k]['buy_num'] = $n;
            $data['type'][$info['type_id']]['list'][$k]['city'] = $c;

            $data['list'][$k] = $info;
            $data['list'][$k]['buy_num'] = $n;
            $data['list'][$k]['city'] = $c;
            $data['num'] += $n;
            $data['price'] += $data['list'][$k]['price'] * $n;
            $data['name'][] = $data['list'][$k]['name'];
        }

        $data['name'] = implode(',', $data['name']);

        $config = Dever::db('main/sell_config')->find();
        $data['card_name'] = $config['card_name'];
    }

    # 发起支付
    public function pay($user, $shop, $name, $num, $card, $price, $address_id, $system_source = 5, $refer = '')
    {
        if (!$user) {
            Dever::alert('错误的用户信息');
        }

        $uid = $user['id'];

        if ($uid > 0) {
            $wechat = Dever::db('passport/wechat')->one(array('uid' => $uid, 'type' => 1, 'system_id' => 1));

            if (!$wechat) {
                Dever::alert('错误的用户信息');
            }
        }
        
        $order_data['shop_id'] = $shop['id'];
        $order_data['uid'] = $uid;
        $order_data['mobile'] = $user['mobile'];
        $order_data['address_id'] = $address_id;
        $order_data['name'] = $name;
        $order_data['num'] = $num;
        $order_data['price'] = $price;

        $order_data['order_num'] = $this->getOrderId();
        $id = Dever::db('card/order')->insert($order_data);

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

        foreach($card as $k => $v) {
            $data['uid'] = $uid;
            $data['order_id'] = $id;
            $data['card_id'] = $v['id'];
            $data['city'] = $v['city'];
            $data['price'] = $v['price'];
            $data['num'] = $v['buy_num'];

            Dever::db('card/order_card')->insert($data);
        }

        $sell_config = Dever::db('main/sell_config')->one();

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

        if ($uid > 0 && isset($wechat) && $wechat) {
            $param['openid'] = $wechat['openid'];
        }

        $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 rpay($id, $system_source = 5, $refer = '')
    {
        $order = Dever::db('card/order')->find($id);

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

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

        $param = array
        (
            'project_id' => 3,
            'channel_id' => 1,
            'system_source' => $system_source,
            'uid' => $order['uid'],
            'name' => $order['price'],
            '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('card/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 'card_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('card/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('card/order')->update($update);

            # 生成卡号，从现有的卡池里获取，如果没有则要生成
            Dever::load('card/lib/code')->assign($order['id']);
        }

        return 'ok';
    }

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

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

        if ($data) {
            $update['where_id'] = $data['id'];
            $update['status'] = $status;
            if ($status == 2) {
                $update['qu_date'] = time();
            }
            if ($status == 3) {
                $update['qs_date'] = time();
            }
            
            $state = Dever::db('card/order_ps')->update($update);
        }
    }

    # 确认收货
    public function finish($id, $order_id)
    {
        $data = $this->getView($id, $order_id, false);
        if ($data['status'] <= 3) {
            $status = 4;
            $state = Dever::db('card/order')->update(array('where_id' => $data['id'], 'status' => $status, 'fdate' => time()));
            if ($state) {
                $this->updatePs($data, 3);
            }

            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('card/order')->update(array('where_id' => $data['id'], 'status' => 5, 'operdate' => time()));

            /*
            # 退款涉及到了这些
            $order_card = Dever::db('card/order_card')->select(array('order_id' => $data['id']));

            if ($order_card) {
                foreach ($order_card as $k => $v) {
                    Dever::db('card/order_card')->update(array('where_id' => $v['id'], 'status' => 3));
                }
            }

            $order_code = Dever::db('card/code')->select(array('order_id' => $data['id'], 'status' => 2));

            if ($order_code) {
                foreach ($order_code as $k => $v) {
                    Dever::db('card/code')->update(array('where_id' => $v['id'], 'status' => 1, 'uid' => '0', 'order_id' => '', 'order_card_id' => '', 'bdate' => ''));
                }
            }
            */
            return 'ok';
        } else {
            Dever::alert('当前订单状态不允许取消');
        }
    }

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

        $info = Dever::db('card/order')->one($id);
        
        $status = $config['status'][$info['status']];

        return $status;
    }

    # 收货
    public function send()
    {
        $order_id = Dever::input('order_id');
        $order = Dever::db('card/order')->find($order_id);

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

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

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

        return 'reload';
    }

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

        $config = Dever::db('card/order')->config;

        $info = Dever::db('card/order')->one($id);

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

        $user = Dever::db('passport/user')->find($info['uid']);

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

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

        if (!$user) {
            $user['username'] = '无';
        }
        if (!isset($user['truename'])) {
            $user['truename'] = $user['username'];
        }

        $time = array();
        $time[] = array('下单时间', $cdate);

        if ($opertime) {
            $time[] = array('操作时间', $opertime);
        }

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

        $result = array();

        $result[$info['order_num']] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array('下单用户', $user['username']),
                    array('联系电话', $info['mobile']),
                    array('订单状态', $status),
                ),

                $time,
            )
        );

        if ($info['address_id'] > 0) {
            $address = Dever::load('passport/address')->getOne($info['uid'], $info['address_id']);

            if ($address) {

                $result['收货地址'] = array
                (
                    'type' => 'info',
                    'content' => array
                    (
                        array
                        (
                            array('联系人', $address['contact']),
                            array('联系电话', $address['mobile']),
                        ),

                        array
                        (
                            array('收货地址', $address['address']),
                            array('门牌号', $address['house_number']),
                        ),
                    ),
                );
            }
        }

        $info['ps_info'] = Dever::db('card/order_ps')->find(array('order_id' => $info['id']));
        if ($info['ps_info']) {
            $info['ps_info']['service_name'] = '平台配送';
            $info['ps_info']['cdate'] = date('Y-m-d H:i', $info['ps_info']['cdate']);
            if ($info['ps_info']['qu_date']) {
                $info['ps_info']['qu_date'] = date('Y-m-d H:i', $info['ps_info']['qu_date']);
            } else {
                $info['ps_info']['qu_date'] = '无';
            }

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

            $status = Dever::db('card/order_ps')->config['status'];
            $info['ps_info']['status_name'] = $status[$info['ps_info']['status']];
            
            if ($info['ps_info']['service_id'] > 0) {
                $service = Dever::db('shop/service')->find($info['ps_info']['service_id']);
                $info['ps_info']['service_name'] = $service['name'];
            }

            $info['ps_info']['order_num'] = str_replace("\r\n", ',', $info['ps_info']['order_num']);

            $info['ps_info']['order_num'] .= '（<a href="https://www.kuaidi100.com/?from=openv" target="_blank">点此手动查单）</a>';
            $result['物流信息'] = array
            (
                'type' => 'info',
                'content' => array
                (
                    array
                    (
                        array('名称', $info['ps_info']['service_name']),
                        array('单号', $info['ps_info']['order_num']),
                        array('费用', $info['ps_info']['price']),
                    ),

                    array
                    (
                        array('发货时间', $info['ps_info']['cdate']),
                        array('取件时间', $info['ps_info']['qu_date']),
                        array('签收时间', $info['ps_info']['qs_date']),
                    ),
                ),
            );
        }

        $body = array();
        $body_total = array();
        $body_total['price'] = 0;
        $body_total['num'] = 0;

        $order_card = Dever::db('card/order_card')->select(array('order_id' => $info['id']));
        $order_card_status = Dever::db('card/order_card')->config['status'];

        foreach ($order_card as $k => $v) {
            $card = Dever::db('card/info')->find($v['card_id']);
            $card_type = Dever::db('card/type')->find($card['type_id']);
            $status = $order_card_status[$v['status']];

            $d = array
            (
                'name' => $card_type['name'] . ' / ' . $card['name'],
                'sku' => $v['cards'],
                'price' => $v['price'],
                'num' => $v['num'],
                'status' => $status,
            );

            $body[] = $d;
            $price = $v['price']*$v['num'];
            $body_total['price'] += $price;
            $body_total['num'] += $v['num'];
        }

        if ($body) {
            $result['礼品卡清单'] = array
            (
                'type' => 'list',
                'content' => $body,
                'total' => $body_total,
            );
        }

        $button = array();
        if ($info['status'] == 2) {
            $url = Dever::load('manage/database')->url('edit', $info['id'], 'order_ps&where_id='.$info['id'].'&search_option_order_id='.$info['id'].'&oper_save_jump=order&oper_table=order&oper_parent=order');
            $button[] = array
            (
                'type' => 'edit',
                'link' => $url,
                'name' => '发货',
            );
        } elseif ($info['status'] == 3) {
            $button[] = array
            (
                'type' => 'action',
                'link' => Dever::url('lib/manage.send?order_id=' . $info['id'], 'card'),
                'name' => '确认收货',
            );
        }

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

        return $html;
    }
}