<?php
/**
 * 人员管理
 * 人员管理基础操作
 * @author DouBin
 * @Date: 2021/07/14
 * @Time: 下午13:50
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Models\Orders;
use BlueCity\Core\Service\Service;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Models\Bmmc;
use App\Models\Pt;
use App\Models\Admin;
use App\Models\AdminInfor;
use Maatwebsite\Excel\Facades\Excel;
use phpDocumentor\Reflection\Types\Integer;
use BlueCity\Core\Inc\ErrorInc;

class AdminsService extends Service{
   /**|--------------------------------------------------------------------
     * @name 导出数据表格
     * @param array $admin 用户信息
     * @param array $bmmc 部门权限列表
     * @return \Illuminate\Http\JsonResponse
     * |--------------------------------------------------------------------
     */
    public static function creactExcel ( $admin , $bmmc ){
    	foreach ($admin as $kq=>$vq){
            foreach($bmmc as $kk=>$vv){
                if($vv['id'] == $vq['admin_groupnew']){
                    $admin[$kq]['bmmc_name'] = $vv['bmmc_name'];
                }
            }
            if ($vq['enable'] == '1'){//账号状态
                $admin[$kq]['enable'] = "开启";
            }else{
                $admin[$kq]['enable'] = "停用";
            }
            $admin[$kq]['phone'] = $vq['admininfor']['phone'];
            $admin[$kq]['pt_name'] = $vq['pt']['pt_name'];
        }

        //$extent = iconv('utf-8', 'gbk','人员管理');
        $name = "admins".date('Ymdhis');
        Excel::create($name,function($excel) use ($admin){
            $excel->sheet('人员列表', function($excel) use ($admin){
                $excel->cell('A1', function($cell) {$cell->setValue('【编号】');   });
                $excel->cell('B1', function($cell) {$cell->setValue('【登录名】');   });
                $excel->cell('C1', function($cell) {$cell->setValue('【姓名】');   });
                $excel->cell('D1', function($cell) {$cell->setValue('【电话】');   });
                $excel->cell('E1', function($cell) {$cell->setValue('【所属部门】');   });
                $excel->cell('F1', function($cell) {$cell->setValue('【默认平台】');   });
                $excel->cell('G1', function($cell) {$cell->setValue('【账号状态】');   });

                foreach ($admin as $key => $value) {
                    $i= $key+2;
                    $excel->cell('A'.$i, $value['id']);
                    $excel->cell('B'.$i, $value['admin_acc']);
                    $excel->cell('C'.$i, $value['admin_name']);
                    $excel->cell('D'.$i, $value['phone']);
                    $excel->cell('E'.$i, $value['bmmc_name']);
                    $excel->cell('F'.$i, $value['pt_name']);
                    $excel->cell('G'.$i, $value['enable']);
                }
            });
        })->save('xls',public_path('excel'));
//        $data = $this->baseurl().'excel/'.$name.'.xls';
    }
    /**|--------------------------------------------------------------------
     * @name 输出列表页信息
     * @param array $paginate 列表信息
     * @param array $Input 请求参数
     * @param array $page_size 每页数量
     * @param array $list 数组化后列表信息
     * @return \Illuminate\Http\JsonResponse
     * |--------------------------------------------------------------------
     */
     public static function listShow ( $paginate , $list , $Input , $page_size){
         $all_button = BmmcService::whereButton($Input['token'],$Input['Pri_id']);
         $export = BmmcService::getTopButton('addAdmins,export','', $all_button);
         $data['button_top'] = $export['button_top']??[];//顶部按钮
         $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        if ($list) {
            $allBmmc = Bmmc::where('id','!=',2)->select('id','bmmc_name')->get();
            foreach ($list as $k=>$v){
	            $button = BmmcService::getListButton(['editAdmins,delAdmins'],$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
                foreach ($allBmmc as $kb=>$vb){
                    if ($vb['id'] == $v['admin_groupnew']){
                        $list[$k]['bmmc_name'] = $vb['bmmc_name'];
                    }
                }
                if ($v['enable'] == '1'){//账号状态
                    $list[$k]['enable_name'] = "开启";
                }else{
                    $list[$k]['enable_name'] = "停用";
                }
                $list[$k]['phone'] = $v['admininfor']['phone'];
                $list[$k]['qq'] = $v['admininfor']['qq'];
                $list[$k]['accountname'] = $v['admininfor']['accountname'];
                $list[$k]['account'] = $v['admininfor']['account'];
                $list[$k]['opeaccline'] = $v['admininfor']['opeaccline'];
                $mpt_name = Pt::where('id',$v['ptid'])->value('pt_name');
                $list[$k]['pt_name'] = $mpt_name?? '暂无';
                if ($v['ptid']){
                    $list[$k]['ptid'] = (int)$v['ptid'];
                }
                $list[$k]['enable'] = (string)$v['enable'];
                if ($v['admin_pt_id']){
                    $admin_pt_id = explode(',',$v['admin_pt_id']);
                    for($i=0;$i<count($admin_pt_id);$i++)
                    {
                        $admin_pt_id[$i] = intval($admin_pt_id[$i]);
                    }
                    $list[$k]['admin_pt_id'] = $admin_pt_id;
                }else{
                    $list[$k]['admin_pt_id'] = '';
                }
                unset($list[$k]['admininfor']);

            }

            $data['list'] = $list;
            $data['page'] =[
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return array('code'=>1,'data'=>$data,'msg'=>'成功');
        } else {

            $data['page'] =[
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            $data['list'] = [];
            return array('code'=>ErrorInc::DATA_EMPTY,'data'=>$data,'msg'=>'暂无数据');
        }
 	}

 	/**|---------------------------------------------------------------------------------
 	 * @name 根据单条指定条件获取数据信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param string $type 查询类型
 	 * @retrun /multitype:array
 	 * @author dou 2021/9/2 18:40
 	 * |---------------------------------------------------------------------------------
 	*/
    public static function getAdminsBy ($key, $value, $select = [] , $type = 'get'){
        $db = new Admin();
        if($key == 'id'){
            $type = 'first';
        }
        if($type == 'first'){
            if(count($select) == 1){
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }
 	/**
     * 获取订单列表
     * @param sring $type 查询类型
     * @param array $params where条件
     * @param array $select 查询字段
     * @param array $orderby 排序规则
     * @return array|mixed
     */
    public static function getAdmins( $params , $select = [] , $orderby = [] , $type = 'get' )
    {
	    $db = new Admin();
     	$list = CommonService::getMysqlData($db,$params,$select,$orderby,$type);
        return $list;
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取用户信息明细
     * @param int $id admin表id
     * @param int $group 操作人权限
     * @param int $group 操作人权限
     * @retrun multitype:array
     * @author dou 2021/8/14 11:38
     * |---------------------------------------------------------------------------------
    */
 	public static function getAdminDetail ( $id , $group , $company_id ){
 	    /*---------------------------------获取admin用户主表信息开始----------------------------------------------*/
        $db = new Admin();
        $adminselect = ['id','admin_acc','admin_name','company_name','ad_brand','ad_project'];
        $list = CommonService::getMysqlData($db,['id'=>$id],$adminselect,[],'first');
        /*---------------------------------获取admin用户主表信息结束----------------------------------------------*/
        $day = date("Y-m-d H:i:s");
        $day1 = date("Y-m-d",strtotime("+1 day",strtotime($day)));
        $day2 = date("Y-m-d",strtotime("-1 month",strtotime($day)));
        $dayNum = Orders::where("ser_id",$id)->where("is_delete",2)->whereRaw("create_time between '".$day."' and '".$day1."'")->count();
        $monthNum = Orders::where("ser_id",$id)->where("is_delete",2)->whereRaw("create_time between '".$day2."' and '".$day1."'")->count();
        /*---------------------------------获取admininfor用户信息表数据开始----------------------------------------------*/
        $infordb = new AdminInfor();
        if(in_array($group, [7,79])){
            $inforselect = ['phone','qq','email','admin_address','service_name','accountname','account','opeaccline','company_des','admin_province','admin_city','admin_county','admin_dressi','head_phone','recom_amount'];
        }else{
            $inforselect = ['phone','qq','email','admin_address','company_des','admin_province','admin_city','admin_county','admin_dressi','head_phone','recom_amount'];
        }
        $admin_infor = CommonService::getMysqlData($infordb,['admin_id'=>$id],$inforselect,[],'first');
       /*------------------------------------------获取商品对应品牌销量开始-----------------------------------------------*/
        $brandnum = OrderListService::getServiceGoodNum(['gs_bid'],['gs_bid'],$id);
        if($brandnum){
            $brandnum = CommonService::jointArrayKey($brandnum, 'gs_bid');
        }
        /*------------------------------------------获取商品对应品牌销量结束-----------------------------------------------*/
        /*---------------------------------获取admininfor用户信息表数据结束----------------------------------------------*/
        if($list){
            $showdata = array_merge($adminselect,$inforselect);//生成当前用户可展示字段信息
            //默认返回的所有数据为空值
            $data = [];
            foreach($showdata as $k => $v){
                $data[$v] = '';
            }
            $data['daynum'] = $dayNum;
            $data['monthnum'] = $monthNum;
            $data['brand_name'] = '';
            $data['project_name'] = '';
            //开始赋值用户主编信息
            foreach($list as $k => $v){
                if($k == 'ad_project'){
                    $category = CategoryService::getAll([] , 'cd_id');
                    $project = trim($v);
                    $project = explode(',', $project);
                    $prodata = [];
                    foreach($project as $key=> $value){
                        if(isset($category[$value]['cd_pname'])){
                            $cd_pname['id'] = $value;
                            $cd_pname['name'] = $category[$value]['cd_pname'];
                            $prodata[] = $cd_pname;
                        }
                    }
                    $data['project_name'] = $prodata;
                }
                if($k == 'ad_brand'){
                    $pjbrand = PjBrandsService::getAll([] , 'id');
                    $pjbrands = CommonService::arrayFilterFieldValue($pjbrand, [['company_id'=>$company_id]]);
                    $bradata = [];
                    if(!$pjbrands) {
                        $brand = trim($v);
                        $brand = explode(',', $brand);
                        foreach($brand as $key => $value){
                            if(isset($pjbrand[$value]['brand_name'])){
                                $brand_name['id'] = $value;
                                $brand_name['name'] = $pjbrand[$value]['brand_name'];
                                $brand_name['sellnum'] = $brandnum[$value]['num']??0;
                                $bradata[] = $brand_name;
                            }
                        }
                    }else {
                        foreach ($pjbrands as $key => $value) {
                            $brand_name['id'] = $value['id'];
                            $brand_name['name'] = $value['brand_name'];
                            $brand_name['sellnum'] = $brandnum[$value['id']]['num'] ?? 0;
                            $bradata[] = $brand_name;
                        }
                    }
                    $data['brand_name'] = $bradata;
                }
                $data[$k] = $v;
            }
            //开始判定
            if($admin_infor){
                foreach($admin_infor as $k => $v){
                    if($k == 'phone' && $group != 7){
                        $v = substr_replace($v,'****',3,4);
                    }
                    $data[$k] = $v;
                }
            }
            return $data;
        }else{
            return false;
        }
 	}
}
