<?php

/**
 * 员工信息接口
 */
namespace app\api\controller\v1\common;
use app\api\exception\DbLinkException;
use app\api\exception\StaffIsNotFoundException;
use app\api\validate\IdMustBeIntValidate;
use think\Db;

class Staff
{
    /**
     * 接口一：需要获取登陆人信息的接口 返回值： id name 工号 部门id 角色id（多个的话，逗号分隔）
     */
    public function getCurrentStaff(){

        (new IdMustBeIntValidate())->verify();
         $id = request()->get('id');
        //如果不是超级管理员
        $staff = Db::table('staff')
            ->field('staff.id,name,d_id,iden_id,si.title as iden_name')
            ->leftJoin(['staff_identity'=>'si'],'si.id = staff.iden_id')
            ->where('staff.id','=',$id)
            ->find();
        if(!$staff)
            throw new StaffIsNotFoundException;

        $staff_roles = Db::table('staff_role')->where('staff_id', '=', $staff['id'])->column('role_id');
        $staff['roles'] = implode(',',$staff_roles);

        return json([
            'code' => 200,
            'message' => 'ok',
            'data' => $staff
        ]);
    }

    //获取员工列表信息
    public function getStaffs(){
        $staffs = Db::table('staff')
            ->field('staff.id,name,d_id,iden_id,si.title as iden_name')
            ->leftJoin(['staff_identity'=>'si'],'si.id = staff.iden_id')
            ->select();

        if(!$staffs){
            throw new DbLinkException;
        }

        foreach ($staffs as $k => $v){
            //获取角色信息
            $staff_roles = Db::table('staff_role')->where('staff_id', '=', $v['id'])->column('role_id');
            if(is_array($staff_roles) && count($staff_roles) > 0){
                $roles = implode(',',$staff_roles);
            } else {
                $roles = $staff_roles ?: '';
            }
            $staffs[$k]['roles'] = $roles;
        }

        return json([
            'code' => 200,
            'message' => 'ok',
            'data' => $staffs
        ]);
    }

    public function getIdentities(){
        $data = Db::table('staff_identity')->column('id,title,level');
        if(!$data){
            throw new DbLinkException;
        }
        return json([
            'code' => 200,
            'message' => 'ok',
            'data' => $data
        ]);
    }
}