<?php

namespace App\Http\Controllers\Api\SystemsManage;

use App\Models\BasicManagement\Admin;
use App\Services\CommonService;
use App\Services\Shop\ShopService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyEmployeeListController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use \PhpOffice\PhpSpreadsheet\IOFactory;

// 基础管理 -- 员工列表
class EmployeeListController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $page_size = $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('admin_shop_role as asr')
            ->leftJoin('admin', 'asr.adm_id', '=', 'admin.adm_id')
            ->leftJoin('role', 'role.rol_id', '=', 'asr.role_id')
            ->leftJoin('wash_grade_level as grle', 'grle.grle_id', '=', 'asr.adm_grle_id')
            ->where('asr.shop_cid', $user_info->adm_cid)
            ->whereIn('admin.adm_type', [1, 3])
            ->where('create_source', 1)
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_phone'])) {
                    $query->where('admin.adm_phone', 'like', '%' . $search_data['adm_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_account'])) {
                    $query->where('admin.adm_account', 'like', '%' . $search_data['adm_account'] . '%');
                }
            })
            ->where(function ($query) use ($user_info) {
                if (!empty($user_info->shop_superior_id)) {//分店 
                    $query->where('asr.create_source', 1);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('admin.adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['rol_id'])) {
                    $query->where('asr.role_id', $search_data['rol_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_role_applet'])) {
                    $query->where('admin.adm_role_applet', $search_data['adm_role_applet']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_state'])) {
                    $query->where('asr.adm_state', $search_data['adm_state']);
                }
            })
            ->select('admin.adm_id', 'admin.adm_phone', 'admin.adm_account', 'admin.adm_name', 'asr.adm_state', 'rol_name', 'asr.role_id', 'asr.adm_shop_leave as adm_leave', 'adm_role_applet', 'grle_name', 'grle_grpr_id', 'create_source', 'login_bind_shop', 'shop_id', 'adm_open_id', 'asr.adm_grle_id')
            ->orderBy('admin.adm_id', 'desc')
            ->paginate($page_size);

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_button){
            foreach ($list_button as $b_k => $b_v){
                if($b_v['pri_id'] == 33){
                    $list_button[$b_k]['pri_method_name'] = '在职';
                }
                if($b_v['pri_id'] == 34){
                    $list_button[$b_k]['pri_method_name'] = '离职';
                }
            }
        }
        //获取状态名称
        $status_names = self::getStatusName(true);
        if (!empty($data_info['data'])) {
            $data = CommonService::dataToArray($data_info['data']);
            $data = array_column($data, 'grle_grpr_id');
            $wash_grade_professional = DB::table('wash_grade_professional')->whereIn('grpr_id', $data)->pluck('grpr_name','grpr_id');
            $adm_role_applet = []; //小程序角色id
            foreach ($data_info['data'] as $key => $value) {
                if (isset($value->adm_role_applet)) { //小程序角色id
                    $adm_role_applet[] = $value->adm_role_applet;
                }
                $data_info['data'][$key]->adm_state_name = $status_names[$value->adm_state];
                $data_info['data'][$key]->grpr_name = $wash_grade_professional[$value->grle_grpr_id]??'';
                $data_info['data'][$key]->grle_name = $wash_grade_professional[$value->grle_grpr_id]??'';
                //员工的可操作按钮
                if($value->adm_leave == 1){
                    $buttonData = array();
                }else{
                    $buttonData = array('edit');
                }
                if(in_array($value->adm_state, [1])){
                    $buttonData[] = 'stop';
                }elseif (in_array($value->adm_state, [2])) {
                    $buttonData[] = 'start';
                }
                // if ($value->adm_open_id) {
                //     $buttonData[] = 'unbindWx';
                // }
                $button = CommonService::getListButton($buttonData,$list_button);
                $data_info['data'][$key]->button_one = $button['button_one']??[];
                $data_info['data'][$key]->button_two = $button['button_two']??[];
                $data_info['data'][$key]->button_three = $button['button_three']??[];
            }
            if (!empty($adm_role_applet)) { //小程序角色id
                $role = DB::table('role')->whereIn('rol_id', $adm_role_applet)->pluck('rol_name', 'rol_id')->toArray();
                foreach ($data_info['data'] as $key => $value) {
                    $data_info['data'][$key]->adm_role_applet_name = isset($role[$value->adm_role_applet]) ? $role[$value->adm_role_applet] : '';
                }
            }
        }

        //顶部状态栏
        $wheres['shop_cid'] = $user_info->adm_cid;
        $wheres['shop_id'] = $user_info->adm_shop_id;
        $data_info['showcount'] = self::getStatusBar($wheres);
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info, 'list_button' => $list_button]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据', 'list_button' => $list_button]);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取顶部状态栏
     * @param array $where 查询条件
     * @retrun /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusBar ($where){
        $showcount = [
            ['showname' => "在职", 'shownum' => '0','status'=>1],
            ['showname' => "离职", 'shownum' => '0','status'=>2]
        ];
        foreach( $showcount as $k => $v ){
            $showcount[$k]['shownum'] = self::getStatusNum($v['status'],$where);
        }
        return $showcount;
    }

    /**
     * 获取指定状态数量
     * @param string $status 状态栏参数
     * @param array $where 查询条件
     * @return /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     */
    public static function getStatusNum ( $status,$where){
        if(in_array($status,[1,2])){
            $db = DB::table('admin_shop_role as asr')
                ->leftJoin('admin', 'admin.adm_id', '=', 'asr.adm_id')
                ->whereIn('adm_type', [1,3]);
            $where['faster_asr.adm_state'] = $status;
            $where['create_source'] = 1;
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }

    /**
     * @name 获取状态name
     * @param false $type
     * @return array
     * @author du
     * @date 2023/6/5
     * @Time: 13:49
     */
    public static function getStatusName ( $type = false ){
        $data = [['adm_state'=>1,'name'=>'在职'],['adm_state'=>2,'name'=>'离职']];

        if($type){
            $data = array_column($data, 'name','adm_state');
        }
        return $data;
    }

    // 新增
    public function add(Request $request)
    {
        if (empty($request['adm_role'])) { //角色id
            $request->offsetSet('adm_role', 0);
        }
        if (empty($request['adm_role_applet'])) { //小程序角色id
            $request->offsetSet('adm_role_applet', 0);
        }

        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误']);
        }

        // 判断新增员工的类型
        if (empty($request['adm_leave'])) {
            $adm_leave = 2; //普通员工
        } else {
            $adm_leave = $request['adm_leave'];
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        //判断当前门店下的手机号是否存在
        $adminShopRole = DB::table('admin_shop_role')
            ->where('phone', $request['adm_phone'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->first();
        if (!empty($adminShopRole)) {
            if($adminShopRole->create_source ==2){
                $insertAdminShopRoleDataRes = DB::table('admin_shop_role')->where('id', $adminShopRole->id)->update(['create_source'=>1,'role_id'=>$request['adm_role']]);
                if ($insertAdminShopRoleDataRes) {
                    Common::addLog($user_info, getRealIp($request), '员工列表', '新增', '新增员工：' . $request['adm_name'] . '('.$user_info->adm_shop_id.')' . '成功');
                    return response()->json(['code' => 200, 'msg' => 'success', 'data' => '新增员工成功']);
                } else {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '新增员工失败']);
                }
            }else {
                return response()->json(['code' => 500, 'msg' => '员工账号已存在', 'data' => '当前门店下手机号已存在']);
            }
        }

        DB::beginTransaction();

        //判断手机号是否在别的门店创建过
        $adminInfo = DB::table('admin')
            ->where('adm_phone', $request['adm_phone'])
            ->first();
        if(!empty($adminInfo)) {
            //创建过
            $admId = $adminInfo->adm_id;
            $shopCid = $user_info->adm_cid;
            $superiorShopId = $shop_id;
            $shopId = $user_info->adm_shop_id;
            $roleId = $request['adm_role'];
            $phone = $adminInfo->adm_phone;
            $loginShop = 2;
        }else{
            //账号表新增一个账号数据，账号类型为员工
            $admin_add_data = [
                'adm_cid' => $user_info->adm_cid, //所属企业/品牌方id
                'adm_shop_id' =>  $user_info->adm_shop_id, //门店id
                'adm_superior_shop_id' =>  $shop_id, //总店id
                'adm_leave' => $adm_leave, //级别1店长2普通员工3技师4业务员5技师和业务员
                'adm_phone' => $request['adm_phone'], //手机号
                'adm_account' => $request['adm_account'], //用户名（登录账号）
                'adm_password' => md5($request['adm_password'] . 'faster123456'), //登录密码
                'adm_name' => $request['adm_name'], //姓名名称
                'adm_role' => $request['adm_role'], //角色id
                'adm_grle_id' => $request['adm_grle_id'], //职级id
                'adm_creator_id' =>  $user_info->adm_id, //操作人id
                'adm_role_applet' =>  $request['adm_role_applet'], //小程序角色id
            ];
            $admId =  DB::table('admin')->insertGetid($admin_add_data);
            $shopCid = $user_info->adm_cid;
            $superiorShopId = $shop_id;
            $shopId = $user_info->adm_shop_id;
            $roleId = $request['adm_role'];
            $phone = $request['adm_phone'];
            $loginShop = 1;
        }

        //添加账号门店权限关系
        $insertAdminShopRoleData = [
            'adm_id' => $admId,
            'shop_cid' => $shopCid,
            'superior_shop_id' => $superiorShopId,
            'shop_id' => $shopId,
            'role_id' =>  $roleId,
            'adm_grle_id' =>  $request['adm_grle_id'], //职级id
            'adm_shop_leave' => 2,
            'phone' => $phone,
            'login_shop' => $loginShop,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'create_source' => 1, //1自主创建2分店登录账号
            'login_bind_shop' => $request['login_bind_shop'] ? $request['login_bind_shop'] : 2, //是否可以登录分店1是2否
        ];
        $insertAdminShopRoleDataRes = DB::table('admin_shop_role')->insert($insertAdminShopRoleData);

        //门店表，对应门店员工人数增加
        $shop_res = DB::table('shop')
            ->where('shop_id', $user_info->adm_shop_id)
            ->increment('shop_staff_number');

        if ($admId && $shop_res && $insertAdminShopRoleDataRes) {
            DB::commit();
            DB::table('admin_shop_role')->where('adm_id', $admId)->update(['login_shop'=>2,'login_shop_wechat'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $admId)->where('shop_id', $shopId)->update(['login_shop'=>1,'login_shop_wechat'=>1]);
            Common::addLog($user_info, getRealIp($request), '员工列表', '新增', '新增员工：' . $request['adm_name'] . '('.$user_info->adm_shop_id.')' . '成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '新增员工成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '新增员工失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        if (empty($request['adm_role'])) { //角色id
            $request->offsetSet('adm_role', 0);
        }
        if (empty($request['adm_role_applet'])) { //小程序角色id
            $request->offsetSet('adm_role_applet', 0);
        }

        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        //判断当前门店下的手机号是否存在
        $adm_id =  DB::table('admin_shop_role')
            ->where('adm_id', '<>', $request['adm_id'])
            ->where('phone', $request['adm_phone'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->value('adm_id');
        if (!empty($adm_id)) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前门店下手机号已存在']);
        }

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 判断要编辑的账号是不是店长账号
        $find_adm_leave =  DB::table('admin_shop_role')
            ->where('adm_id', $request['adm_id'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->value('adm_shop_leave as adm_leave');
        if ($find_adm_leave == 1) {
            // 判断当前账号是否是店长账号
            $shop_adm_id =  DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_adm_id');
            if ($user_info->adm_id != $shop_adm_id) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '不是店长账号不允许编辑']);
            }
        }

        // 判断新增员工的类型
        if (empty($request['adm_leave'])) {
            $adm_leave = 2; //普通员工
        } else {
            $adm_leave = $request['adm_leave'];
        }
        if ($find_adm_leave == 1) {
            // 店长权限
            $adm_leave = 1;
        }

        // 2 账号表编辑账号数据
//        $admin_edit_data['adm_phone'] = $request['adm_phone']; //手机号
       $admin_edit_data['adm_name'] = $request['adm_name']; //姓名名称
//        $admin_edit_data['adm_leave'] = $adm_leave; //级别1店长2普通员工3技师4业务员5技师和业务员
//        $admin_edit_data['adm_role'] = $request['adm_role']; //角色id
//        $admin_edit_data['adm_creator_id'] = $user_info->adm_id; //操作人id
//        $admin_edit_data['adm_role_applet'] = $request['adm_role_applet']; //小程序角色id
       $admin_edit_data['adm_update_time'] = date('Y-m-d H:i:s');
//        if ($request['adm_password']) {
//            $admin_edit_data['adm_password'] = md5($request['adm_password'] . 'faster123456');
//        }

        DB::beginTransaction();

        // 编辑账号
       $adm_res =  DB::table('admin')
           ->where('adm_id', $request['adm_id'])
           ->update($admin_edit_data);
        // $adm_res = true;
        // 编辑账号门店权限关系
        $updateAdminShopRoleData = [
            'login_bind_shop' => $request['login_bind_shop'] ? $request['login_bind_shop'] : 2,
            'adm_shop_leave' => $adm_leave,
            'role_id' => $request['adm_role'],
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $updateAdminShopRoleDataRes =  DB::table('admin_shop_role')
            ->where('adm_id', $request['adm_id'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->update($updateAdminShopRoleData);
        if ($adm_res && $updateAdminShopRoleDataRes) {
            Common::addLog($user_info, getRealIp($request), '员工列表', '编辑', '编辑员工：' . $request['adm_name'] . '('.$user_info->adm_shop_id.')' . '成功');
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '编辑员工成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '编辑员工失败']);
        }
    }

    // 职级
    public function addGrle(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->addGrleShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 修改职级
        if ($request['type'] == 1) {
            $find_data = DB::table('admin_shop_role as a')
                ->leftJoin('wash_grade_level as grle', 'a.adm_grle_id', '=', 'grle.grle_id')
                ->leftJoin('wash_grade_professional as c', 'grle.grle_grpr_id', '=', 'c.grpr_id')
                ->where('adm_id', $request['adm_id'])
                ->where('shop_id', $user_info->adm_shop_id)
                ->select( 'phone as adm_phone', 'adm_grle_id', 'grle_name', 'grpr_name')
                ->first();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $find_data]);
        }

        // 验证数据
        $error_message = $verify_data->addGrleValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        $update_data['adm_grle_id'] = $request['adm_grle_id']; //职级id
        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
        DB::beginTransaction();
        $adm_res = DB::table('admin')->where('adm_id', $request['adm_id'])->update($update_data);

        // 编辑账号门店权限关系
        $updateAdminShopRoleData = [
            'adm_grle_id' => $request['adm_grle_id'],
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $updateAdminShopRoleDataRes =  DB::table('admin_shop_role')
            ->where('adm_id', $request['adm_id'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->update($updateAdminShopRoleData);

        if ($adm_res && $updateAdminShopRoleDataRes) {
            Common::addLog($user_info, getRealIp($request), '员工列表', '修改职级', '员工：' . $request['adm_name'] . '('.$user_info->adm_shop_id.')' . '修改职级成功');
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '修改职级成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '修改职级失败']);
        }
    }

    // 在职
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (isset($request['shop_id']) && $request['shop_id']) {
            $shop_id = $request['shop_id'];
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        // 查询员工信息
        $find_adm = DB::table('admin_shop_role as asr')
            ->leftJoin('admin', 'admin.adm_id', '=', 'asr.adm_id')
            ->whereIn('asr.adm_id', $request['adm_id'])
            ->where('shop_id', $shop_id)
            ->select('admin.adm_name', 'asr.adm_shop_leave as adm_leave', 'admin.adm_phone', 'admin.adm_id')
            ->get();
        foreach ($find_adm as $key => $value) {
            $adm_name[] = $value->adm_name;
        }
        DB::beginTransaction();
        // 营业
//        $update_data['adm_state'] = 1; //状态1营业2停业
//        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
//        $adm_res = DB::table('admin')->whereIn('adm_id', $request['adm_id'])->update($update_data);
        $adm_res = true;
        // 编辑账号门店权限关系
        $updateAdminShopRoleData = [
            'adm_state' => 1,
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $updateAdminShopRoleDataRes =  DB::table('admin_shop_role')
            ->whereIn('adm_id', $request['adm_id'])
            ->where('shop_id', $shop_id)
            ->update($updateAdminShopRoleData);
        if ($adm_res && $updateAdminShopRoleDataRes) {
            if (config('apisystem.SYNC_STATE')) {
                // 与速电系统同步技师数据
                $system_shop = DB::table('shop_relevance')
                    ->where('shre_shop_id', $shop_id)
                    ->first(['shre_relevance_shop_id', 'shre_state']);
                if (isset($system_shop->shre_state) && $system_shop->shre_state == 2) {
                    foreach ($find_adm as $key => $value) {
                        if ($value->adm_leave == 3 || $value->adm_leave == 5) {
                            $param['id'] = $value->adm_id; //技师id
                            $param['name'] = $value->adm_name; //技师姓名
                            $param['phone'] = $value->adm_phone; //技师手机号
                            $param['store_id'] = $system_shop->shre_relevance_shop_id; //第三方系统的门店id
                            $param['time'] = date('Y-m-d H:i:s');
                            $param['type'] = 1; //1添加编辑2删除
                            $param['token'] = config('apisystem.sd_token');
                            // $url = config('apisystem.sd_server_name') . '/index.php/sync_install_persion';
                            $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/sync_install_persion';
                            $doPost_res = Common::doPost($param, $url);
                            $doPost_res = json_decode($doPost_res);
//                            if (!isset($doPost_res->code) || $doPost_res->code != 200) {
//                                DB::rollBack();
//                                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '失败']);
//                            }
                        }
                    }
                }
            }
            if ($request['shop_id']) {
                Common::addLog($user_info, getRealIp($request), '分店员工列表', '在职', '员工：（' . implode(',', $adm_name) . '）('.$shop_id.')在职成功');
            } else {
                Common::addLog($user_info, getRealIp($request), '员工列表', '在职', '员工：（' . implode(',', $adm_name) . '）('.$user_info->adm_shop_id.')在职成功');
            }
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '在职成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '在职失败']);
        }
    }

    // 离职
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询员工信息
        if (isset($request['shop_id']) && $request['shop_id']) {
            $shop_id = $request['shop_id'];
        } else {
            $shop_id = $user_info->adm_shop_id;
        }
        $find_adm = DB::table('admin_shop_role as asr')
            ->leftJoin('admin', 'admin.adm_id', '=', 'asr.adm_id')
            ->whereIn('asr.adm_id', $request['adm_id'])
            ->where('shop_id', $shop_id)
            ->select('admin.adm_name', 'asr.adm_shop_leave as adm_leave', 'admin.adm_phone', 'admin.adm_id')
            ->get();
        foreach ($find_adm as $key => $value) {
            $adm_name[] = $value->adm_name;
            if ($value->adm_leave == 1) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '店长账号不允许离职']);
            }
        }
        DB::beginTransaction();
        // 离职
//        $update_data['adm_state'] = 2; //状态1营业2停业
//        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
//        $adm_res = DB::table('admin')->whereIn('adm_id', $request['adm_id'])->update($update_data);
        $adm_res = true;
        // 编辑账号门店权限关系
        $updateAdminShopRoleData = [
            'adm_state' => 2,
            'login_shop' => 2,
            'login_shop_wechat' => 2,
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $updateAdminShopRoleDataRes =  DB::table('admin_shop_role')
            ->whereIn('adm_id', $request['adm_id'])
            ->where('shop_id', $shop_id)
            ->update($updateAdminShopRoleData);

        if ($adm_res && $updateAdminShopRoleDataRes) {
            if (config('apisystem.SYNC_STATE')) {
                $system_shop = DB::table('shop_relevance')
                    ->where('shre_shop_id', $shop_id)
                    ->first(['shre_relevance_shop_id', 'shre_state']);
                // 与速电系统同步技师数据
                if (isset($system_shop->shre_state) && $system_shop->shre_state == 2) {
                    foreach ($find_adm as $key => $value) {
                        if ($value->adm_leave == 3 || $value->adm_leave == 5) {
                            $param['id'] = $value->adm_id; //技师id
                            $param['name'] = $value->adm_name; //技师姓名
                            $param['phone'] = $value->adm_phone; //技师手机号
                            $param['store_id'] = $system_shop->shre_relevance_shop_id; //第三方系统的门店id
                            $param['time'] = date('Y-m-d H:i:s');
                            $param['type'] = 2; //1添加编辑2删除
                            $param['token'] = config('apisystem.sd_token');
                            $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/sync_install_persion';
                            $doPost_res = Common::doPost($param, $url);
                            $doPost_res = json_decode($doPost_res);
//                            if (!isset($doPost_res->code) || $doPost_res->code != 200) {
//                                DB::rollBack();
//                                return response()->json(['code' => 500, 'msg' => '同步失败', 'data' => '失败']);
//                            }
                        }
                    }
                }
            }
            if (isset($request['shop_id']) && $request['shop_id']) {
                Common::addLog($user_info, getRealIp($request), '分店员工列表', '离职', '员工：（' . implode(',', $adm_name) . '）('.$shop_id.')离职成功');
            } else {
                Common::addLog($user_info, getRealIp($request), '员工列表', '离职', '员工：（' . implode(',', $adm_name) . '）('.$user_info->adm_shop_id.')离职成功');
            }
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '离职成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '离职失败']);
        }
    }

    // 设置
    public function set(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->setValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 获取页面信息
        if ($request['type'] == 1) {
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->adm_shop_id;
            // 查询门店类型
            $shop_info = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->select('shop_type', 'shop_id', 'shop_store_name')
                ->first();
            // 1. 仓库数据,查询当前账号所属总店或加盟店的固定仓库、移动仓库
            $warehouse = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_shop_id', $shop_id)
                ->where('ware_type', '<>', 2)
                ->select('ware_id', 'ware_name')
                ->get();

            // 3. 员工的设置信息
            $adm_set = DB::table('admin_set')
                ->where('adms_adm_id', $request['adm_id'])
                ->where('adms_shop_id', $user_info->adm_shop_id)
                ->select('adms_shop_id', 'adms_ware_id', 'adms_ware_ids', 'adms_myware_id', 'adms_statistical_data')
                ->first();
            if (empty($adm_set)) {
                $adm_set = [];
            } else {
                $adm_set->adms_ware_id = $adm_set->adms_ware_id ? explode(",", $adm_set->adms_ware_id) : [];
                $adm_set->adms_ware_ids = $adm_set->adms_ware_ids ? explode(",", $adm_set->adms_ware_ids) : [];
                $adm_set->adms_myware_id = $adm_set->adms_myware_id ? explode(",", $adm_set->adms_myware_id) : []; //我的仓库模块及发货、退换的仓库权限
                $adm_set->adms_statistical_data = json_decode($adm_set->adms_statistical_data, true) ?: []; //销售统计模块权限
            }

            // 销售统计的权限设置数据 总计数据字段 is_price 1是表示金额
            // 品牌查询
            $field1 = [
                ["pid" => "1", "id" => "1", "field_title" => "return_num", "field_name" => "退货数量", "show" => "2"],
                ["pid" => "1", "id" => "2", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "1", "id" => "3", "field_title" => "return_sprice", "field_name" => "退款金额", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "4", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "5", "field_title" => "sale_cost", "field_name" => "销售成本", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "6", "field_title" => "return_cost", "field_name" => "退货成本", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "7", "field_title" => "allcost", "field_name" => "成本合计", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "8", "field_title" => "profit", "field_name" => "利润", "show" => "2", "is_price" => "1"],
            ];
            // 销售明细
            $field2 = [
                ["pid" => "2", "id" => "1", "field_title" => "allcost", "field_name" => "成本合计", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "2", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "2", "id" => "3", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"],
            ];
            // 销量排行
            $field3 = [
                ["pid" => "3", "id" => "1", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "3", "id" => "2", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"]
            ];
            // 开单员销量
            $field4 = [
                ["pid" => "4", "id" => "1", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "4", "id" => "2", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"],
                ["pid" => "4", "id" => "3", "field_title" => "return_num", "field_name" => "退货数量", "show" => "2"],
                ["pid" => "4", "id" => "4", "field_title" => "return_sprice", "field_name" => "退款金额", "show" => "2", "is_price" => "1"]
            ];
            // 业务员销量
            $field5 = [
                ["pid" => "5", "id" => "1", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "5", "id" => "2", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"],
                ["pid" => "5", "id" => "3", "field_title" => "return_num", "field_name" => "退货数量", "show" => "2"],
                ["pid" => "5", "id" => "4", "field_title" => "return_sprice", "field_name" => "退款金额", "show" => "2", "is_price" => "1"]
            ];
            // 客户汇总-查看明细
            $field6 = [
                ["pid" => "6", "id" => "1", "field_title" => "allcost", "field_name" => "成本合计", "show" => "2", "is_price" => "1"],
                ["pid" => "6", "id" => "2", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "6", "id" => "3", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"],
            ];
            // 客户汇总
            $field7 = [
                ["pid" => "7", "id" => "1", "field_title" => "allcost", "field_name" => "成本合计", "show" => "2", "is_price" => "1"],
                ["pid" => "7", "id" => "2", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "7", "id" => "3", "field_title" => "profit", "field_name" => "利润", "show" => "2", "is_price" => "1"],
                ["pid" => "7", "id" => "4", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"]
            ];
            // 实时数据
            $field8 = [
                ["pid" => "8", "id" => "1", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "8", "id" => "2", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"]
            ];
            // 服务查询
            $field9 = [
                ["pid" => "9", "id" => "1", "field_title" => "allnum", "field_name" => "数量合计", "show" => "2"],
                ["pid" => "9", "id" => "2", "field_title" => "profits", "field_name" => "销售合计", "show" => "2", "is_price" => "1"]
            ];
            $field10 = [];

            // 列表数据字段
            // 品牌查询
            $list_field1 = [
                ["pid" => "1", "id" => "1", "field_title" => "brand_name", "field_name" => "品牌名称", "show" => "2"],
                // ["pid"=>"2","id"=>"2","field_title"=>"dast_service_type","field_name"=>"买家类型","show"=>"2"],
                ["pid" => "1", "id" => "3", "field_title" => "sale_num", "field_name" => "销售数量", "show" => "2"],
                ["pid" => "1", "id" => "4", "field_title" => "sale_sprice", "field_name" => "销售金额", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "5", "field_title" => "sale_cost", "field_name" => "销售成本", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "6", "field_title" => "return_num", "field_name" => "退货数量", "show" => "2"],
                ["pid" => "1", "id" => "7", "field_title" => "return_sprice", "field_name" => "退货金额", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "8", "field_title" => "return_cost", "field_name" => "退货成本", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "9", "field_title" => "allnum", "field_name" => "实售数量", "show" => "2"],
                ["pid" => "1", "id" => "10", "field_title" => "profits", "field_name" => "营业额", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "11", "field_title" => "allcost", "field_name" => "营业成本", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "12", "field_title" => "direct_accounting_price", "field_name" => "直营核算价", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "13", "field_title" => "profit", "field_name" => "营业利润", "show" => "2", "is_price" => "1"],
                ["pid" => "1", "id" => "14", "field_title" => "profit_margin", "field_name" => "利润率", "show" => "2"],
            ];
            // 销售明细
            $list_field2 = [
                ["pid" => "2", "id" => "1", "field_title" => "dast_order_number", "field_name" => "订单编号", "show" => "2"],
                ["pid" => "2", "id" => "2", "field_title" => "goo_goods_encode", "field_name" => "商品编码", "show" => "2"],
                ["pid" => "2", "id" => "3", "field_title" => "goo_cate_name", "field_name" => "商品品类", "show" => "2"],
                ["pid" => "2", "id" => "4", "field_title" => "goo_name", "field_name" => "商品名称", "show" => "2"],
                ["pid" => "2", "id" => "5", "field_title" => "goo_ampere_hour", "field_name" => "规格", "show" => "2"],
                ["pid" => "2", "id" => "6", "field_title" => "dast_goo_quantity", "field_name" => "数量", "show" => "2"],
                ["pid" => "2", "id" => "7", "field_title" => "goo_unit", "field_name" => "单位", "show" => "2"],
                ["pid" => "2", "id" => "8", "field_title" => "dast_goo_price", "field_name" => "单价", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "9", "field_title" => "allprice", "field_name" => "总额", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "10", "field_title" => "cost", "field_name" => "成本", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "11", "field_title" => "total_cost", "field_name" => "总成本", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "12", "field_title" => "profit", "field_name" => "利润", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "13", "field_title" => "goo_direct_accounting_price", "field_name" => "直营核算价", "show" => "2", "is_price" => "1"],
                ["pid" => "2", "id" => "14", "field_title" => "unit_name", "field_name" => "客户单位", "show" => "2"],
                ["pid" => "2", "id" => "15", "field_title" => "type_name", "field_name" => "客户类型", "show" => "2"],
                ["pid" => "2", "id" => "16", "field_title" => "ware_freight_space", "field_name" => "仓库编码", "show" => "2"],
                ["pid" => "2", "id" => "17", "field_title" => "dast_create_time", "field_name" => "创建时间", "show" => "2"],
                ["pid" => "2", "id" => "18", "field_title" => "service_name", "field_name" => "订单类型", "show" => "2"],
                ["pid" => "2", "id" => "19", "field_title" => "dast_creacor", "field_name" => "开单员", "show" => "2"],
                // ["pid"=>"2","id"=>"8","field_title"=>"attribute","field_name"=>"单位","show"=>"2"],
                // ["pid"=>"2","id"=>"9","field_title"=>"dast_service_type","field_name"=>"","show"=>"2"],
                // ["pid"=>"2","id"=>"10","field_title"=>"dast_type","field_name"=>"","show"=>"2"],
                // ["pid"=>"2","id"=>"13","field_title"=>"goo_class","field_name"=>"类型：1自营商品2系统商品","show"=>"2"],
                ["pid" => "2", "id" => "20", "field_title" => "order_reamrks", "field_name" => "备注", "show" => "2"]
            ];
            // 销量排行
            $list_field3 = [
                ["pid" => "3", "id" => "1", "field_title" => "goo_goods_encode", "field_name" => "商品编码", "show" => "2"],
                ["pid" => "3", "id" => "2", "field_title" => "goo_name", "field_name" => "商品名称", "show" => "2"],
                ["pid" => "3", "id" => "3", "field_title" => "goo_cate_name", "field_name" => "商品分类", "show" => "2"],
                ["pid" => "3", "id" => "4", "field_title" => "goo_ampere_hour", "field_name" => "规格", "show" => "2"],
                ["pid" => "3", "id" => "5", "field_title" => "attribute", "field_name" => "单位", "show" => "2"],
                // ["pid"=>"3","id"=>"6","field_title"=>"goo_unit","field_name"=>"单位","show"=>"2"],
                ["pid" => "3", "id" => "6", "field_title" => "quantity", "field_name" => "数量", "show" => "2"],
                ["pid" => "3", "id" => "7", "field_title" => "price", "field_name" => "总额", "show" => "2", "is_price" => "1"],
            ];
            // 开单员销量
            $list_field4 = [
                ["pid" => "4", "id" => "1", "field_title" => "dast_creacor", "field_name" => "开单员", "show" => "2"],
                ["pid" => "4", "id" => "2", "field_title" => "sale_num", "field_name" => "销售数量", "show" => "2"],
                ["pid" => "4", "id" => "3", "field_title" => "sale_sprice", "field_name" => "销售金额", "show" => "2", "is_price" => "1"],
                ["pid" => "4", "id" => "4", "field_title" => "return_num", "field_name" => "退款数量", "show" => "2"],
                ["pid" => "4", "id" => "5", "field_title" => "return_sprice", "field_name" => "退款金额", "show" => "2", "is_price" => "1"],
                ["pid" => "4", "id" => "6", "field_title" => "profits", "field_name" => "纯营业额", "show" => "2", "is_price" => "1"],
            ];
            // 业务员销量
            $list_field5 = [
                ["pid" => "5", "id" => "1", "field_title" => "dast_adm_name", "field_name" => "业务员", "show" => "2"],
                ["pid" => "5", "id" => "2", "field_title" => "sale_num", "field_name" => "销售数量", "show" => "2"],
                ["pid" => "5", "id" => "3", "field_title" => "sale_sprice", "field_name" => "销售金额", "show" => "2", "is_price" => "1"],
                ["pid" => "5", "id" => "4", "field_title" => "return_num", "field_name" => "退款数量", "show" => "2"],
                ["pid" => "5", "id" => "5", "field_title" => "return_sprice", "field_name" => "退款金额", "show" => "2", "is_price" => "1"],
                ["pid" => "5", "id" => "6", "field_title" => "allnum", "field_name" => "实售数量", "show" => "2"],
                ["pid" => "5", "id" => "7", "field_title" => "profits", "field_name" => "纯营业额", "show" => "2", "is_price" => "1"]
            ];
            // 客户汇总-查看明细
            $list_field6 = [
                ["pid" => "6", "id" => "1", "field_title" => "dast_order_number", "field_name" => "订单编号", "show" => "2"],
                ["pid" => "6", "id" => "2", "field_title" => "goo_goods_encode", "field_name" => "商品编码", "show" => "2"],
                ["pid" => "6", "id" => "3", "field_title" => "goo_cate_name", "field_name" => "商品品类", "show" => "2"],
                ["pid" => "6", "id" => "4", "field_title" => "goo_name", "field_name" => "商品名称", "show" => "2"],
                ["pid" => "6", "id" => "5", "field_title" => "goo_ampere_hour", "field_name" => "规格", "show" => "2"],
                ["pid" => "6", "id" => "6", "field_title" => "dast_goo_quantity", "field_name" => "数量", "show" => "2"],
                ["pid" => "6", "id" => "7", "field_title" => "goo_unit", "field_name" => "单位", "show" => "2"],
                ["pid" => "6", "id" => "8", "field_title" => "dast_goo_price", "field_name" => "单价", "show" => "2", "is_price" => "1"],
                ["pid" => "6", "id" => "9", "field_title" => "allprice", "field_name" => "总额", "show" => "2", "is_price" => "1"],
                ["pid" => "6", "id" => "10", "field_title" => "cost", "field_name" => "成本", "show" => "2", "is_price" => "1"],
                ["pid" => "6", "id" => "11", "field_title" => "total_cost", "field_name" => "总成本", "show" => "2", "is_price" => "1"],
                ["pid" => "6", "id" => "12", "field_title" => "profit", "field_name" => "利润", "show" => "2", "is_price" => "1"],
                // ["pid"=>"6","id"=>"13","field_title"=>"goo_direct_accounting_price","field_name"=>"直营核算价","show"=>"2","is_price"=>"1"],
                ["pid" => "6", "id" => "14", "field_title" => "unit_name", "field_name" => "客户单位", "show" => "2"],
                ["pid" => "6", "id" => "15", "field_title" => "type_name", "field_name" => "客户类型", "show" => "2"],
                ["pid" => "6", "id" => "16", "field_title" => "ware_freight_space", "field_name" => "仓库编码", "show" => "2"],
                ["pid" => "6", "id" => "17", "field_title" => "dast_create_time", "field_name" => "创建时间", "show" => "2"],
                ["pid" => "6", "id" => "18", "field_title" => "service_name", "field_name" => "订单类型", "show" => "2"],
                ["pid" => "6", "id" => "19", "field_title" => "dast_creacor", "field_name" => "开单员", "show" => "2"],
                // ["pid"=>"2","id"=>"8","field_title"=>"attribute","field_name"=>"单位","show"=>"2"],
                // ["pid"=>"2","id"=>"9","field_title"=>"dast_service_type","field_name"=>"","show"=>"2"],
                // ["pid"=>"2","id"=>"10","field_title"=>"dast_type","field_name"=>"","show"=>"2"],
                // ["pid"=>"2","id"=>"13","field_title"=>"goo_class","field_name"=>"类型：1自营商品2系统商品","show"=>"2"],
                ["pid" => "2", "id" => "20", "field_title" => "order_reamrks", "field_name" => "备注", "show" => "2"]
            ];
            // 客户汇总
            $list_field7 = [
                ["pid" => "7", "id" => "1", "field_title" => "type_name", "field_name" => "客户类型", "show" => "2"],
                ["pid" => "7", "id" => "2", "field_title" => "dast_client_name", "field_name" => "客户名称", "show" => "2"],
                ["pid" => "7", "id" => "3", "field_title" => "quantity", "field_name" => "数量", "show" => "2"],
                ["pid" => "7", "id" => "4", "field_title" => "price", "field_name" => "销售金额", "show" => "2", "is_price" => "1"],
                ["pid" => "7", "id" => "5", "field_title" => "cost", "field_name" => "销售成本", "show" => "2", "is_price" => "1"],
                ["pid" => "7", "id" => "6", "field_title" => "profit", "field_name" => "销售利润", "show" => "2", "is_price" => "1"],
                ["pid" => "7", "id" => "7", "field_title" => "operate", "field_name" => "操作", "show" => "2"]
            ];
            // 实时数据
            $list_field8 = [
                ["pid" => "8", "id" => "1", "field_title" => "ord_order_number", "field_name" => "订单编号", "show" => "2"],
                ["pid" => "8", "id" => "2", "field_title" => "ord_service_type", "field_name" => "订单类型", "show" => "2"],
                ["pid" => "8", "id" => "3", "field_title" => "goo_goods_encode", "field_name" => "商品编码", "show" => "2"],
                ["pid" => "8", "id" => "4", "field_title" => "goo_name", "field_name" => "商品名称", "show" => "2"],
                ["pid" => "8", "id" => "5", "field_title" => "goo_ampere_hour", "field_name" => "规格", "show" => "2"],
                ["pid" => "8", "id" => "6", "field_title" => "orgo_goo_quantity", "field_name" => "数量", "show" => "2"],
                ["pid" => "8", "id" => "7", "field_title" => "goo_unit", "field_name" => "单位", "show" => "2"],
                ["pid" => "8", "id" => "8", "field_title" => "allprice", "field_name" => "总额", "show" => "2", "is_price" => "1"],
                ["pid" => "8", "id" => "9", "field_title" => "unit_name", "field_name" => "客户单位", "show" => "2"],
                ["pid" => "8", "id" => "10", "field_title" => "type_name", "field_name" => "客户类型", "show" => "2"],
                ["pid" => "8", "id" => "11", "field_title" => "ware_freight_space", "field_name" => "仓库编码", "show" => "2"],
                ["pid" => "8", "id" => "12", "field_title" => "ord_create_time", "field_name" => "创建时间", "show" => "2"],
                ["pid" => "8", "id" => "13", "field_title" => "order_reamrks", "field_name" => "备注", "show" => "2"],
                // ["pid"=>"8","id"=>"8","field_title"=>"attribute","field_name"=>"单位","show"=>"2"],
                // ["pid"=>"8","id"=>"13","field_title"=>"orgo_goo_price","field_name"=>"总额","show"=>"2","is_price"=>"1"],
            ];
            // 服务查询
            $list_field9 = [
                ["pid" => "9", "id" => "1", "field_title" => "dast_order_number", "field_name" => "订单编号", "show" => "2"],
                ["pid" => "9", "id" => "2", "field_title" => "service_name", "field_name" => "订单类型", "show" => "2"],
                ["pid" => "9", "id" => "3", "field_title" => "dast_creacor", "field_name" => "开单员", "show" => "2"],
                ["pid" => "9", "id" => "4", "field_title" => "dast_unit_name", "field_name" => "客户单位", "show" => "2"],
                ["pid" => "9", "id" => "5", "field_title" => "chty_name", "field_name" => "客户类型", "show" => "2"],
                ["pid" => "9", "id" => "6", "field_title" => "dast_sepr_name", "field_name" => "服务项目", "show" => "2"],
                ["pid" => "9", "id" => "7", "field_title" => "dast_goo_price", "field_name" => "服务金额", "show" => "2", "is_price" => "1"],
                ["pid" => "9", "id" => "8", "field_title" => "dast_create_time", "field_name" => "创建日期", "show" => "2"],
                ["pid" => "9", "id" => "9", "field_title" => "order_reamrks", "field_name" => "备注", "show" => "2"],
            ];
            // 拿货占比
            $list_field10 = [
                ["pid" => "10", "id" => "1", "field_title" => "chun_unit_name", "field_name" => "客户单位", "show" => "2"],
                ["pid" => "10", "id" => "2", "field_title" => "sell_amount", "field_name" => "销售数量", "show" => "2"],
                ["pid" => "10", "id" => "3", "field_title" => "renewal_amount", "field_name" => "更换数量", "show" => "2"],
                ["pid" => "10", "id" => "4", "field_title" => "renewal_ratio", "field_name" => "更换占比", "show" => "2"],
                ["pid" => "10", "id" => "5", "field_title" => "deliver_amount", "field_name" => "送货数量", "show" => "2"],
                ["pid" => "10", "id" => "6", "field_title" => "deliver_ratio", "field_name" => "送货占比", "show" => "2"],
            ];
            // 销售统计页面按钮权限字段 field1对应总计项权限，list_field1对应列表项权限
            $statistical_data = [
                ["title" => "品牌查询", "name" => "品牌查询", "checked" => "false", "id" => "1", "count_field" => $field1, "list_field" => $list_field1],
                ["title" => "销售明细", "name" => "销售明细", "checked" => "false", "id" => "2", "count_field" => $field2, "list_field" => $list_field2],
                ["title" => "销量排行", "name" => "销量排行", "checked" => "false", "id" => "3", "count_field" => $field3, "list_field" => $list_field3],
                ["title" => "开单员销量", "name" => "开单员销量", "checked" => "false", "id" => "4", "count_field" => $field4, "list_field" => $list_field4],
                ["title" => "业务员销量", "name" => "业务员销量", "checked" => "false", "id" => "5", "count_field" => $field5, "list_field" => $list_field5],
                ["title" => "查看明细", "name" => "查看明细", "checked" => "false", "id" => "6", "count_field" => $field6, "list_field" => $list_field6],
                ["title" => "客户汇总", "name" => "客户汇总", "checked" => "false", "id" => "7", "count_field" => $field7, "list_field" => $list_field7],
                ["title" => "实时数据", "name" => "实时数据", "checked" => "false", "id" => "8", "count_field" => $field8, "list_field" => $list_field8],
                ["title" => "服务查询", "name" => "服务查询", "checked" => "false", "id" => "9", "count_field" => $field9, "list_field" => $list_field9],
                ["title" => "拿货占比", "name" => "拿货占比", "checked" => "false", "id" => "10", "count_field" => $field10, "list_field" => $list_field10]
            ];
            // 将仓库数据和门店数据合并
            $data['warehouse'] = $warehouse;
            $data['statistical_data'] = $statistical_data; // 销售统计权限数据
            $data['adm_set'] = $adm_set;
            $data['shop_name'] = $shop_info->shop_store_name;
            $data['shop_type'] = $shop_info->shop_type;
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        }

        // 判断admin_set表中是否有 该员工的设置
        $adm_set = DB::table('admin_set')
            ->where('adms_adm_id', $request['adm_id'])
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_id');
        $adms_data['adms_ware_id'] = $request['warehouse'] ? implode(",", $request['warehouse']) : ''; //所绑定的仓库信息
        $adms_data['adms_ware_ids'] = $request['ware_ids'] ? implode(",", $request['ware_ids']) : ''; //仓库操作权限
        $adms_data['adms_myware_id'] = $request['adms_myware_id'] ? implode(",", $request['adms_myware_id']) : ''; //我的仓库-仓库查看及相关操作权限
        $request['statistical_data'] = json_encode($request['statistical_data'], true);
        $adms_data['adms_statistical_data'] = isset($request['statistical_data']) ? $request['statistical_data'] : ''; //销售统计页面查看权限
        $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
        if ($adm_set) {
            // 有该员工的设置编辑
            $adms_res = DB::table('admin_set')
                ->where('adms_id', $adm_set)
                ->update($adms_data);
        } else {
            $adms_data['adms_shop_id'] = $user_info->adm_shop_id; //门店id权限
            // 没有该员工的设置新增
            $adms_data['adms_adm_id'] = $request['adm_id']; //员工id
            $adms_res = DB::table('admin_set')->insert($adms_data);
        }

        if ($adms_res) {
            $adm_name = DB::table('admin')
                ->where('adm_id', $request['adm_id'])
                ->value('adm_name');
            Common::addLog($user_info, getRealIp($request), '员工列表', '设置', $user_info->adm_name . '设置员工：' . $adm_name . '('.$user_info->adm_shop_id.')'.'成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设置成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '设置失败']);
        }
    }

    // 导出
    public function exportadm(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('admin as a')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->leftJoin('wash_grade_level as grle', 'grle.grle_id', '=', 'a.adm_grle_id')
            ->leftJoin('wash_grade_professional as grpr', 'grpr.grpr_id', '=', 'grle.grle_grpr_id')
            ->leftJoin('role as r', 'r.rol_id', '=', 'grle.grle_grpr_id')
            ->where(function ($query) use ($user_info) {
                $query->where('adm_cid', $user_info->adm_cid);
            })
            ->select('adm_account', 'adm_name', 'adm_phone', 'grle_name', 'grpr_name', 'asr.role_id as adm_role')
            ->get()->toArray();
        // ini_set("memory_limit", "1024M");  // 根据电脑配置不够继续增加
        if (!empty($list_data)) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data), true);
            // foreach ($list_data as $key => $value) {
            //     $list_data[$key]['goo_price'] = $value['goo_price'] / 100;
            // }
            $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
            // 创建文件夹
            if (!file_exists($pathName)) {
                mkdir($pathName, 0775, true);
                chmod($pathName, 0775);
            }

            $streamFileRand = time() . rand(10000, 99999) . '.xls';
            // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
            $streamFilename = $pathName . '/' . $streamFileRand;

            $where['action_name'] = '员工表';
            $where['field_name'] = ['序列码', '用户名', '名称', '电话', '职级', '职位', '角色'];
            // 调用导出的公共方法
            export::publicExport(
                $streamFilename, //路径
                $where,    //sheet名及其每一行的标题
                $list_data      //导出数据
            );
            Common::addLog($user_info, getRealIp($request), '员工列表', '导出', '导出成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据']);
        }
    }

    // 重置密码--提交
    public function resetPassword(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->resetPasswordValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }
        // 更改密码
        $user_info = DB::table('admin')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
            ->where('adm_id', $request['adm_id'])
            ->first(['admin.adm_id', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'admin.adm_name', 'admin.adm_phone', 'asr.adm_state']);
        if (empty($user_info)) {
            return response()->json(['code' => 500, 'msg' => '没有找到此员工', 'data' => '没有找到此员工']);
        }
        DB::beginTransaction();
        $edit_pwd['adm_password'] = md5($request['pwd'] . 'faster123456');
        $edit_pwd['adm_update_time'] = date('Y-m-d H:i:s');
        $adm_res = DB::table('admin')
            ->where('adm_id', $request['adm_id'])
            ->update($edit_pwd);

        if ($adm_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '重设密码', '重设密码', '重设密码成功');
            return response()->json(['code' => 200, 'msg' => '重设成功', 'data' => '重设成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '重设失败', 'data' => '重设失败']);
        }
    }

    // 导入-下载模板
    public function downTemplate(Request $request)
    {
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/Template/EmployeeList.xlsx']);
    }

    // 导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return response()->json(['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '']);
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 2) {
                return response()->json(['code' => 500, 'msg' => '未获取到会员数据', 'data' => '']);
            }
            if ($highestRow > 2503) {
                return response()->json(['code' => 500, 'msg' => '一次最多导入1500条数据', 'data' => '']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            $usersExits = [];

            $import_staff = []; //导入的员工数据
            $import_key = 0;
            for ($j = 3; $j <= $highestRow; $j++) {
                // 员工姓名
                $import_staff[$import_key]['adm_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                if (empty($import_staff[$import_key]['adm_name'])) {
                    return response()->json(['code' => 500, 'msg' => '员工名称必填', 'data' => '']);
                }
                if (mb_strlen($import_staff[$import_key]['adm_name']) > 5) {
                    return response()->json(['code' => 500, 'msg' => '员工名称最多5个字', 'data' => '']);
                }
                // 联系电话
                $import_staff[$import_key]['adm_phone'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                if (empty($import_staff[$import_key]['adm_phone'])) {
                    return response()->json(['code' => 500, 'msg' => '联系电话必填', 'data' => '']);
                }
                $pattern = '/^1[3456789]{1}\d{9}$/';
                $verifyPhone = preg_match($pattern, $import_staff[$import_key]['adm_phone']);
                if ($verifyPhone <= 0) {
                    return response()->json(['code' => 500, 'msg' => '联系电话格式不正确', 'data' => '']);
                }
                // 角色
                $import_staff[$import_key]['adm_role'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                if (empty($import_staff[$import_key]['adm_role'])) {
                    return response()->json(['code' => 500, 'msg' => '角色必填', 'data' => '']);
                }
            }
            if (empty($import_staff)) {
                return response()->json(['code' => 500, 'msg' => '导入表格不能为空，请重新上传！', 'data' => '']);
            }

            DB::beginTransaction();

            $encode_arr = []; //系统编码
            $temp_hint = []; //已存在的员工
            // 对表格数据处理加入
            for ($j = 3; $j <= $highestRow; $j++) {
                // 员工姓名
                $add_adm_data['adm_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                // 联系电话
                $add_adm_data['adm_phone'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                // 角色
                $add_adm_data['adm_role'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());

                // 根据PC端角色名称查询PC端角色是否存在，不存在id为0
                $find_adm_role_id = DB::table('role')
                    ->where('rol_shop_id', $user_info->adm_shop_id)
                    ->where('rol_name', $add_adm_data['adm_role'])
                    ->where('rol_category', 1) //1、pc端角色2、app端角色3、微信小程序角色
                    ->value('rol_id');
                if (empty($find_adm_role_id)) {
                    $find_adm_role_id = 0;
                }

                // 判断手机号是否存在
                $adm =  DB::table('admin_shop_role')
                    ->where('phone', $add_adm_data['adm_phone'])
                    ->where('shop_id', $user_info->adm_shop_id)
                    ->first(['adm_id']);
                if (!empty($adm)) {
                    $temp_hint[] = '当前门店下手机号：' . $add_adm_data['adm_phone'] . '已存在！';
                }else{
                    //判断手机号是否在别的门店创建过
                    $admimInfo = DB::table('admin')
                        ->where('phone', $add_adm_data['adm_phone'])
                        ->first();
                    if(empty($admimInfo)) {
                        //没有创建过
                        $admin_add_data['adm_cid'] = $user_info->adm_cid; //所属企业/品牌方id
                        $admin_add_data['adm_shop_id'] = $user_info->adm_shop_id; //门店id
                        $admin_add_data['adm_superior_shop_id'] = $shop_id; //总店id
                        $admin_add_data['adm_phone'] = $add_adm_data['adm_phone']; //手机号
                        $admin_add_data['adm_account'] = 'os' . time() . rand(100, 999); //用户名（登录账号）
                        $admin_add_data['adm_password'] = md5('123456faster123456'); //登录密码
                        $admin_add_data['adm_name'] = $add_adm_data['adm_name']; //姓名名称
                        $admin_add_data['adm_leave'] = 2;
                        $admin_add_data['adm_role'] = $find_adm_role_id; //角色id
                        $admin_add_data['adm_creator_id'] = $user_info->adm_id; //操作人id
                        $admId =  DB::table('admin')->insertGetid($admin_add_data);

                        //添加账号门店权限关系
                        $insertAdminShopRoleData = [
                            'adm_id' => $admId,
                            'shop_cid' => $user_info->adm_cid,
                            'superior_shop_id' => $shop_id,
                            'shop_id' => $user_info->adm_shop_id,
                            'role_id' =>  $find_adm_role_id,
                            'adm_shop_leave' => 2,
                            'phone' => $add_adm_data['adm_phone'],
                            'create_time' => date("Y-m-d H:i:s", time()),
                            'update_time' => date("Y-m-d H:i:s", time()),
                        ];
                        $insertAdminShopRoleDataRes = DB::table('admin_shop_role')->insert($insertAdminShopRoleData);
                    }else{
                        //添加账号门店权限关系
                        $admId = $admimInfo->adm_id;
                        $insertAdminShopRoleData = [
                            'adm_id' => $admimInfo->adm_id,
                            'shop_cid' => $admimInfo->adm_cid,
                            'superior_shop_id' => $admimInfo->adm_superior_shop_id,
                            'shop_id' => $admimInfo->adm_shop_id,
                            'role_id' =>  $admimInfo->adm_role,
                            'adm_shop_leave' => $admimInfo->adm_leave,
                            'phone' => $admimInfo->adm_phone,
                            'create_time' => date("Y-m-d H:i:s", time()),
                            'update_time' => date("Y-m-d H:i:s", time()),
                            'login_shop' => 2
                        ];
                        $insertAdminShopRoleDataRes = DB::table('admin_shop_role')->insert($insertAdminShopRoleData);
                    }
                    // 2. 门店表，对应门店员工人数增加
                    $shop_res = DB::table('shop')
                        ->where('shop_id', $user_info->adm_shop_id)
                        ->increment('shop_staff_number');
                    if (!$admId || !$shop_res || !$insertAdminShopRoleDataRes) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => '导入失败', 'data' => '']);
                    }
                }
            }
            Common::addLog($user_info, getRealIp($request), '员工列表', '导入', '导入员工成功');
            DB::commit();
            return response()->json(['code' => 200, 'msg' => '导入成功', 'data' => '', 'num' => $highestRow - 2, 'encode' => $temp_hint]);
        } else {
            return response()->json(['code' => 500, 'msg' => '导入有误，请重新上传！！', 'data' => '']);
        }
    }
    
    /*
     * @name 员工搜索下拉
     * @retrun array
     * @author Ma 2023/9/7 9:09
     *
    */
    public function searchList(Request $request){
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();
        $list_data = DB::table('admin')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
            ->leftJoin('role', 'role.rol_id', '=', 'admin.adm_role')
            ->leftJoin('wash_grade_level as grle', 'grle.grle_id', '=', 'admin.adm_grle_id')
            ->where('asr.shop_cid', $user_info->adm_cid)
            ->where("asr.adm_state",1)
            ->whereIn('admin.adm_type', [1, 3])
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name']) && !is_numeric($search_data['adm_name'])) {
                    $query->where('admin.adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (isset($search_data['adm_name']) && is_numeric($search_data['adm_name'])) {
                    $query->where('admin.adm_phone', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->select('admin.adm_id', 'admin.adm_phone', 'admin.adm_name')
            ->orderBy('admin.adm_id', 'desc')
            ->get()->toArray();
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $list_data]);
        } else {
            return response()->json(['code' => 200, 'msg' => '暂无数据', 'data' => []]);
        }
    }

    /**
     * 解绑微信
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-04
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function unbindWx(Request $request) {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->unbindWxValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (isset($request['shop_id']) && $request['shop_id']) {
            $shop_id = $request['shop_id'];
        } else {
            $shop_id = $user_info->adm_shop_id;
        }
        $update_data['adm_open_id'] = '';
        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('admin')
            ->where('adm_id', $request['adm_id'])
            ->update($update_data);
        if ($update_res) {
            return response()->json(['code' => 200, 'msg' => '解绑成功', 'data' => '']);
        } else {
            return response()->json(['code' => 500, 'msg' => '解绑失败', 'data' => '']);
        }
    }
}
