<?php
/**
 *------Create thems Controller------
 *------SCWPHP  Version 1.0.0------
 *------Dev Model Jions------
 *------Create Time 2017-06-12 02:52:02------
 */

namespace App\Api\Controller;
/* ini_set('display_errors', 1);
 error_reporting(E_ALL);*/

use App\Api\Model\ArticleType;

class Notice extends BaseController {

    private  $longExpireTime   =  3600;
    private  $ExpireTime       =  60;
    private  $shortExpireTime  =  5;

    private   $_cacheKey;
    Public function Index() {
    }

    /**
     * 获取内容
     * [getContent description]
     * @return [type] [description]
     */
    public function Content() {

        $identity = isset($_REQUEST['identity']) ? $_REQUEST['identity'] : "";
        if (empty($identity)) {
            Render(null, '-5005', lang()->get("notice no identity"));
        }

      //添加缓存Bruce
/*        if( $cache_data=C()->get('cache')->get($this->cacheKey(__FUNCTION__,$identity))){
            Render(json_decode($cache_data,1), "1", "success");
        }*/

        $data = lm('article')
            ->select('title', 'content', 's_title', 'time', 'author', 'img', 'type', 'mobileimg', 'mobilecontent')
            ->where('identity', "{$identity}")
            ->where('status', '1')
            ->first();
        if (!$data) {
            return '-5003';
        }


        $data = $data->toArray();
        if ($data) {
//            C()->get('cache')->set($this->_cacheKey,json_encode($data),$this->longExpireTime);
            Render($data, "1", "success");
        } else {
            Render($data, "-5004", lang()->get('Content fail data'));
        }
    }

    /**
     *查询帮助教程
     *
     */
    public function HelpTutorial() {

        $type = isset($_GET['type']) ? $_GET['type'] : '';
        $limit = isset($_GET['limit']) ? $_GET['limit'] : 3;
        if (empty($type)) {
            Render(null, '-5009');
        }
        //添加缓存Bruce

            if($cache_data=C()->get('cache')->get( $this->cacheKey(__FUNCTION__,$type))){
            Render(json_decode($cache_data,1), "1", "success");
        }

        $data = lm('article')
            ->select('identity', 'title', 'content', 'time')
            ->where('typebind', $type)
            ->where('status', '1')
            ->orderBy('sort', 'desc')
            ->limit($limit)
            ->get();

        if (!($data)) {
            return '-5008';
        }
        $data   = $data->toArray();
        if ($data) {
            C()->get('cache')->set($this->_cacheKey,json_encode($data),$this->longExpireTime);
            Render($data, "1", "success");
        } else {
            Render($data, "-5007", '');
        }
    }


    /**
     * 资讯公告
     * [Tittle description]
     */
    public function Tittle() {
        $identity = isset($_GET['identity']) ? $_GET['identity'] : "";
        if (empty($identity)) {
            Render(null, '-5009');
        }

        //添加缓存Bruce
        if( $cache_data=C()->get('cache')->get($this->cacheKey(__FUNCTION__,$identity))){
            Render(json_decode($cache_data,1), "1", "success");
        }

        $data = lm('article')
            ->select('title', 'content', 'time', 'type', 'mobilecontent')
            ->where('identity', $identity)
            ->where('status', '1')
            ->get()
            ->toArray();

        if (!is_array($data)) {
            return '-5008';
        }
        if ($data) {
            C()->get('cache')->set($this->_cacheKey,json_encode($data),$this->shortExpireTime);
            Render($data, "1", "success");
        } else {
            Render($data, "-5007", '');
        }

    }

    //只显示优惠活动下面的子分类 type =3
    public function TypeName() {
        //添加缓存Bruce
        if( $cache_data=C()->get('cache')->get($this->cacheKey(__FUNCTION__))){
            Render(json_decode($cache_data,1), "1", "success");
        }
        $data = lm('articleType')
            ->select('id', 'cate_name as name', 'create_time as create_at')
            ->where(["parent_id" => 3])
            ->get()
            ->toArray();

        if (!is_array($data)) {
            return '-5008';
        }
        if ($data) {
            C()->get('cache')->set($this->_cacheKey,json_encode($data),$this->longExpireTime);
            Render($data, "1", "success");
        } else {
            Render($data, "-5007", '');
        }

    }

