<?php namespace Seller\Lib;
use Dever;
use Dever\Helper\Str;
use Manage\Lib\Auth;
class Manage extends Auth
{
    # 获取商户列表
    public function getInfo()
    {
        return Dever::db('info', 'seller')->select(array('status' => 1));
    }

    # 获取卡密可以分配的商户列表
    public function getList($channel_id)
    {
        $data[0] = array
        (
            'id' => -1,
            'name' => '--通用卡密--',
        );
        $seller = array();
        if ($channel_id) {
            $seller_channel = Dever::db('channel', 'seller')->select(array('channel_id' => $channel_id, 'status' => 1), array('group' => 'seller_id'));
            if ($seller_channel) {
                foreach ($seller_channel as $v) {
                    $info = Dever::db('info', 'seller')->find(array('id' => $v['seller_id'], 'status' => 1));
                    if ($info) {
                        $seller[] = $info;
                    }
                }
            }
        }
        $data = array_merge($data, $seller);
        return $data;
    }

    # 为商户生成appkey
    public function createAppKey($data)
    {
        $info = Dever::db('info', 'seller')->find($data['id']);
        if (!$info['appkey']) {
            $update['appkey'] = 'app' . Str::rand(15, 0);
            $update['appsecret'] = strtoupper(Str::rand(32));
            $check = Dever::db('info', 'seller')->find(array('appkey' => $update['appkey']));
            if ($check) {
                return $this->createAppKey($data);
            }
            Dever::db('info', 'seller')->update($data['id'], $update);
        }
        /*
        # 写到redis中
        $info = Dever::db('info', 'seller')->find($data['id']);
        Dever::cache('seller_' . $info['appkey'], $info);
        */
    }

    # 为商户生成账号
    public function createUser($data)
    {
        if (isset($data['mobile']) && $data['mobile'] && isset($data['password']) && $data['password']) {
            $info = Dever::db('info', 'seller')->find($data['id']);
            Dever::load('group', 'manage')->createUser('seller', $info['id'], $info['name'], $data['mobile'], $data['password'], true);
        }
        return $data;
    }

    # 订单手动充值
    public function createOrder($data)
    {
        if (!$data['seller_id']) {
            Dever::error('未选择商户');
        }
        if (!$data['data']) {
            Dever::error('未输入充值数据');
        }
        //$goods = explode(',', $data['goods']);
        $goods_id = $data['goods_id'];
        $sku_id = $data['sku_id'];
        $seller_id = $data['seller_id'];
        $seller = Dever::db('info', 'seller')->find($seller_id);
        if (!$seller) {
            Dever::error('商户不存在');
        }
        if ($seller && $seller['status'] == 2) {
            Dever::error('商户已封禁');
        }
        if (!$goods_id) {
            Dever::error('未选择商品');
        }
        if (!$sku_id) {
            Dever::error('未选择规格');
        }
        $goods = Dever::db('info', 'goods')->find($goods_id);
        $sku = Dever::db('info_sku', 'goods')->find($sku_id);
        if (!$goods) {
            Dever::error('商品不存在');
        }
        if (!$sku) {
            Dever::error('规格不存在');
        }
        if ($sku['info_id'] != $goods['id']) {
            Dever::error('商品['.$goods['name'].']下无此规格');
        }
        $cate = Dever::db('cate', 'goods')->find($goods['cate_id']);

        $class = Dever::load('order', 'seller');
        if ($cate['key'] == 'km') {
            $num = $data['data'];
            # 验证是否有剩余的卡密
            # 获取渠道
            $channel = $class->channel($seller['id'], $goods['id'], $sku['id']);
            if (!$channel) {
                Dever::error('通道未开启');
            }
            if ($num > $channel['max']) {
                Dever::error('不能超过最大购买数：' . $channel['max'] . '张');
            }
            $total = Dever::db('card', 'channel')->count(array('channel_id' => $channel['id'], 'goods_id' => $goods['id'], 'sku_id' => $sku['id'], 'status' => 1, 'use_status' => 1));
            if ($total < $num) {
                Dever::error('剩余卡密数量不足，当前剩余卡密数量：' . $total . '张');
            }
            $order = Str::order('PAY');
            $class->add($seller, $goods, $sku, $cate['key'] . '_' . $seller['id'], $order, $num);
        } else {
            $param = explode("\r\n", $data['data']);
            foreach ($param as $k => $v) {
                $order = Str::order('PAY') . '_' . $k;
                $class->add($seller, $goods, $sku, $v, $order);
            }
        }
        return $data;
    }

