<?php

namespace App\Services\Api\MobileWeb;

use App\Services\CommonService;
use App\Services\DealPicService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\{InstallPerson, Certification};

// 移动端，技师管理
class TechnicianService
{
    // 列表查询
    public static function index($request, $show_count = 10)
    {
        $session = $request['session'];
        if($session['user_type']==1){
            return ['ErrorCode' => 1, 'ErrorMessage'=>'暂无数据', 'data'=>[]];
        }
        // 查询技师信息
        $list_data = DB::table('install_person')
            ->where('admin_id', $session['admin_id']) //所属服务商
            ->where('delet_y', 1) //是否删除:1正常2删除
            ->where(function ($query) use ($request) {
                // 状态：1启用2停用
                if (!empty($request['install_is_type'])) {
                    $query->where('install_is_type', $request['install_is_type']);
                }

                // 姓名
                if (!empty($request['install_name'])) {
                    $query->where('install_name', 'like', '%' . $request['install_name'] . '%');
                }
                // 手机号
                if (!empty($request['install_phone'])) {
                    $query->where('install_phone', 'like', '%' . $request['install_phone'] . '%');
                }
            })
            ->select('id', 'check_code', 'install_name', 'install_phone', 'install_is_type', 'install_pic')
            ->orderby('id', 'desc')
            ->paginate($show_count);
        $page['count'] = 0;
        $page['page'] = 0;
        $page['page_size'] = $show_count;
        $page['allPage'] = 0;
        $data['list'] = [];
        $data['page'] = $page;

        $list_items = $list_data->items();
        if ($list_items) {
            foreach($list_items as $k => $v){
                switch ( $v['install_is_type'] ){
                    case 1:
                        $list_items[$k]['is_type_name'] = '启用中';
                        break;
                    default:
                        $list_items[$k]['is_type_name'] = '已停用';
                        break;
                }
            }
            $page['count'] = $list_data->total(); //总数据个数
            $page['page'] = $list_data->currentPage(); //当前页面页码
            $page['page_size'] = $show_count; //一页显示多少个
            $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
            $data['list'] = $list_items;
            $data['page'] = $page;
        }

        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'data'=>$data];
        } else {
            return ['ErrorCode' => 1, 'ErrorMessage'=>'暂无数据', 'data'=>$data];
        }
    }

    /**
     * 获取code值
     */
    public static function getCheckCode($serId)
    {
        $certification_num = Certification::where('ser_id', $serId)->value('certification_num');
        if (!$certification_num) {
            return false;
        }
        $check_code = InstallPerson::whereRaw("admin_id='" . $serId . "' and check_code>10000000 and check_code<1000000000 and check_code like '" . $certification_num . "%'")
            ->orderBy('check_code', 'DESC')->limit('1')
            ->value("check_code");
        $length = strlen($check_code);
        if (in_array($length, [8, 9])) {
            $num = rand(5, 99);
            $che = $check_code + $num;
            $bin = strpos($che, "4");
            if ($bin) {
                $code = str_replace("4", '5', $che);
            } else {
                $code = $che;
            }
        } else {
            $check_code = InstallPerson::whereRaw("check_code like '" . $certification_num . "%'")
                ->orderBy('check_code', 'DESC')
                ->limit('1')
                ->value("check_code");
            $length = strlen($check_code);
            if (in_array($length, [8, 9])) {
                $num = rand(5, 99);
                $che = $check_code + $num;
                $bin = strpos($che, "4");
                if ($bin) {
                    $code = str_replace("4", '5', $che);
                } else {
                    $code = $che;
                }
            } else {
                $code = $certification_num . "1001";
            }
        }
        return $code;
    }

    // 新增技师
    public static function add($request,$ip)
    {
        $session = $request['session'];
        if($session['user_type']==1){
            return ['ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage'=>'无操作权限', 'Data'=>[]];
        }
        $admin_id = $session['admin_id'];
        // 判断当前技师是否存在
        $find_id =  InstallPerson::where('admin_id', $session['admin_id'])
            ->where('install_phone', $request['install_phone'])
            ->where('delet_y', 1)
            ->value('id');
        if ($find_id) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'当前手机号已存在', 'data'=>''];
        }

        // 获取CODE
        $arr['check_code'] = self::getCheckCode($admin_id);
        if (!$arr['check_code']) {
            return ['ErrorCode'=>ErrorInc::INVALID_PARAM, 'ErrorMessage'=>'服务商不存在', 'data'=>''];
        }
        $is_shman = 1; //是否为店长1否，2是
        if ($is_shman == 2) {
            // 查看是否有店长，若存在，将原来的店长改为技师
            $exit_id = InstallPerson::where('admin_id', $admin_id)->where('is_shman', 2)->value('id');
            InstallPerson::where('id', $exit_id)->update(['is_shman' => 1, 'install_pid' => 0]);
        } else {
            // 查看是否有技师，没有，则将本次的添加的为店长
            $exit_id = InstallPerson::where('admin_id', $admin_id)->value('id');
            if (!$exit_id) {
                $is_shman = 2;
            }
        }

        $arr['install_name'] = $request['install_name'];
        $arr['install_phone'] = $request['install_phone'];
        $arr['install_is_type'] = $request['install_is_type'];
        $arr['install_year'] = $request['install_year'];
        if (isset($request['install_pic'])) {
            $arr['install_pic'] = $request['install_pic'];
        }
        $arr['admin_id'] = $admin_id;
        $arr['is_shman']   = $is_shman;
        $arr['install_remark'] = $request['install_remark'] ?? '';
        $arr['install_password1'] = $arr['check_code'];
        $arr['install_password'] = md5($arr['check_code']);
        $arr['install_province']=$request['install_province'];
        $arr['install_city']=$request['install_city'];
        $arr['install_cuntry']=$request['install_cuntry'];
        $arr['install_address']=$request['install_address'];
        if(empty($request['address'])){
            $arr['longitude']='';
            $arr['latitude']='';
        }else{
            $geocodes = CommonService::jingwei($arr['install_province'],$arr['install_province'].$arr['install_city'].$arr['install_cuntry'].$arr['install_address']);
            if(empty($geocodes)){
                $arr['longitude']='';
                $arr['latitude']='';
            }else{
                $arr['longitude']=explode(',',$geocodes)[0];
                $arr['latitude']=explode(',',$geocodes)[1];
            }
        }
        $ins_res = InstallPerson::insert($arr);
        if ($ins_res) {
            $content =  "新增技师：" . $request['install_name'];
            CommonService::inserting_log('新增技师', $arr['check_code'], $content, '移动端-技师管理', $session, $ip);//日志
            // 返回数据
            $return_data['install_name'] = $arr['install_name'];
            $return_data['install_phone'] = $arr['install_phone'];
            $return_data['install_is_type'] = $arr['install_is_type'];
            switch ( $arr['install_is_type'] ){
                case 1:
                    $return_data['is_type_name'] = '启用中';
                    break;
                default:
                    $return_data['is_type_name'] = '已停用';
                    break;
            }
            $return_data['check_code'] = $arr['check_code'];
            $return_data['install_password'] = $arr['check_code'];
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>$return_data];
        } else {
            return ['ErrorCode'=>ErrorInc::MYSQL_FAILED, 'ErrorMessage'=>'失败', 'Data'=>[]];
        }
    }

    // 编辑显示
    public static function editShow($request)
    {
        $session = $request['session'];
        // 判断当前技师是否存在
        $find_data =  InstallPerson::where('admin_id', $session['admin_id'])
            ->where('id', $request['edit_install_id'])
            ->where('delet_y', 1)
            ->select('id', 'check_code', 'install_name', 'install_phone', 'install_year', 'install_pic', 'install_is_type', 'install_remark','install_province','install_city','install_cuntry','install_address')
            ->first();
        if (empty($find_data)) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'未查找到技师！', 'data'=>''];
        }
        return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>$find_data];
    }

    // 编辑技师
    public static function edit($request,$ip)
    {
        $session = $request['session'];
        if($session['user_type']==1){
            return ['ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage'=>'无操作权限', 'Data'=>[]];
        }
        $admin_id = $session['admin_id'];
        // 判断当前技师是否存在
        $find_id =  InstallPerson::where('admin_id', $session['admin_id'])
            ->where('id', '<>', $request['edit_install_id'])
            ->where('install_phone', $request['install_phone'])
            ->where('delet_y', 1)
            ->value('id');
        if ($find_id) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'当前手机号已存在', 'data'=>''];
        }
        $check_code = InstallPerson::where('id', $request['edit_install_id'])->value('check_code');
        $arr['install_name'] = $request['install_name'];
        $arr['install_phone'] = $request['install_phone'];
        $arr['install_is_type'] = $request['install_is_type'];
        if (isset($request['install_pic'])) {
            $arr['install_pic'] = $request['install_pic'];
        }
        $arr['install_year'] = $request['install_year'];
        $arr['install_remark'] = $request['install_remark'] ?? '';
        $arr['updata_time'] = date("Y-m-d H:i:s");
        $ins_res = InstallPerson::where('id', $request['edit_install_id'])->update($arr);
        if ($ins_res) {
            $content =  "编辑技师：" . $request['install_name'];
            CommonService::inserting_log('编辑技师', $check_code, $content, '移动端-技师管理', $session, $ip);//日志
            return ['ErrorCode' => 1, 'ErrorMessage'=>'操作成功', 'Data'=>[]];
        } else {
            return ['ErrorCode'=>ErrorInc::MYSQL_FAILED, 'ErrorMessage'=>'操作失败', 'Data'=>[]];
        }
    }

    // 修改密码
    public static function changePassword($request)
    {
        $find_data = InstallPerson::where('id', $request['install_id'])
            ->where('admin_id', $request['admin_id'])
            ->where('delet_y', 1)
            ->select('install_password', 'install_name')
            ->first();
        if (!$find_data) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'无此用户', 'data'=>''];
        }
        if (md5($request['password']) != $find_data['install_password']) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'原密码不正确！', 'data'=>''];
        }

        $info['install_password'] = md5($request['new_password']);
        $info['install_password1'] = $request['new_password'];
        $info['updata_time'] = date('Y-m-d H:i:s');
        $info['install_province']=$request['install_province'];
        $info['install_city']=$request['install_city'];
        $info['install_cuntry']=$request['install_cuntry'];
        $info['install_address']=$request['install_address'];
        if(empty($request['address'])){
            $info['longitude']='';
            $info['latitude']='';
        }else{
            $geocodes = CommonService::jingwei($info['install_province'],$info['install_province'].$info['install_city'].$info['install_cuntry'].$info['install_address']);
            if(empty($geocodes)){
                $info['longitude']='';
                $info['latitude']='';
            }else{
                $info['longitude']=explode(',',$geocodes)[0];
                $info['latitude']=explode(',',$geocodes)[1];
            }
        }
        $res = InstallPerson::where('id', $request['install_id'])->update($info);
        if ($res) {
            $content =  $find_data['install_name'] . "，修改密码";
            czrzLog("修改密码", '', $content, "移动端-技师管理", Request::ip(), '');
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>[]];
        } else {
            return ['ErrorCode'=>500, 'ErrorMessage'=>'失败', 'Data'=>[]];
        }
    }

    // 删除
    public static function delete($request,$ip)
    {
        $session = $request['session'];
        $find_data = InstallPerson::where('id', $request['install_id'])
            ->where('admin_id', $request['admin_id'])
            ->where('delet_y', 1)
            ->select('install_name', 'check_code')
            ->first();
        if (!$find_data) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'无此用户', 'data'=>''];
        }

        $edit_inpe_data['delet_y'] = 2; //是否删除：1否2删除
        $edit_inpe_data['updata_time'] = date('Y-m-d H:i:s');
        $res = InstallPerson::where('id', $request['install_id'])->update($edit_inpe_data);
        if ($res) {
            $content =  $find_data['install_name'] . '(' . $find_data['check_code'] . ')';
            CommonService::inserting_log('删除', $find_data['check_code'], $content, '移动端-技师管理', $session, $ip);//日志
            czrzLog("删除", '', $content, "移动端-技师管理", Request::ip(), '');
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>[]];
        } else {
            return ['ErrorCode'=>500, 'ErrorMessage'=>'失败', 'Data'=>[]];
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加头像
     * @param string file 图片base64
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/13 18:47
     * |---------------------------------------------------------------------------------
    */
    public static function addHeadPic ( $request ){
        $request['path']='./InstallHeadPic/'.date('Ym');
        $rea = DealPicService::addPic($request['file'],$request['path'],1);
        if($rea){
            $rea = OrderListService::picurl($rea);
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $rea];
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $rea];
        }
    }
}