    /**
     * 点击更多
     * @return string
     */
    public function Mores() {
        $data = lm('article')
            ->select('identity', 'title', 'content', 'time')
            ->where('type', '2')
            ->where('status', 1)
            ->first();


        if (!$data) {
            return '-5011';
        }
        $data = $data->toArray();
        if ($data) {
            Render($data, "1", "success");
        } else {
            Render(null, "-5010", '');
        }
    }

    /**
     * 通知
     * [Notice description]
     */
    public function Notice() {
        $user = $this->_getList();
        Render($user, '1', 'success');
    }

    /**
     * 充值跑马灯
     * [recharge description]
     */
    public function RechargeDesc() {

        //缓存--Bruce
        if( $cache_data=C()->get('cache')->get($this->cacheKey(__FUNCTION__))){
            Render(json_decode($cache_data,1), "1", "success");
        }

        $list = lm('setinfo', 'commons')->where('infotype', 9)->select('infocontent')->first();
        if (empty($list)) {
            Render(null, '-2102', '');
        }
        C()->get('cache')->set($this->_cacheKey,json_encode($list['infocontent']),$this->longExpireTime);
        Render($list['infocontent'], '1', 'success');
    }

    /**
     * 通知封装
     * [_getList description]
     * @return [type] [description]
     */
    private function _getList() {
        try {
            $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : "";

            // if (empty($type)) {
            // 	Render(null, '-5002', lang()->get('type fail get'));
            // }
            $curpage = isset($_POST['curpage']) ? intval($_POST['curpage']) : "1";
            $pagelist = '20';
            $firstcode = ($curpage - 1) * $pagelist;
            //获取总页数

            if($cache_data=C()->get('cache')->get($this->cacheKey(__FUNCTION__,$type.'$curpage'))){
                Render(json_decode($cache_data,1), "1", "success");
            }
            //文章类别
            $all_type = (new ArticleType)->type();

            /*        $sontype    =   lm("ArticleType",'Api')->get()->toarray();
                    var_dump($sontype);exit();*/
            //获取子类别
            $types = [];
            if (!empty($type)) {

                $_type = explode(',', $type);
                foreach ($_type as $v) {
                    if (!empty($v)) {
                        $types = array_merge($types, $this->getTree($all_type, $v));
                    }
                }

                $types = array_column($types, 'id');
                $types = array_merge($_type, $types);
            } else {
                //为空的时候只显示优惠活动下的  id=3
                $types = array_merge($types, $this->getTree($all_type, 3));
                $types = array_column($types, 'id');
                $types = array_merge($types, [3]);
            }


            $tol_list = lm('article');
            if (empty($types)) {
                $datas = $tol_list->where('status', '1')->where('type', '!=', 8)->count();
            } else {

                if (count($types > 1)) {
                    $datas = $tol_list->whereIn('type', $types)->where('status', '1')->count();
                } else {
                    $datas = $tol_list->where('type', $types[0])->where('status', '1')->count();
                }

            }


            $tolpage = ceil($tol_list / $pagelist);
            $res = lm('article')
                ->leftJoin('lottery_money', 'article.child_id', '=', 'lottery_money.id')
                ->select('article.identity', 'article.title', 'article.content',
                    'article.s_title', 'article.time', 'article.author', 'article.img',
                    'article.child_id', 'article.type', 'article.mobilecontent',
                    'article.mobileimg', 'article.typebind', 'article.sort', 'article.id', 'lottery_money.type as act_cate');
            if (empty($types)) {
                $datas = $res->where('article.status', '1')->where('article.type', '!=', 8)
                    ->orderBy('article.sort', 'desc')->orderBy('article.time', 'desc')
                    ->skip("{$firstcode}")
                    ->take("{$pagelist}")
//                    ->leftjoin('')
                    ->get()
                    ->toArray();
            } else {
                if (count($types > 1)) {
                    $datas = $res->whereIn('article.type', $types);
                } else {
                    $datas = $res->where('article.type', $types[0]);
                }

                $datas = $datas->where('article.status', '1')
                    ->orderBy('article.sort', 'desc')->orderBy('article.time', 'desc')
                    ->skip("{$firstcode}")
                    ->take("{$pagelist}")
                    ->get()
                    ->toArray();
            }

            if (!is_array($datas)) {
                return '-5001';
            }
            $data['data'] = $datas;
            $data['page']['curpage'] = $curpage;
            $data['page']['tolpage'] = $tolpage;
            C()->get('cache')->set($this->_cacheKey,json_encode($data),$this->shortExpireTime);
            return $data;
        } catch (\Exception $e) {
            // Render("",-5007);
            print $e->getMessage();
            exit();
        }
    }