    # 修改订单状态
    public function editOrder($id, $data)
    {
        if ($data['status'] < 10) {
            Dever::error('请选择订单状态');
        }
        $newid = array();
        $id = explode(',', $id);
        foreach ($id as $k => $v) {
            $info = Dever::db('order', 'seller')->find($v);
            if ($info['status'] < 10) {
                $newid[] = $v;
                if (!$info['order_num']) {
                    $update['order_num'] = Dever::load('order', 'seller')->createOrder();
                    Dever::db('order', 'seller')->update($v, $update);
                }
            }
        }
        if (!$newid) {
            Dever::error('请选择未完成订单');
        }
        $newid = implode(',', $newid);
        $data['finish'] = 1;
        $data['finish_date'] = time();
        return array($newid, $data);
    }

    # 将订单插入到订单日志中
    public function addOrderLog($id, $data)
    {
        $id = explode(',', $id);
        foreach ($id as $k => $v) {
            $info = Dever::db('order', 'seller')->find($v);
            if ($info['status'] >= 10) {
                Dever::load('order', 'seller')->finish($info);
            }
        }
    }

    # 后台充值、提现
    public function operCash($data)
    {
        if ($data['type'] == 1) {
            Dever::db('info', 'seller')->update($data['seller_id'], array('cash' => array('+', $data['cash']), 'p_cash' => array('+', $data['cash'])));
        } elseif ($data['type'] == 2) {
            Dever::load('info', 'seller')->dec($data['seller_id'], $data['cash']);
            $data['cash'] = -1*$data['cash'];
        }
        return $data;
    }

    # 展示订单信息
    public function showOrder($order_id)
    {
        $result = '';
        if ($order_id) {
            $order = Dever::db('order', 'seller')->find($order_id);
            if ($order) {
                $result = $order['order_num'];
            } else {
                $order = Dever::db('order_bak', 'seller')->find($order_id);
                if ($order) {
                    $result = $order['order_num'];
                }
            }
        }
        
        return $result;
    }

    # 展示订单商品
    public function showOrderGoods($cate_id, $goods_id, $sku_id)
    {
        $goods = Dever::db('info', 'goods')->find($goods_id);

        $result = $goods['name'];
        return $result;
    }

    # 展示订单账号
    public function showOrderAccount($status, $account)
    {
        if (strstr($account, 'km_')) {
            if ($status == 10) {
                return '<a>提取卡密</a>';
            }
        }
        return $account;
    }


    # 展示订单金额
    public function showOrderCash($cate_id, $goods_id, $sku_id, $cash, $price, $buy_price, $num)
    {
        $goods = Dever::db('info', 'goods')->find($goods_id);

        $result = $goods['name'] . ' / ' . $cash . ' / ' . $price . ' / ' . $buy_price;
        return $result;
    }

    # 展示订单状态
    public function showOrderStatus($status)
    {
        $value = Dever::db('order', 'seller')->config['struct']['status']['value'][$status];
        if ($status < 10) {
            return $value;
        } elseif ($status == 10) {
            return '<span style="color:blue">'.$value.'</span>';
        } elseif ($status == 11) {
            return '<span style="color:red">'.$value.'</span>';
        }
    }

