<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/24
 * Time: 15:30
 */

namespace app\web\controller;


use think\Request;
use app\web\validate\User as UserValidate;
class User extends BaseController
{
    public function getUrl($key)
    {
        $url_list = [
            'select' => 'http://api.sosyun.com/commapi/User/userInfoById?uid=0',
            'selectByID' => 'http://api.sosyun.com/commapi/User/userInfoById?uid=1',
            'add' => 'http://api.sosyun.com/commapi/User/addUser',
            'del' => 'http://api.sosyun.com/commapi/User/delUser',
            'edit' => 'http://api.sosyun.com/commapi/User/editUser'
        ];

        return $url_list[$key];
    }
    public function user_management(){

        return $this->fetch();
    }
    //获取用户列表
    public function getUsers(){
        $url = $this->getUrl('select');
        $org_id = session('organization.org_id');
        $res = json_decode(curlPost($url,[]),true);

        if ($res['code'] != self::SUCCESS_CODE) {
            return json([]);
        }

        $data = $res['data'];
        return json($data);
    }
    // 添加用户

    public function store(Request $request)
    {
        $data = $request->post();

        $validate = new UserValidate();
        $err_msg = $validate->scene("add")->check($data);

        if ($err_msg) {
            return json($this->renderError($validate->getError()));
        }

        $res = json_decode(curlPost($this->getUrl('add'), $data),true);

        if ($res['code'] == self::SUCCESS_CODE) {
            return json($this->renderSuccess());
        }

        return json($res);

    }
    //修改用户
    public function edit(Request $request){
        $data = $request->post();
        if($data['id']){
            $data['uid'] = $data['id'];
        }

        $validate = new UserValidate();
        $err_msg = $validate->scene("update")->check($data);

        if ($err_msg) {
            return json($this->renderError($validate->getError()));
        }

        $res = json_decode(curlPost($this->getUrl('edit'), $data),true);

        if ($res['code'] == self::SUCCESS_CODE) {
            return json($this->renderSuccess());
        }

        return json($res);

    }
    //删除用户
    public function del(Request $request){
        $data = $request->get();

        if (empty($data['id']) && $data['id'] !== 0) {
            return json($this->renderError("删除失败!"));
        }
        $res = json_decode(curlPost($this->getUrl("del"),['uid'=>$data['id']]),true);

        if ($res['code'] != self::SUCCESS_CODE) {
            return json($res);
        }

        return json($this->renderSuccess());
    }
}