<?php namespace Seller\Api;
use Dever;
use Manage\Lib\Auth;
class Manage extends Auth
{
    public function showOrderExpand($value = false)
    {
        $data = Dever::db('order', 'seller')->find($value);
        return Dever::load('manage', 'seller')->showOrderExpand($data);
    }

    public function showOrderLogExpand($value = false)
    {
        $data = Dever::db('order_log', 'seller')->find($value);
        return Dever::load('manage', 'seller')->showOrderExpand($data);
    }

    public function showOrderExpandKm($value = false)
    {
        $data = Dever::db('order', 'seller')->find($value);
        return Dever::load('manage', 'seller')->showOrderExpandKm($data);
    }

    public function showOrderLogExpandKm($value = false)
    {
        $data = Dever::db('order_log', 'seller')->find($value);
        return Dever::load('manage', 'seller')->showOrderExpandKm($data);
    }

    # 补发回调
    public function sendCallBack()
    {
        $id = Dever::input('id');
        if ($id) {
            $where['id'] = array('in', $id);
            $order = Dever::db('order', 'seller')->load($where);
            foreach ($order as $k => $v) {
                $msg = '';
                if ($v['status'] == 10) {
                    $msg = 'ok';
                } elseif ($v['status'] == 11) {
                    $msg = 'error';
                }
                if ($msg) {
                    Dever::load('order', 'seller')->notify($v, $msg, array(), 1000);
                }
            }
        } else {
            Dever::error('请选择发回调的订单');
        }
        return '回调发送成功';
    }

    # 获取商品
    public function getGoods($value = false)
    {
        $result = array();
        $result['goods']['value'] = '';
        $result['sku_id']['value'] = '';
        $result['goods_id']['value'] = '';
        $result['goods']['option'] = array();
        $result['sku_id']['option'] = array();
        if (!$value) {
            return $result;
        }
        $channel = Dever::db('channel', 'seller')->select(array('seller_id' => $value, 'status' => 1));
        if ($channel) {
            $option = $setCate = $setGoods = array();
            $i = 0;
            foreach ($channel as $k => $v) {
                $goods = Dever::db('info', 'goods')->find($v['goods_id']);
                if ($goods && $goods['status'] == 1) {
                    if (!isset($setCate[$goods['cate_id']])) {
                        $cate = Dever::db('cate', 'goods')->find($goods['cate_id']);
                        if ($cate) {
                            $setCate[$goods['cate_id']] = $i;
                            $option[$i] = array
                            (
                                'id' => $cate['id'],
                                'name' => $cate['name'],
                            );
                            $i++;
                        }
                    }
                    if (!isset($setGoods[$goods['id']])) {
                        $v['name'] = $goods['name'];
                        $option[$setCate[$goods['cate_id']]]['children'][] = $v;
                        $setGoods[$goods['id']] = 1;
                    }
                }
            }
            $result['goods']['option'] = $option;
        }
        return $result;
    }

    public function getSku($value)
    {
        if (is_array($value)) {
            $value = end($value);
        }
        $result = array();
        $result['sku_id']['value'] = '';
        if (!$value) {
            $result['sku_id']['option'] = array();
            return $result;
        }
        $channel = Dever::db('channel', 'seller')->find($value);
        $channel_sku = Dever::db('channel', 'seller')->select(array('seller_id' => $channel['seller_id'], 'goods_id' => $channel['goods_id'], 'status' => 1));
        if ($channel_sku) {
            $sku = array();
            foreach ($channel_sku as $k => $v) {
                if ($v['sku_id']) {
                    $v['sku_id'] = explode(',', $v['sku_id']);
                    foreach ($v['sku_id'] as $v1) {
                        $sku[$v1] = $v1;
                    }
                }
            }
        }
        $result['goods_id']['value'] = $channel['goods_id'];

        $where = array('info_id' => $channel['goods_id']);
        if (isset($sku) && $sku) {
            $where['id'] = array('in', implode(',', $sku));
        }
        $sku = Dever::db('info_sku', 'goods')->select($where);
        if ($sku) {
            $option = array();
            foreach ($sku as $k => $v) {
                if ($v['key'] != -1) {
                    $spec = Dever::db('info_spec_value', 'goods')->find(array('id' => array('in', $v['key'])), array('col' => 'id,group_concat(value) as name', 'group' => 'info_id'));
                    if ($spec) {
                        $spec['id'] = $v['id'];
                        $result['sku_id']['value'] = $v['id'];
                        $option[] = $spec;
                    }
                } else {
                    $result['sku_id']['value'] = $v['id'];
                    $option[0] = array
                    (
                        'id' => $v['id'],
                        'name' => '无',
                    );
                }
            }
            $result['sku_id']['option'] = $option;
            //$result['sku_id']['desc'] = '222';
        }
        
        return $result;
    }

