<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Validate;
use app\common\model\Area as AreaModel;
use helper\PinYin;
class Area extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if (empty($G['id'])) {
                return $this->ajaxReturn('',0,AreaModel::getSelect(['pid'=>0]));
            }else{
                return $this->ajaxReturn('',0,AreaModel::getSelect(['pid'=>$G['id']]));
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑地区
     */
    public function edit($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:area',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AreaModel=AreaModel::find($id);
            $AreaModel->title    = $D['title'];
            $AreaModel->alias    = $D['alias'];
            $AreaModel->level    = $D['level'];
            $AreaModel->status   = $D['status'];
            if (isset($D['sort'])&&intval($D['sort']))
                $AreaModel->sort    = intval($D['sort']);
            if (!empty($D['pid'])) 
	            $AreaModel->pid   	= $D['pid'];
            $PinYin=new PinYin;
            $p=$PinYin->get_all_py($D['title']);
            $AreaModel->letter    = $PinYin->get_first_letter($p);
            if($AreaModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $area=AreaModel::getCate()->toArray();
            View::assign('area',$area);
            $Find=AreaModel::where(['id'=>$id])->find();
            View::assign('Find',$Find);
            return View::fetch('add');
        }
    }
    /**
     * 添加地区
     */
    public function add()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:area',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AreaModel=new AreaModel;
            $AreaModel->title    = $D['title'];
            $AreaModel->alias    = $D['alias'];
            $AreaModel->level    = $D['level'];
            $AreaModel->status   = $D['status'];
            if (isset($D['sort'])&&intval($D['sort']))
                $AreaModel->sort    = intval($D['sort']);
            if (!empty($D['pid'])){
	            $AreaModel->pid   	= $D['pid'];
            }else{
                $AreaModel->pid     = 0;
            }
            $PinYin=new PinYin;
            $p=$PinYin->get_all_py($D['title']);
            $AreaModel->letter    = $PinYin->get_first_letter($p);
            if($AreaModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $area=AreaModel::getCate()->toArray();
            View::assign('area',$area);
            return View::fetch();
        }
    }
    public function setAreaStatus($id,$status)
    {
        $AreaModel=AreaModel::where(['id'=>$id])->find();
        $AreaModel->status=$status;
        if ($AreaModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function setAreaHot($id,$status)
    {
        $AreaModel=AreaModel::where(['id'=>$id])->find();
        $AreaModel->hot=$status;
        if ($AreaModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function updateFileAjax()
    {
        $this->updateFileCache();
        return $this->ajaxReturn('更新成功');
    }
    public function updateFileCache()
    {
        $Arealist=AreaModel::getCache()->toArray();
        Cache::set('arealist',$Arealist);
        if(AreaModel::where(['pid'=>0,'status'=>1])->count()===1){
            $Find=AreaModel::where(['pid'=>0,'status'=>1])->find();
            if (AreaModel::where(['pid'=>$Find->id,'status'=>1])->count()===1) {
                $City=AreaModel::where(['pid'=>$Find->id,'status'=>1])
                ->field('id,title,letter,hot,level')->order('sort asc,id asc')->select()->toArray();
                $Data=[];
                foreach ($City as $k => $v) {
                    $Area=AreaModel::where(['pid'=>$v['id'],'status'=>1])
                    ->field('id,title,letter,hot,level')->order('sort asc,id asc')->select()->toArray();
                    foreach ($Area as $ke => $va) {
                        $Data[]=$va;
                    }
                }
            }else{
                $Data=AreaModel::where(['pid'=>$Find->id,'status'=>1])
                ->field('id,title,letter,hot,level')->order('sort asc,id asc')->select()->toArray();
            }
        }else{
            $Data=AreaModel::alias('city')->where(['city.level'=>2])
            ->join('area p','p.id=city.pid AND p.status=1')
            ->field('city.id,city.title,city.letter,city.hot,city.level')->order('city.sort asc,city.id asc')->select()->toArray();
        }
        $Citylist=[];
        foreach ($Data as $k => $v) {
            if ($v['hot']) {
                if (empty($Citylist['A0']['title']))
                    $Citylist['A0']['title']='热门城市';
                $Citylist['A0']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
            }
            if (empty($Citylist[strtoupper($v['letter']).'1']['title']))
                $Citylist[strtoupper($v['letter']).'1']['title']=strtoupper($v['letter']);
            $Citylist[strtoupper($v['letter']).'1']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
        }
        ksort($Citylist);
        $CacheCity=[];
        foreach ($Citylist as $k => $v) $CacheCity[]=$v;
        Cache::set('citylist',$CacheCity);
    }
}