    # 展示订单统计信息
    public function showOrderStat($where)
    {
        $db = Dever::db('order', 'seller');
        $total = $db->count($where);

        $zongjine = $db->find($where, array('col' => 'sum(cash) as cash'));

        $where['status'] = 10;
        $yes = $db->count($where);
        if ($total <= 0) {
            $lv = '0';
        } else {
            $lv = round($yes/$total*100, 2);
        }
        $czongjine = $db->find($where, array('col' => 'sum(cash) as cash'));
        $szongjine = $db->find($where, array('col' => 'sum(price) as cash'));
        $kzongjine = $db->find($where, array('col' => 'sum(buy_price) as cash'));
        $lirun = $szongjine['cash'] - $kzongjine['cash'];
        
        $where['status'] = array('<', 10);
        $chu = $db->count($where);

        $where['status'] = 11;
        $shibaijine = $db->find($where, array('col' => 'sum(price) as cash'));
        $shibai = $db->count($where);

        return array
        (
            /*
            array
            (
                # 一共24
                'span' => '3',
                'name' => '总订单数',
                'value' => $total,
            ),*/
            array
            (
                'span' => 3,
                'name' => '处理中的笔数',
                'value' => (float) $chu,
            ),
            array
            (
                'span' => 3,
                'name' => '失败的笔数',
                'value' => (float) $shibai,
            ),
            array
            (
                'span' => 3,
                'name' => '成功的笔数',
                'value' => (float) $yes,
            ),
            array
            (
                'span' => 3,
                'name' => '失败的金额',
                'value' => (float) $shibaijine['cash'] ?? 0,
            ),
            array
            (
                'span' => 3,
                'name' => '成功的金额',
                'value' => (float) $szongjine['cash'] ?? 0,
            ),
            array
            (
                'span' => 3,
                'name' => '成功比例',
                'value' => (float) $lv,
                'suffix' => '%',
            ),
            array
            (
                'span' => 3,
                'name' => '交易成本',
                'value' => (float) $kzongjine['cash'] ?? 0,
            ),
            array
            (
                'span' => 3,
                'name' => '交易利润',
                'value' => (float) $lirun ?? 0,
            ),
        );
    }

    # 展示账户统计信息
    public function showLogStat($where)
    {
        $db = Dever::db('info', 'seller');
        $where['id'] = $where['seller_id'];
        $info = $db->find($where);
        return array
        (
            array
            (
                # 一共24
                'span' => '8',
                'name' => '余额',
                'value' => $info['cash'],
            ),
            array
            (
                'span' => '8',
                'name' => '授信额度',
                'value' => $info['credit'],
            ),
            array
            (
                'span' => '8',
                'name' => '总充值金额',
                'value' => $info['p_cash'],
            ),
        );
    }

    # 展示订单扩展信息
    public function showOrderExpand($data)
    {
        $seller = Dever::db('info', 'seller')->find($data['seller_id']);
        $channel = array();
        if ($data['channel_id']) {
            $channel = Dever::db('info', 'channel')->find($data['channel_id']);
        }
        $value = $this->showOrderStatus($data['status']);
        $goods = $this->showOrderCash($data['cate_id'], $data['goods_id'], $data['sku_id'], $data['cash'], $data['price'], $data['buy_price'], $data['num']);
        $result['type'] = 'desc';
        if (strstr($data['account'], 'km_')) {
            $code = $this->kmPwd($data['id'], $data['cdate']);
            $tiqu = array('提取邮箱', '订单处理中，无法提取');
            /*
            $log['seller_id'] = $data['seller_id'];
            $log['order_id'] = $data['id'];
            $order_km = Dever::db('order_km', 'seller')->find($log);
            */
            if ($data['status'] == 10) {
                $tiqu = array('提取卡密', array
                (
                    'input' => '请输入邮箱',
                    'value' => $seller['email'],
                    'button' => '提取',
                    'remote' => Dever::url('seller/manage.tqKmManage', array('order_id' => $data['id'])),
                ));
            }
            
            $result['content'][] = array
            (
                'title' => '卡密信息',
                'border' => true,
                'direction' => 'horizontal',
                'size' => 'small',
                'column' => 1,
                'content' => array
                (
                    array('提取密码', '<font style="color:red">' . $code . '</font>'),
                    $tiqu,
                ), 
            );
            
        }
        
        $result['content'][] = array
        (
            'title' => '商户发起请求',
            'border' => true,
            'direction' => 'horizontal',
            'size' => 'small',
            'column' => 1,
            'content' => array
            (
                array('商户名称', $seller['name']),
                array('商户订单号', $data['seller_order_num']),
                array('商品', $goods),
                array('数量', $data['num']),
                array('商户请求参数', $data['seller_request']),
                array('请求时间', date('Y-m-d H:i', $data['cdate'])),
            ), 
        );
        $result['content'][] = array
        (
            'title' => '系统下单',
            'border' => true,
            'direction' => 'horizontal',//'vertical' | 'horizontal'
            'size' => 'small',//'' | 'large' | 'default' | 'small'
            'column' => 1,
            'content' => array
            (
                array('系统订单ID', $data['id']),
                array('系统订单号', $data['order_num']),
                array('订单状态', $value),
                array('系统发起请求', $data['channel_request']),
                array('请求时间', $data['channel_order_date'] ? date('Y-m-d H:i', $data['channel_order_date']) : '-'),
            ), 
        );
        if ($channel) {
            $result['content'][] = array
            (
                'title' => '渠道响应信息',
                'border' => true,
                'direction' => 'horizontal',
                'size' => 'small',
                'column' => 1,
                'content' => array
                (
                    array('渠道名称', $channel['name']),
                    array('渠道地址', $channel['host']),
                    array('渠道订单号', $data['channel_order_num']),
                    array('渠道响应信息', $data['channel_response']),
                ), 
            );
        }
        
        if ($data['channel_callback']) {
            $result['content'][] = array
            (
                'title' => '渠道回调信息',
                'border' => true,
                'direction' => 'horizontal',
                'size' => 'small',
                'column' => 1,
                'content' => array
                (
                    array('渠道回调信息', $data['channel_callback']),
                    array('回调时间', date('Y-m-d H:i', $data['channel_callback_date'])),
                    array('官方流水号', '<span>' . $data['official_order_num'] . '</span>'),
                    array('官方充值结果', $data['official_msg']),
                ), 
            );
        }
        
        $result['content'][] = array
        (
            'title' => '系统向商户发起回调',
            'border' => true,
            'direction' => 'horizontal',
            'size' => 'small',
            'column' => 1,
            'content' => array
            (
                array('商户响应信息', $data['seller_callback']),
                array('响应时间', $data['seller_callback_date'] ? date('Y-m-d H:i', $data['seller_callback_date']) : '-'),
                array('响应次数', $data['seller_callback_num']),
            ), 
        );
        return $result;
    }