    /**
     * 支付切换
     * [switch description]
     * @return [type] [description]
     */
    public function Switchs() {
        $status = isset($_POST['status']) ? $_POST['status'] : '-1';
        if (empty($status)) {
            Render(null, '-5017');
        }
        $identity = isset($_POST['identity']) ? $_POST['identity'] : '76d6e867-19bd-b553-c58d-4548561dd217';
        if (empty($identity)) {
            Render(null, '-5018');
        }
        $res = [
            'status' => $status,
        ];
        $data = lm('payment')
            ->where('identity', $identity)
            ->update($res);

        if ($data) {
            Render($data, '1', 'success');
        } else {
            Render(null, '-5016', 'error');
        }
    }

    /**
     * 银行卡与人员管理
     * @return string
     */
    public function Bank_card_management() {
        $accountManager = new \Biz\Account\AccountManager();
        $uinfo = $accountManager->getCurrentUser();
        if ($uinfo) {
            $uinfo = json_encode($uinfo);
            $uinfo = json_decode($uinfo, 1);
            $gc = explode(',', $uinfo['group_code']);
        } else {
            Render('', -4001);
        }
        $temp = 1;
        $where='';
        if (!isset($gc)) {
            $where = "groups = '0,'";
        } else {
            foreach ($gc as $k => $v) {
                if (!empty($v)) {
                    $where .= ($temp == 1) ? '(' : ' or ';
                    $temp = 2;
                    $where .= "groups like '%," . $v . ",%'";
                }
            }
            $where .= ($temp == 2) ? ')' : '';
        }
        $data = lm('system_bank', 'commons')->getInfos($where);
        if (!is_array($data)) {
            if (isset($gc)) {
                $where = "groups = '0,'";
                $data = lm('system_bank', 'commons')->getInfos($where);
                if (!is_array($data)) {
                    Render(null, '-5025', 'error');
                }
            } else {
                Render(null, '-5025', 'error');
            }
        }

        if ($data) {
            Render($data, '1', 'success');
        } else {
            Render(null, '-5024', 'error');
        }
    }

    private function getTree($array, $pid = 0, $cen = 0) {
        $arr = array();
        $cen = ++$cen;
        $str = "";
        foreach ($array as $k => $v) {
            if ($v['parent_id'] == $pid) {
                $str = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $cen - 1);
                $arr[] = ["id" => $v["id"], "name" => ($cen - 1 ? $str . "└" . $v["cate_name"] : $v["cate_name"])];
                unset($array[$k]);
                $arr = array_merge($arr, $this->getTree($array, $v['id'], $cen));
            }
        }
        return $arr;
    }

    /**
     * @param $keyAdd 附加数据
     * @return string   返回缓存keyo值
     */
    private function cacheKey($fun,$keyAdd=''){
      return  $this->_cacheKey=md5( __CLASS__.'_'.$fun.'_'.$keyAdd);
    }
}
