<?php

namespace App\Services\Api\MobileWeb;

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)
    {
        // 查询技师信息
        $list_data = DB::table('install_person')
            ->where('admin_id', $request['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) {
            $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'=>ErrorInc::DATA_EMPTY, '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)
    {
        $admin_id = $request['admin_id'];
        // 判断当前技师是否存在
        $find_id =  InstallPerson::where('admin_id', $request['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['install_year'] = $request['install_year'];
        $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']);
        $ins_res = InstallPerson::insert($arr);
        if ($ins_res) {
            $content =  "新增技师：" . $request['install_name'];
            czrzLog("新增技师", '', $content, "移动端-技师管理", Request::ip(), '');
            // 返回数据
            $return_data['install_name'] = $arr['install_name'];
            $return_data['install_phone'] = $arr['install_phone'];
            $return_data['install_is_type'] = $arr['install_is_type'];
            $return_data['check_code'] = $arr['check_code'];
            $return_data['install_password'] = $arr['check_code'];
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>$return_data];
        } else {
            return ['ErrorCode'=>500, 'ErrorMessage'=>'失败', 'Data'=>[]];
        }
    }

    // 编辑显示
    public static function editShow($request)
    {
        // 判断当前技师是否存在
        $find_data =  InstallPerson::where('admin_id', $request['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')
            ->first();
        if (empty($find_data)) {
            return ['ErrorCode'=>ErrorInc::BUSINESS_FORBID, 'ErrorMessage'=>'未查找到技师！', 'data'=>''];
        }
        return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>$find_data];
    }

    // 编辑技师
    public static function edit($request)
    {
        $admin_id = $request['admin_id'];
        // 判断当前技师是否存在
        $find_id =  InstallPerson::where('admin_id', $request['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'=>''];
        }

        $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'] ?? '';
        $ins_res = InstallPerson::where('id', $request['edit_install_id'])->update($arr);
        if ($ins_res) {
            $content =  "编辑技师：" . $request['install_name'];
            czrzLog("编辑技师", '', $content, "移动端-技师管理", Request::ip(), '');
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>[]];
        } else {
            return ['ErrorCode'=>500, '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');
        $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)
    {
        $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'] . ')';
            czrzLog("删除", '', $content, "移动端-技师管理", Request::ip(), '');
            return ['ErrorCode' => 1, 'ErrorMessage'=>'成功', 'Data'=>[]];
        } else {
            return ['ErrorCode'=>500, 'ErrorMessage'=>'失败', 'Data'=>[]];
        }
    }
}