    # 提取卡密
    public function tqKmManage()
    {
        return $this->tqKmRun(2);
    }

    # 提取卡密
    public function tqKm()
    {
        return $this->tqKmRun(1);
    }

    # 提取卡密
    public function tqKmRun($type = 1)
    {
        $value = Dever::input('value');
        $id = Dever::input('order_id');
        $order = Dever::db('order', 'seller')->find($id);

        /*
        $code = Dever::load('manage', 'seller')->kmPwd($order['id'], $order['cdate']);
        if ($code != $value) {
            Dever::error('密码错误');
        }*/

        if (!$value) {
            Dever::error('请输入正确的邮箱');
        }
        if (!preg_match(Dever::rule('email'), $value)) {
            Dever::error('请输入正确的邮箱');
        }
        if ($type == 1) {
            $log['seller_id'] = $order['seller_id'];
            $log['order_id'] = $id;
            $order_km = Dever::db('order_km', 'seller')->find($log);
            if ($order_km) {
                Dever::error('您已经提取过卡密，无法重复提取，如需再次提取请联系商务');
            }
        }

        $result = array();
        $result['msg'] = '提取成功';
        //$result['url'] = Dever::url('seller/manage.tqKmAct', array('order_id' => $order['id'], 'value' => $value));
        \Dever\Helper\Cmd::run('seller/manage.tqKmAct', array('order_id' => $order['id'], 'value' => $value));

        # 增加提取日志
        $log['admin_id'] = $this->uid;
        $log['system_id'] = $this->system['id'];
        $log['admin_name'] = $this->user['name'];
        $log['email'] = $value;

        Dever::db('order_km', 'seller')->insert($log);
        return $result;
    }

    # 提取卡密
    public function tqKmAct()
    {
        $value = Dever::input('value');
        $id = Dever::input('order_id');
        $order = Dever::db('order', 'seller')->select($id);
        if (!$order) {
            Dever::error('订单不存在');
        }

        $code = Dever::load('manage', 'seller')->kmPwd($order[0]['id'], $order[0]['cdate']);
        /*
        if ($code != $value) {
            Dever::error('密码错误');
        }
        */
        $data = Dever::load('manage', 'seller')->outKm(array('body' => $order));
        
        $file = Dever::load('export', 'excel')->act($data['body'], $data['head'], '导出卡密', 0, '', false, false, $code, 'km' . $id);

        $seller = Dever::db('info', 'seller')->find($order[0]['seller_id']);
        $email = $value;
        $username = $seller['name'];
        $title = '您有新的卡密请查收';
        $content = '请您打开附件提取卡密，提取密码请联系商务人员';
        $this->send($email, $username, $title, $content, $file);
        Dever::db('info', 'seller')->update($seller['id'], array('email' => $value));
        return '卡密提取成功';
    }

    # 发送邮件
    public function send($email, $username, $title, $content, $file = '')
    {
        $config = Dever::db('config', 'channel')->find(1);

        Dever::apply('PHPMailer', 'email', 'src');
        Dever::apply('Exception', 'email', 'src');
        Dever::apply('SMTP', 'email', 'src');
        $mail = new \PHPMailer\PHPMailer\PHPMailer();

        $mail->isSMTP();
        //$mail->SMTPDebug = 2;
        $mail->CharSet = 'UTF-8';
        $mail->Host = 'smtp.exmail.qq.com';
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $config['email_user'];
        $mail->Password = $config['email_pass'];
        $mail->setFrom($config['email_user'], 'kaibihe');
        $mail->addAddress($email, $username);
        $mail->Subject = "=?utf-8?B?" . base64_encode($title) . "?=";
        $mail->Body = $content;
        $mail->isHTML(true);
        if ($file) {
            $mail->addAttachment($file);
        }
        if (!$mail->send()) {
            Dever::log($email . '-' . $username . '-' . $mail->ErrorInfo, 'email');
            Dever::alert("Mailer Error: " . $mail->ErrorInfo);
        } else {
            @unlink($file);
            return 'ok';
        }
    }
}