<?php


namespace app\admin\controller;

use app\BaseController;
use think\Request;
use think\facade\Db;
use app\admin\model\ActionLog;

//角色权限共享
class Share extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(101,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $page = isset($post['page']) ? intval($post['page']): 1;
        $size = isset($post['size']) ? intval($post['size']):10;
        $condition=[];
        $condition[]=["is_del","=",0];
        $source_uname = isset($post['source_uname'])&&$post['source_uname']!='' ? trim($post['source_uname']) :"";
        if($source_uname!=''){
            $uid =Db::name("depart_user")->where([["nickname","like","%$source_uname%"],["is_del","=",0]])->column("uid");
            $condition[]=["share_user","in",$uid];
        }
         $to_uname = isset($post['to_uname'])&&$post['to_uname']!='' ? trim($post['to_uname']) :"";
        if($to_uname!=''){
            $uid =Db::name("depart_user")->where([["nickname","like","%$to_uname%"],["is_del","=",0]])->column("uid");
            $condition[]=["to_user","in",$uid];
        }
         $group_name = isset($post['group_name'])&&$post['group_name']!='' ? trim($post['group_name']) :"";
        if($group_name!=''){
            $uid =Db::name("role_group")->where([["group_name","like","%$group_name%"],["is_del","=",0]])->column("id");
            $condition[]=["to_group","in",$uid];
        }
        $count =Db::name("role_share")->where($condition)->count();
        $total = ceil($count/$size)>1 ? ceil($count/$size) : 1;
        $page = $page>=$total?intval($total):$page;
        $list = Db::name("role_share")->where($condition)->page($page,$size)->order("id desc")->select();
        $result = [];
        foreach ($list as $key=>$val){
            $temp = [];
            $temp['id']=$val['id'];

            $menu = Db::name("admin_menu")->where("id in ({$val['action_collect']})")->column("menu_name");
            $temp['actionlist']=implode(",",$menu);
            $userid = [];
            $val['share_user']!=""&&$val['share_user']!=0  ?$userid[]=$val['share_user']:"";
            $val['to_user']!=""&&$val['to_user']!=0  ?$userid[]=$val['to_user']:"";
            $cond = ['id' => $userid];
            $user = GetUserlist($token, $cond);
            $share_name = "";
            $to_name = "";

            if ($user['code'] == 0 && !empty($user['data'])) {
                foreach ($user['data'] as $v) {

                    if($val['share_user']==$v['id']){
                        $share_name= isset($v['nickname']) ?$v['nickname']:"";
                    }
                    if($val['to_user']==$v['id']){
                        $to_name= isset($v['nickname']) ?$v['nickname']:"";
                    }
                }
            }

            $temp['share_user']=$share_name;
            $togroup = $val['to_group']!=""&&$val['to_group']!=0?Db::name("role_group")->where("id","=",
                $val["to_group"])->find()
                :['group_name'=>""];

            $temp['to_user']=$to_name;
            $temp['to_group']=$togroup['group_name'];
            $temp['status']=$val['status'];
            $temp['action']=$val['action'];
            $temp['addtime']=$val['addtime'];
            array_push($result,$temp);
        }
        return  app_show(0,"获取成功",['list'=>$result,"count"=>$count]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(101,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $collect = isset($post['collect']) ? trim($post['collect']):"";
        $user = isset($post['userid']) ? intval($post['userid']):"";
        $touser = isset($post['touserid']) ? intval($post['touserid']):"";
        $togroup = isset($post['togroupid']) ? intval($post['togroupid']):"";
        $action = isset($post['action'])&&$post['action']!=='' ? trim($post['action']):"";
        if($collect==""){
            return error_show(1002,"菜单数据不能为空");
        }
        if($user==""){
            return error_show(1003,"数据源用户不能为空");
        }
        if($touser=="" && $togroup==""){
            return error_show(1004,"共享用户或用户组不能为空");
        }
        $data=[
            "action_collect"=>$collect,
            "share_user"=>$user,
            "to_user"=>$touser==0?"":$touser,
            "to_group"=>$togroup==0?'':$togroup,
            "action"=>$action==0?'':$action,
            "status"=>1,
            "addtime"=>date("Y-m-d H:i:s"),
            "updatetime"=>date("Y-m-d H:i:s")
        ];
        $result= Db::name("role_share")->save($data);
        $st = ["order_code"=>$collect,"status"=>1,"action_remark"=>'',"action_type"=>"create"];
        ActionLog::logAdd($token,$st,"role_share",1,$st);
        return $result ? app_show(0,"新建成功"):error_show(1006,"新建失败");
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(1001,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $id = isset($post['id'])&&$post['id']!="" ? intval($post['id']):"";
        if($id===""){
            return error_show(1002,"参数id不能为空");
        }
        $collect = isset($post['collect'])&&$post['collect']!="" ? trim($post['collect']):"";
        $user = isset($post['userid'])&&$post['userid']!="" ? intval($post['userid']):"";
        $touser = isset($post['touserid'])&&$post['touserid']!="" ? intval($post['touserid']):"";
        $togroup = isset($post['togroupid'])&&$post['togroupid']!="" ? intval($post['togroupid']):"";
        $action = isset($post['action'])&&$post['action']!="" ? trim($post['action']):"";
        $info = Db::name("role_share")->where("id","=",$id)->find();
        if(!$info){
            return error_show(1002,"未找到对应数据");
        }
        if($collect==""){
            return error_show(1002,"菜单数据不能为空");
        }
        if($user==""){
            return error_show(1003,"数据源用户不能为空");
        }
        if($touser=="" && $togroup==""){
            return error_show(1004,"共享用户或用户组不能为空");
        }
//        if($action===""){
//            return error_show(1005,"共享数据权限不能为空");
//        }
        $data=[
            "action_collect"=>$collect,
            "share_user"=>$user,
            "to_user"=>$touser==0?"":$touser,
            "to_group"=>$togroup==0?'':$togroup,
            "action"=>$action==0?'':$action,
            "updatetime"=>date("Y-m-d H:i:s")
        ];
        $result= Db::name("role_share")->where("id","=",$id)->update($data);
        $st = ["order_code"=>$collect,"status"=>0,"action_remark"=>'',"action_type"=>"edit"];
        ActionLog::logAdd($token,$st,"role_share",0,$st);
        return $result ? app_show(0,"更新成功"):error_show(1006,"更新失败");
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(1001,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $id = isset($post['id'])&&$post['id']!=""  ? intval($post['id']):"";
        $info =  Db::name("role_share")->where([["id","=",$id],["is_del","=",0]])->find();
        if(!$info){
            return error_show(1002,"未找到对应数据");
        }

        $menu =Db::name("admin_menu")->where("id in ({$info['action_collect']})")->column("menu_name");

        $info['actionlist']=implode(",",$menu);

        $userid = [];
        $info['share_user']!=""&&$info['share_user']!=0  ?$userid[]=$info['share_user']:"";
        $info['to_user']!=""&&$info['to_user']!=0  ?$userid[]=$info['to_user']:"";
        $cond = ['id' => $userid];
        $user = GetUserlist($token, $cond);
        $share_name = "";
        $to_name = "";
        if ($user['code'] == 0 && !empty($user['data'])) {
            foreach ($user['data'] as $v) {
                if($info['share_user']==$v['id']){
                    $share_name= isset($v['nickname']) ?$v['nickname']:"";
                }
                if($info['to_user']==$v['id']){
                    $to_name= isset($v['nickname']) ?$v['nickname']:"";
                }
            }
        }
        $info['to_group']==0 ? $info['to_group']='':"";
        $info['to_user']==0 ? $info['to_user']='':"";
        $togroup= $info['to_group']!="" ?Db::name("role_group")->where("id","=",$info["to_group"])->find()
            :['group_name'=>""];
        $info['share_user_name']=$share_name;
        $info['to_user_name'] = $to_name;
        $info['to_group_name'] = $togroup['group_name'];
        return   app_show(0,"获取成功",$info);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function status()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(1001,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $id = isset($post['id']) ? intval($post['id']):"";
        if($id==""){
            return error_show(1002,"参数id 不能为空");
        }
        $info =  Db::name("role_share")->where([["id","=",$id],["is_del","=",0]])->find();
        if(!$info){
            return error_show(1002,"未找到对应数据");
        }
        $status =  isset($post['status']) && $post['status']!==""? intval($post['status']):"";
        if($status===""){
            return error_show(1002,"参数status 不能为空");
        }
        if(!in_array($status,[0,1])){
            return error_show(1002,"参数status 无效");
        }
        $item=$info['status'];
        $info['status']=$status;
        $info['updatetime']=date("Y-m-d H:i:s");
        $msg = $status==1?"启用":"禁用";
        $update = Db::name("role_share")->save($info);
        $st = ["order_code"=>$id,"status"=>$item,"action_remark"=>'',"action_type"=>"edit"];
        ActionLog::logAdd($token,$st,"role_share",$info['status'],$st);
        return  $update? app_show(0,"{$msg}成功"):error_show(1004,"{$msg}失败");
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete()
    {
        $post  =$this->request->post();
        $token = isset($post['token']) ? trim($post['token']) : "";
        if($token==""){
            return error_show(1001,'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if(!empty($effetc) && $effetc['code']!=0){
            return error_show($effetc['code'],$effetc['message']);
        }
        $id = isset($post['id']) ? intval($post['id']):"";
        if($id==""){
            return error_show(1002,"参数id 不能为空");
        }
        $info =  Db::name("role_share")->where([["id","=",$id],["is_del","=",0]])->find();
        if(!$info){
            return error_show(1002,"未找到对应数据");
        }
        $teme = $info['status'];
        $info["status"]=0;
        $info["is_del"]=1;
        $info["updatetime"]=date("Y-m-d H:i:s");
        $update = Db::name("role_share")->save($info);
        $st = ["order_code"=>$id,"status"=> $teme,"action_remark"=>'',"action_type"=>"delete"];
        ActionLog::logAdd($token,$st,"role_share",$info['status'],$st);
        return  $update? app_show(0,"删除成功"):error_show(1004,"删除失败");
    }
}