<?php

namespace App\Http\Controllers\User;

use App\Models\Bmmc;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use DB;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\Pt;
use App\Models\AdminAddress;
use App\Services\CommonService;
use App\Services\BmmcService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\AdminsService;
use App\Http\Controllers\BaseController;
use Validator;
use Excel;

/**
 * Class AdminsController 人员管理
 * @package App\Http\Controllers\Admin
 */
class AdminsController extends BaseController
{
    /**|--------------------------------------------------------------------
     * @name 列表页
     * @param admin_acc   登录名
     * @param admin_name  姓名
     * @param phone       手机号
     * @param ptid        平台id
     * @param enable      账号状态 1:启用; 2:停用;
     * @param admin_groupnew 所属部门
     * @param page        页数
     * @return \Illuminate\Http\JsonResponse
     * |--------------------------------------------------------------------
     */
    public function index(Request $request)
    {
        $Input = $request->all();
        $session = $request->get('session_token');
        $page_size = (int)$request->input('page_size',15);
        $Db = Admin::whereHas('admininfor',function($query)use($Input){
            if (isset($Input['phone'])){
                $query->where('phone','like','%'.$Input['phone'].'%');
            }
        })->with('admininfor');
        if ($request->filled('admin_acc')) {//登录名
            $Db = $Db->where('admin_acc','like','%'.$Input['admin_acc'].'%');
        }
        if ($request->filled('admin_name')) {//姓名
            $Db = $Db->where('admin_name','like','%'.$Input['admin_name'].'%');
        }
        if ($request->filled('ptid')) {//平台
            $Db = $Db->where('ptid',$Input['ptid']);
        }
        if ($request->filled('enable')) {//账号状态
            $Db = $Db->where('enable',$Input['enable']);
        }
        if ($request->filled('admin_groupnew')) {//所属部门
            $Db = $Db->where('admin_groupnew',$Input['admin_groupnew']);
        }
        $info = Bmmc::whereRaw("FIND_IN_SET('".$session['admin_groupnew']."',bmmc_pids)")->select('id')->get();
        if (!$info->isEmpty()){
            $ids = [];
            foreach ($info as $k=>$v){
                $ids[] = $v['id'];
            }
        }else{
            $ids = [];
        }
        if ($session['admin_groupnew'] == 7){//管理员可以看全部
            $Db = $Db->where('admin_groupnew','!=',2);
        }else{//其他只能看到除自己所属部门的成员
            $Db = $Db->where('admin_groupnew','!=',2)->whereIn('admin_groupnew',$ids)->where('id','!=',$session['id']);
            if ($session['admin_groupnew'] != 8) {//管理员可以看全部
                $Db = $Db->where('company_id', $session['company_id']);
            }else{
                $Db = $Db->whereIn('company_id', $session['all_companys']);
            }
        }
        $count = $Db->count();


        /**-------------------------------导出excel------------------------------------------**/
        if($request->input('is_excel') == 1){
            $cellData = $Db->select('id','admin_acc','admin_name','admin_groupnew','enable','ptid','admin_pt_id','admin_password')->orderBy('id', 'DESC')->get();
            $AllBmmc = Bmmc::where('id','!=',2)->select('id','bmmc_name')->get();
            AdminsService::creactExcel($cellData,$AllBmmc);
            return $this->success('导出成功', []);
        }

        /**-------------------------------------------------------------------------**/
        $paginate = $Db->select('id','admin_acc','admin_name','admin_groupnew','enable','ptid','admin_pt_id','admin_password','company_id')->orderBy('id', 'DESC')->paginate($page_size);
     	$list = self::dataToArray($paginate->items());
        $list=AdminsService::listShow($paginate,$list,$Input,$page_size);
        if($list['code']=='1'){
	        return $this->success($list['msg'], $list['data']);
        }else{
	        return $this->error($list['msg'] , $list['code'] , $list['data']);
        }
    }
    /**|----------------------------------------------------------------------------------
     * @name 添加成员
     * @param admin_acc      登录名
     * @param admin_password 登录密码
     * @param enable         是否启用
     * @param admin_name     姓名
     * @param admin_groupnew    所属部门
     * @param phone          手机号
     * @param qq             QQ
     * @param admin_pt_id    可见平台(array)
     * @param ptid    默认平台
     * @param ad_brand    可操作品牌
     * @return \Illuminate\Http\JsonResponse
     * |----------------------------------------------------------------------------------
     */
    public function addAdmins (Request $request)
    {
        $message = [
            'admin_acc.required'=> '登录名不能为空',
            'admin_acc.unique'=> '登录名已存在',
            'admin_password.required'=> '登录密码不能为空',
            'admin_password.max'=> '登录密码长度不能超过16个字符',
            'admin_password.min'=> '登录密码长度不得小于6个字符',
            'admin_name.required'=> '姓名不能为空',
            'admin_groupnew.required'=> '所属部门不能为空',
            //'admin_pt_id.required'=> '平台不能为空',
           // 'admin_pt_id.array'=> '平台格式错误',
            'enable.required'=> '停用状态必选',
        ];
        $rules =[
            'admin_acc' =>'required|unique:admin,admin_acc',
            'admin_password'=>'required|max:16|min:6',
            'admin_name'=>'required',
            'admin_groupnew'=>'required',
          //  'admin_pt_id'=> 'required|array',
            'enable'=> 'required',
        ];
        $Validator = Validator::make($request->all(),$rules,$message);
        if($Validator->fails()){
        	$error = CommonService::validatorToString($Validator);
	        return $this->error($error, ErrorInc::FAILED_PARAM, []);
        }

        $admins['admin_acc'] = $this->trimall($request->input('admin_acc'));//登录名
        $admins['admin_password'] = md5($request->input('admin_password'));//密码
        $admins['enable'] = $request->input('enable');//是否启用
        $admins['admin_name'] = $request->input('admin_name');//姓名
        $admins['admin_groupnew'] = $request->input('admin_groupnew');//所属部门
        $admins['admin_group'] = $admins['admin_groupnew'];
        $admins['ad_brand'] = $request->input('ad_brand');//可查看品牌


        if($request->filled('company_id')){
            $admins['company_id'] = $request->input('company_id');
        }else{
            $admins['company_id'] = $request->get('session_token')['company_id'];
        }

        if($request->input('admin_pt_id')){
            $admins['admin_pt_id'] = implode(",",$request->input('admin_pt_id'));//可见平台
            if($request->filled('company_id')){
                $c_pts = Pt::where('company_id',$request->input('company_id'))->pluck('id')->toarray();
               $ptids = array_unique(array_intersect($request->input('admin_pt_id'),$c_pts));
               $admins['admin_pt_id'] = implode(",",$ptids);
            }

        }else{
            $admins['admin_pt_id'] = 0;
        }

        if ($request->filled('perso_nal')){
            $admins['perso_nal'] = implode(",",$request->input('perso_nal'));//个人可操作权限
        }
        if ($request->filled('ptid')){
            $admins['ptid'] = $request->input('ptid');//默认平台
        }

        $find_data  = DB::table('admin')
            ->where('company_id', $admins['company_id'])
            ->where('admin_groupnew', "!=" ,2)
            ->count();
        if ($find_data >= 5) {
            return $this->error('添加数量超出限制', ErrorInc::MYSQL_FAILED, []);
        }

        $post['phone'] = $request->input('phone');//电话
        $post['qq'] = $request->input('qq');//QQ
		DB::beginTransaction();


       $insRes = Admin::insertGetId($admins);
       $post['admin_id'] = $insRes;
       $res = AdminInfor::insert($post);
        if ($res && $insRes){
	        DB::commit();
            $this->insertingLog('添加，','','添加人员：'.$request->input('admin_acc'),'人员管理',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('添加成功', []);
        }else{
	        DB::rollback();
            return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
        }
    }



    /**|----------------------------------------------------------------------------
     * @name 编辑个人信息
     * @param type                  1:编辑展示; 2:编辑动作
     * @param id                    人员id号
     * @param admin_acc             登录名
     * @param admin_password        登录密码
     * @param password_confirmation 确认密码
     * @param enable                是否启用
     * @param admin_name            姓名
     * @param admin_groupnew           所属部门
     * @param phone                 手机号
     * @param qq                    QQ
     * @param ad_brand    可操作品牌
     * @return \Illuminate\Http\JsonResponse
     * |----------------------------------------------------------------------------
     */
    public function editAdmins (Request $request)
    {
        if (!$request->filled('id')){
	        return $this->error('数据编号不能为空', ErrorInc::INVALID_PARAM, []);
        }
        $id = $request->input('id');
        $message = [
            'admin_acc.required'=> '登录名不能为空',
            'admin_acc.unique'=> '登录名已存在',
            'admin_name.required'=> '姓名不能为空',
            'admin_groupnew.required'=> '所属部门不能为空',
            'id.required'=> '数据编号不能为空',
        ];
        $rules =[
            'admin_acc' =>'required|unique:admin,admin_acc,'.$id,
            'admin_name'=>'required',
            'admin_groupnew'=>'required',
            'id'=>'required',
        ];
        $id = $request->input('id');
        $Validator = Validator::make($request->all(),$rules,$message);
        if($Validator->fails()){
            $error = CommonService::validatorToString($Validator);
        	return $this->error($error, ErrorInc::FAILED_PARAM, []);
        }
        if ($request->filled('admin_password') && $request->filled('admin_password_confirmation')){
            $mess = [
                'admin_acc.required'=> '登录名不能为空',
                'admin_acc.unique'=> '登录名已存在',
                'admin_password.confirmed'=> '两次密码不一致',
            ];
            $rul =[
                'admin_password' =>'max|:16|min:6',
                'admin_password' =>'confirmed',
                'admin_password_confirmation'=>'required',
            ];
            $Validator = Validator::make($request->all(),$rul,$mess);
            if($Validator->fails()){
                $error = CommonService::validatorToString($Validator);
        		return $this->error($error, ErrorInc::FAILED_PARAM, []);
            }

        }
        $adArr['admin_acc'] = $this->trimall($request->input('admin_acc'));//登录名
        if ($request->input('admin_password')){
            $adArr['admin_password'] = md5($request->input('admin_password'));
            $infoArr['back_pass']=$request->input('admin_password');
        }
        $adArr['enable'] = $request->input('enable');//是否启用
        $adArr['admin_name'] = $request->input('admin_name');//姓名
        $adArr['admin_groupnew']=$request->input('admin_groupnew');//所属部门

        if($request->filled('company_id')){
            $adArr['company_id'] = $request->input('company_id');
        }else{
            $adArr['company_id'] = $request->get('session_token')['company_id'];
        }

        if($request->input('admin_pt_id')){
            $adArr['admin_pt_id'] = implode(",",$request->input('admin_pt_id'));//可见平台
            if($request->filled('company_id')){
                $c_pts = Pt::where('company_id',$adArr['company_id'])->pluck('id')->toarray();
                $ptids = array_unique(array_intersect($request->input('admin_pt_id'),$c_pts));
                $adArr['admin_pt_id'] = implode(",",$ptids);
            }

        }else{
            $adArr['admin_pt_id'] = 0;
        }
       // $adArr['admin_pt_id']=implode(",",$request->input('admin_pt_id'));//可见平台


        if ($request->filled('perso_nal')){
            $adArr['perso_nal'] = implode(",",$request->input('perso_nal'));//个人可操作权限
        }
        $adArr['ptid'] = $request->input('ptid');//默认平台
        $adArr['ad_brand'] = $request->input('ad_brand');//可查看品牌
        $infoArr['phone'] = $request->input('phone');//电话
        $infoArr['qq'] = $request->input('qq');//QQ
        DB::beginTransaction();
        $rest = Admin::where('id',$request->input('id'))->update($adArr);
        $restt = AdminInfor::where('admin_id',$request->input('id'))->update($infoArr);
        if ($rest || $restt){
            DB::commit();
            Db::table('admin_address')->where('admin_id',$request->input('id'))->delete();
            $content = $request->input('admin_acc')."成员";
            $this->insertingLog('编辑，','',$content,'人员管理',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('操作成功', []);
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
        }
    }
    // 删除空格
    public function trimall($str){
        $is_str=array(" ","　","\t","\n","\r");
        $is_str_er=array("","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取编辑前信息
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/6 17:05
     * |---------------------------------------------------------------------------------
    */
    public function beforEdit ( Request $request ){
        if(!$request->filled('id')){
            return $this->error('缺少数据编号', ErrorInc::MYSQL_FAILED, []);exit;
        }
        $ptId = AdminsService::getAdminsBy('id', $request->input("id"),['admin_pt_id']);
        if($ptId){
            $pt = PlatformService::getAll();
            $ptId = trim($ptId,',');
            $pt = CommonService::arrayFilterFieldValue($pt,array(array('id'=>explode(',',$ptId))));
            if($pt){
                $cd_ids = array_column($pt, 'cd_ids');
                $cd_ids = implode(',', $cd_ids);
                $cd_ids = explode(',', $cd_ids);
                $cd_ids = array_unique($cd_ids);
                $cd_id = [];
                foreach($cd_ids as $k => $v){
                    if($v != ''){
                        $cd_id[] = (int)$v;
                    }
                }
                return $this->success('操作成功', $cd_id);
            }else{
                return $this->success('操作成功', []);
            }
        }else{
            return $this->success('操作成功', []);
        }
    }

}
