<?php
namespace addons\address\controller;
use think\addons\Controller;
use app\common\model\User;
use Request;
use Db;

class Admin extends Controller
{
    // 后台管理操作控制器必须判断管理员登陆
    protected function initialize()
    {
        parent::initialize();
        // 判断是否管理员登陆
        if(!session('?adminid')) abort(404,'访问的内容不存在');
        $this->isInstall();
    }

    // 管理入口
    public function index()
    {
        if(Request::isPost())
        {
            $userid = Request::post('userid');
            $data = Db::name('address')->withAttr('userinfo',function($value,$data){
                return User::get($data['user_id']);
            })->when(!empty($userid),function($query)use($userid){
                $query->whereUserId($userid);
            })->withAttr('address2',function($value,$data){
                $province = Db::name('region')->getFieldById($data['province'],'name');
                $city = Db::name('region')->getFieldById($data['city'],'name');
                $district = Db::name('region')->getFieldById($data['district'],'name');
                return $province .' / '. $city .' / '. $district;
            })->append(['address2'])->paginate(input('post.limit/d'))->toArray();
            return json(['code'=>0,'msg'=>'获取数据成功','data'=>$data['data'],'count'=>$data['total']]);
        }
        return $this->fetch('');
    }
    // 删除
    public function del()
    {
        if(Request::isPost()) {
            $data = Request::post();
            $result = Db::name('address')->delete($data['id']);
            if ($result) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('删除失败');
        }
    }
}