    # 展示订单卡密扩展信息
    public function showOrderExpandKm($data)
    {
        if ($data && $data['status'] == 10 && strstr($data['account'], 'km_')) {
            $seller = Dever::db('info', 'seller')->find($data['seller_id']);
            $result['type'] = 'desc';
            $result['content'][] = array
            (
                'title' => '提取卡密',
                'border' => true,
                'direction' => 'horizontal',
                'size' => 'small',
                'column' => 1,
                'content' => array
                (
                    array('提取邮箱', array
                    (
                        'input' => '请输入邮箱',
                        'value' => $seller['email'],
                        'button' => '提取',
                        'remote' => Dever::url('seller/manage.tqKm', array('order_id' => $data['id'])),
                    )),
                ), 
            );
            $log = Dever::db('order_km', 'seller')->select(array('order_id' => $data['id']));
            $content = array();
            if ($log) {
                foreach ($log as $v) {
                    if ($v['email']) {
                        $v['admin_name'] .= ' 提取邮箱：' . $v['email'];
                    }
                    $content[] = array(date('Y-m-d H:i:s', $v['cdate']), '操作人：' . $v['admin_name']);
                }
            }
            $result['content'][] = array
            (
                'title' => '提取记录',
                'border' => true,
                'direction' => 'horizontal',
                'size' => 'small',
                'column' => 1,
                'content' => $content,
            );
        } else {
            $result['type'] = 'string';
            $result['content'] = '暂无信息';
        }
        
        return $result;
    }

    # 导出卡密
    public function outKm($data)
    {
        $result = array();
        $result['head'] = array('订单id', '订单号', '商品', '面值', '卡号', '密码', '有效期');
        $result['body'] = array();
        foreach ($data['body'] as $k => $v) {
            //$v['sku_id']
            $goods_name = Dever::load("manage", "goods")->showGoodsInfo($v['goods_id'], false);
            $card = Dever::db('card', 'channel')->select(array('order_id' => $v['id'], 'status' => 1));
            if ($card) {
                foreach ($card as $k1 => $v1) {
                    $result['body'][] = array($v['id'], $v['order_num'], $goods_name, $v['cash'], $v1['number'], $v1['pwd'], $v1['end']);
                }
            }
        }
        return $result;
    }

    # 生成卡密密码
    public function kmPwd($id, $cdate)
    {
        $num = ($id + 1000000000);
        return md5(\Dever\Helper\Str::idtostr($num));
    }
}