<?php
namespace Qrcode\Controller;

use Base\Service\PromoteService;
use Think\Controller;

class QrCodePromotionController extends BaseController
{
    public function lists1()
    {
        $page = I('p', 1);
        $row = I('row', 10);

        $query = M('qrcode_promotion', 'tab_')->where([])->order('create_time desc');
        [$items, $page, $count] = $this->paginate($query);

        $baseGames = M('base_game', 'tab_')->select();
        $baseGames = index_by_column('id', $baseGames);

        $games = M('game', 'tab_')->where(['id', 'partner_id'])->select();
        $games = index_by_column('id', $games);
        foreach ($baseGames as $key => $baseGame) {
            if ($baseGame['android_game_id'] > 0) {
                $baseGame['partner_id'] = $games[$baseGame['android_game_id']]['partner_id'];
            } else {
                $baseGame['partner_id'] = $games[$baseGame['ios_game_id']]['partner_id'];
            }
            $baseGames[$key] = $baseGame;
        }
//var_dump($items);die;
        $this->assign('_page', $page);
        $this->assign('records', $items);
        $this->assign('baseGames', $baseGames);
        $this->display();
    }

    public function uploadQrCodeBackground()
    {
        $fileController = new FileController();
        $ossStatus = C('OSS_STATUS');
        C('OSS_STATUS', false);
        /* 调用文件上传组件上传文件 */
        $Picture = D('Picture');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');

        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$pic_driver}_CONFIG"),
            $_REQUEST['flag']
        ); //

        C('OSS_STATUS', $ossStatus);

        $path = '';
        if ($info) {
            $path = get_cover($info['file']['id'], 'path');
        }

        return $this->ajaxReturn([
            'id' => $info['file']['id'],
            'path' => $path
        ]);
    }

    public function save()
    {
        $params = I('post.');
        if (!$params['base_game_id']) {
            $this->ajaxReturn(['status' => 0, 'message' => '参数有误!']);
        }
        $exists = M('qrcode_promotion', 'tab_')->where([
            "game_id" => $params['base_game_id']
        ])->find();
        if ($exists) {
            M('qrcode_promotion', 'tab_')->where([
                "game_id" => $params['base_game_id']
            ])->save([
                'background_img' => $params['img'],
                'update_time' => time(),
                'admin_id' => getAdmin(),
                'admin_name' => getAdmin('username'),
            ]);
        } else {
            if (!$params['base_game_id']) {
                $this->ajaxReturn(['status' => 0, 'message' => '游戏不能为空!']);
            }
            M('qrcode_promotion', 'tab_')->add([
                'game_id' =>  $params['base_game_id'],
                'game_name' => $params['game_name'].'',
                'status' => 0,
                'background_img' => $params['img'],
                'create_time' => time(),
                'update_time' => 0,
                'admin_id' => getAdmin(),
                'admin_name' => getAdmin('username'),
            ]);
        }
        $this->ajaxReturn(['status' => 1, 'message' => '保存成功!']);
    }

    public function add()
    {
        $baseGames = M('base_game', 'tab_')->select();
        $baseGames = index_by_column('id', $baseGames);

        $games = M('game', 'tab_')->where(['id', 'partner_id'])->select();
        $games = index_by_column('id', $games);
        foreach ($baseGames as $key => $baseGame) {
            if ($baseGame['android_game_id'] > 0) {
                $baseGame['partner_id'] = $games[$baseGame['android_game_id']]['partner_id'];
            } else {
                $baseGame['partner_id'] = $games[$baseGame['ios_game_id']]['partner_id'];
            }
            $baseGames[$key] = $baseGame;
        }
        $this->assign('baseGames', $baseGames);

        if (IS_POST) {
            $loginer = $this->getLoginPromote();
            $params = I('post.');
            if (!$params['base_game_id']) {
                $this->ajaxReturn(['status' => 0, 'message' => '参数有误!']);
            }
            $exists = M('qrcode_promotion', 'tab_')->where([
                "game_id" => $params['base_game_id']
            ])->find();
            if ($exists) {
                M('qrcode_promotion', 'tab_')->where([
                    "game_id" => $params['base_game_id']
                ])->save([
                    'background_img' => $params['img'],
                    'update_time' => time(),
                    'admin_id' => $loginer['id'],
                    'admin_name' => $loginer['account'],
                ]);
            } else {
                if (!$params['base_game_id']) {
                    $this->ajaxReturn(['status' => 0, 'message' => '游戏不能为空!']);
                }
                M('qrcode_promotion', 'tab_')->add([
                    'game_id' =>  $params['base_game_id'],
                    'game_name' => $params['game_name'].'',
                    'status' => 0,
                    'background_img' => $params['img'],
                    'create_time' => time(),
                    'update_time' => 0,
                    'admin_id' => $loginer['id'],
                    'admin_name' => $loginer['account'],
                ]);
            }
            $this->ajaxReturn(['status' => 1, 'message' => '保存成功!']);
        }

        $this->display();
    }

    public function linkAdd()
    {
        if (IS_POST) {
            $isHttps = is_https();
            $loginer = $this->getLoginPromote();
            $params = I('post.');
            if (!$params['id']) {
                $this->ajaxReturn(['status' => 0, 'message' => '参数有误!']);
            }

            $id = M('qrcode_promotion_list', 'tab_')->add([
                'qp_id' => $params['id'],
                'admin_id' => $loginer['id'],
                'admin_name' => $loginer['account'],
                'h5_link' => '',
                'short_link' => '',
                'create_time' => time(),
                'status' => 0,
                'qrcode_img' => $params['img'],
            ]);
            if ($id > 0) {
                $h5Link = ($isHttps? 'https://': 'http://').$_SERVER['HTTP_HOST']."/index.php?s=/Qrcode/Jump/jumpMp/id/{$id}";
                $expireDate = date('Y-m-d', strtotime("+30 day"));
                $shortLink = $this->getShortUrl($h5Link, $expireDate);

                M('qrcode_promotion_list', 'tab_')->where(['id' => $id])->save([
                    'h5_link' => $h5Link,
                    'short_link' => $shortLink
                ]);
            }

            $this->ajaxReturn(['status' => 1, 'message' => '保存成功!']);
        }

        $qpId = I('get.id', 0);
        $this->assign("qp_id", $qpId);
        $this->display();
    }

    public function linkLists()
    {
        $page = I('p', 1);
        $row = I('row', 10);
        $qpId = I('get.id', 0);
        if (!$qpId) return ;

        $promotionInfo = M('qrcode_promotion', 'tab_')->where([
            'id' => $qpId
        ])->find();

        $query = M('qrcode_promotion_list', 'tab_')->where([
            'qp_id' => I('get.id')
        ])->order('create_time desc');
        [$items, $page, $count] = $this->paginate($query);

        $this->assign("qp_id", $qpId);
        $this->assign('_page', $page);
        $this->assign('records', $items);
        $this->assign('promotion_info', $promotionInfo);
        $this->display();
    }

    public function lists()
    {
        $query = M('qrcode_promotion', 'tab_')->where([])->order('create_time desc');
        [$items, $page, $count] = $this->paginate($query);

        $this->assign('_page', $page);
        $this->assign('records', $items);

        $this->display();
    }

    public function getShortUrl($long_url, $expire_date)
    {
        $url = urlencode($long_url);
        $key = "612a01db7889bec5e0d0d2d81f@df6cdda6eb39c505f08848f714b0433e";
        $request_url = "http://api.3w.cn/api.htm?format=json&url={$url}&key={$key}&expireDate={$expire_date}&domain=0";
        $result_str = file_get_contents($request_url);

        $url = "";
        if ($result_str) {
            $result_arr = json_decode($result_str, true);

            if ($result_arr && $result_arr['code'] == "0") {
                $url = $result_arr['url'];
            }
        }

        return $url;
    }

}