<?php

namespace App\Services\SystemsManage;

use App\Http\Models\Api\Common;
use App\Services\LoginUserService;
use BlueCity\Core\Service\Service;
use App\Services\BasicManagement\AdminService;
use Illuminate\Support\Facades\DB;
use App\Services\CommonService;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyPersonalController;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyEmployeeListController;

class PersonalService extends Service
{
    /**
     * @name 列表
     * @param Request $request
     * @return array
     * @date 2023/6/27
     */
    public static function index($user_info,$request)
    {
        // 验证数据
        $verify_data = new VerifyPersonalController;
        $error_message = $verify_data->processIndexValidator($request);
        if ($error_message) {
            return ['code' => 500, 'msg' => '参数错误', 'data' => '参数错误'];
        }
        // 记录日志
        $log_record['request'] = $request;
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'index';
        logFileRecord($log_record, 'wash/Personal', 2);

        request()->offsetSet('rt', 'wechat');

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //状态
        $state_name = self::getStateName(true);
        $return_data = AdminService::index($user_info, $request,$request['show_count']);
        foreach ($return_data['data']['data'] as $key => $value){
            $return_data['data']['data'][$key]->adp_state_name = $state_name[$value->adp_state];
            $buttonData = [];
            if($value->adp_state == 1){//待审核
                $buttonData[] = 'edit';
            }elseif ($value->adp_state == 2) {
                $buttonData[] = 'info';
            }elseif($value->adp_state == 3){
                $buttonData[] = 'info';
                $buttonData[] = 'edits';
            }
            if($list_button){
                $button = CommonService::getListButton($buttonData,$list_button);
                $return_data['data']['data'][$key]->button_one = $button['button_one']??[];
                $return_data['data']['data'][$key]->button_two = $button['button_two']??[];
                $return_data['data']['data'][$key]->button_three = $button['button_three']??[];
            }else{
                $return_data['data']['data'][$key]->button_one = [];
                $return_data['data']['data'][$key]->button_two = [];
                $return_data['data']['data'][$key]->button_three = [];
            }
        }
        //获取top按钮
        $top_button = CommonService::getTopButton('address',[],$list_button);
        $return_data['data']['button_list'] = $top_button;
        return $return_data;
    }

    /**
     * @name 添加
     * @param Request $request
     * @return array
     * @date 2023/6/27
     */
    public static function add($request,$source = 1)
    {
        // 验证数据
        $verify_data = new VerifyEmployeeListController;
        $error_message = $verify_data->addValidator($request);
        if ($error_message) {
            return ['code' => 500, 'msg' => $error_message, 'data' => '参数错误'];
        }

        $find_role = DB::table('role')
            ->where('rol_id', $request['adm_role'])
            ->first();
        if (!$find_role) {
            return ['code' => 500, 'msg' => '未查询到此角色', 'data' => ''];
        }

        // 判断手机号是否存在
        $adm =  DB::table('admin_shop_role as asr')
            ->leftJoin("admin as a", "a.adm_id", "=", "asr.adm_id")
            ->where('asr.phone', $request['adm_phone'])
            ->where('asr.shop_id', $find_role->rol_shop_id)
            ->first(['asr.adm_id', 'a.adm_type']);
        if ($adm && ($adm->adm_type == 1)) {
            return ['code' => 500, 'msg' => '当前门店已注册', 'data' => ''];
        }

        // 判断手机号是否存在
        $adm_pro =  DB::table('admin_process')
            ->where('adp_adm_phone', $request['adm_phone'])
            ->where('adp_shop_id', $find_role->rol_shop_id)
            ->first();
        if (!empty($adm_pro)) {
            if ($adm_pro->adp_state == 1) {
                return ['code' => 200, 'msg' => '手机号正在审核中', 'data' => ''];
            }

            if ($adm_pro->adp_state == 2) {
                return ['code' => 500, 'msg' => '手机号已通过审核', 'data' => ''];
            }
            if ($adm_pro->adp_state == 3) {
                $update_data['adp_state'] = 1;
                if (empty($request['adm_password'])) {
                    $request['adm_password'] = substr($request['adm_phone'], 0, 6);
                }
                $password = md5($request['adm_password'] . 'faster123456');
                $update_data['adp_adm_password'] = $password;
                $update_data['adp_adm_name'] = $request['adm_name'];
                $update_data['adp_adm_rol_id'] = $request['adm_role']; //角色id
                $update_data['adp_create_time'] = date('Y-m-d H:i:s');
                $update_data['adp_update_time'] = date('Y-m-d H:i:s');
                $adm_res =  DB::table('admin_process')->where('adp_id', $adm_pro->adp_id)->update($update_data);
                if ($adm_res) {
                    return ['code' => 200, 'msg' => '提交成功', 'data' => ''];
                } else {
                    return ['code' => 500, 'msg' => '提交失败', 'data' => ''];
                }
            }
        }

        if (empty($request['adm_password'])) {
            $request['adm_password'] = substr($request['adm_phone'], 0, 6);
        }
        $password = md5($request['adm_password'] . 'faster123456');
        $admin_add_data['adp_shop_id'] = $find_role->rol_shop_id; //门店id
        $admin_add_data['adp_adm_phone'] = $request['adm_phone']; //手机号
        $admin_add_data['adp_adm_account'] = $request['adm_account']; //用户名（登录账号）
        $admin_add_data['adp_adm_password'] = $password; //登录密码
        $admin_add_data['adp_adm_name'] = $request['adm_name']; //姓名名称
        $admin_add_data['adp_adm_rol_id'] = $request['adm_role']; //角色id
        $admin_add_data['adp_create_time'] = date('Y-m-d H:i:s');
        $admin_add_data['adp_source'] = $source;

        // 新增账号
        $adm_res =  DB::table('admin_process')->insertGetid($admin_add_data);
        if ($adm_res) {
            return ['code' => 200, 'msg' => '提交成功', 'data' => ''];
        } else {
            return ['code' => 500, 'msg' => '提交失败', 'data' => ''];
        }
    }

    /**
     * @name 修改
     * @param Request $request
     * @return array
     * @date 2023/6/27
     */
    public static function Edit($user_info,$request)
    {
        // 验证数据
        $verify_data = new AdminService;
        $error_message = $verify_data->mainValidator->ProcessValidator($request);
        if ($error_message) {
            return ['code' => 500, 'msg' => $error_message, 'data' => '参数错误'];
        }
        request()->offsetSet('rt', 'wechat');

        //获取页面信息
        if(isset($request['type']) && $request['type'] == 1){
            $find_data = DB::table('admin_process')
                ->leftJoin('role', 'rol_id', '=', 'adp_adm_rol_id')
                ->where('adp_id', $request['adp_id'])
                ->where('adp_shop_id', $user_info->adm_shop_id)
                ->select('adp_id', 'adp_adm_name', 'adp_adm_phone', 'adp_adm_phone', 'adp_adm_rol_id', 'rol_name', 'adp_state', 'adp_create_time')
                ->first();
            if (!$find_data) {
                return ['code' => 500, 'msg' => '审核不存在', 'data' => ''];
            }
            $log_data = DB::table('admin_reason')
                ->where('adr_adp_id', $request['adp_id'])
                ->orderby('adr_id', 'asc')
                ->get()->toArray();
            foreach ($log_data as $key => $value){
                if($value->adr_state == 1){//审核恢复
                    $log_data[$key]->adr_state_name = '恢复';
                }else if($value->adr_state == 2){//审核通过
                    $log_data[$key]->adr_state_name = '通过';
                }else if($value->adr_state == 3){//审核驳回
                    $log_data[$key]->adr_state_name = '驳回';
                }
            }
            $data['data'] = $find_data;
            $data['process_log'] = $log_data;

            return ['code' => 200, 'msg' => '', 'data' => $data];
        }
        // 判断手机号是否存在
        $admin_process =  DB::table('admin_process')
            ->where('adp_id', $request['adp_id'])
            ->where('adp_shop_id', $user_info->adm_shop_id)
            ->first();
        if (!$admin_process) {
            return ['code' => 500, 'msg' => '审核不存在', 'data' => ''];
        }

        if ($admin_process->adp_state == 2) {
            return ['code' => 500, 'msg' => '审核已通过', 'data' => ''];
        }

        // 判断手机号是否存在
        $adm =  DB::table('admin_shop_role')
            ->where('phone', $admin_process->adp_adm_phone)
            ->where('shop_id', $user_info->adm_shop_id)
            ->first();
        if ($adm) {
            return ['code' => 500, 'msg' => '当前门店手机号已存在', 'data' => ''];
        }

        $find_role = DB::table('role')
            ->where('rol_id', $admin_process->adp_adm_rol_id)
            ->first();
        DB::beginTransaction();
        $update_process['adp_state'] = $request['adp_state']; //审核状态1未审核2已通过3驳回
        $update_process['adp_create_id'] = $user_info->adm_id;; //审核人id
        $update_process['adp_create_name'] = $user_info->adm_name;; //审核人
        $update_process['adp_update_time'] = date('Y-m-d H:i:s'); //时间
        // 修改审核状态
        $update_res =  DB::table('admin_process')->where('adp_id', $request['adp_id'])->update($update_process);
        //审核记录

        $add_process['adr_state'] =$request['adp_state'];
        $add_process['adr_adm_phone'] = $admin_process->adp_adm_phone;
        $add_process['adr_reason'] = $request['reason'];
        $add_process['adr_adp_id'] = $request['adp_id'];
        $add_process['adr_create_id'] = $user_info->adm_id; //审核人
        $add_process['adr_rol_id'] = $admin_process->adp_adm_rol_id; //角色id
        $add_process['adr_rol_name'] = $find_role->rol_name; //角色
        $add_process['adr_create_name'] = $user_info->adm_name; //审核人
        $add_process['adr_create_time'] = date('Y-m-d H:i:s'); //时间
        $adm_rea_res =  DB::table('admin_reason')->insertGetid($add_process);

        //如果通过
        if($request['adp_state'] == 2){
            $admId = DB::table('admin')->where('adm_phone', $admin_process->adp_adm_phone)->value('adm_id');
            if(empty($admId)) {
                $admin_add_data['adm_cid'] = $find_role->rol_cid; //所属企业/品牌方id
                $admin_add_data['adm_shop_id'] = $find_role->rol_shop_id; //门店id
                $admin_add_data['adm_superior_shop_id'] = $find_role->rol_shop_id; //总店id
                $admin_add_data['adm_leave'] = 2; //级别1店长2普通员工3技师4业务员5技师和业务员
                $admin_add_data['adm_phone'] = $admin_process->adp_adm_phone; //手机号
                $admin_add_data['adm_account'] = $admin_process->adp_adm_account; //用户名（登录账号）
                $admin_add_data['adm_password'] = $admin_process->adp_adm_password; //登录密码
                $admin_add_data['adm_name'] = $admin_process->adp_adm_name; //姓名名称
                $admin_add_data['adm_role'] = $admin_process->adp_adm_rol_id; //角色id
                $admin_add_data['adm_creator_id'] = $user_info->adm_id; //操作人id
                $admin_add_data['adm_create_time'] = date('Y-m-d H:i:s'); //创建时间
                // 新增账号
                $admId = DB::table('admin')->insertGetid($admin_add_data);
            }
            //新增账号门店权限关系表
            $insertAdminShopRoleData = [
                'adm_id' => $admId,
                'shop_cid' => $find_role->rol_cid,
                'superior_shop_id' => $find_role->rol_shop_id,
                'shop_id' => $find_role->rol_shop_id,
                'role_id' => $admin_process->adp_adm_rol_id,
                'adm_shop_leave' => 2,
                'phone' => $admin_process->adp_adm_phone,
                'create_time' => date("Y-m-d H:i:s", time()),
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            $admin_shop_role_id =  DB::table('admin_shop_role')->insertGetId($insertAdminShopRoleData);

        } else {
            $admId = true;
            $admin_shop_role_id = true;
        }

        if ($adm_rea_res && $admId && $update_res && $admin_shop_role_id) {
            DB::commit();
            return ['code' => 200, 'msg' => '审核成功', 'data' => ''];
        } else {
            DB::rollBack();
            return ['code' => 500, 'msg' => '审核失败', 'data' => ''];
        }
    }

    /**
     * @name 获取状态name
     * @param false $type
     * @return array
     */
    public static function getStateName($type){
        $data = [['id'=>1,'name'=>'新申请'],['id'=>2,'name'=>'已通过'],['id'=>3,'name'=>'已驳回']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /**
     * @name 详情
     * @param Request $request
     * @return array
     * @date 2023/6/27
     */
    public static function Info($request,$user_info)
    {
        $find_data = DB::table('admin_process')
            ->leftJoin('role', 'rol_id', '=', 'adp_adm_rol_id')
            ->where('adp_id', $request['adp_id'])
            ->where('admin_process.adp_shop_id', $user_info->adm_shop_id)
            ->select('adp_id', 'adp_adm_name', 'adp_adm_phone', 'adp_adm_phone', 'adp_adm_rol_id', 'rol_name', 'adp_state', 'adp_create_time')
            ->first();
        if (!$find_data) {
            return ['code' => 500, 'msg' => '审核不存在', 'data' => ''];
        }
        $show_count = 10;
        $list_data = DB::table('admin_reason')
            ->leftJoin('admin_process', 'adp_id', '=', 'adr_adp_id')
            ->leftJoin('role', 'rol_id', '=', 'adp_adm_rol_id')
            ->where('adr_adp_id', $request['adp_id'])
            ->select('adr_reason', 'adr_create_name', 'adr_create_time', 'rol_name', 'adr_state')
            ->orderBy('adr_id', 'asc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        foreach ($list_items as $key => $value){
            if($value->adr_state == 1){//审核恢复
                $list_items[$key]->adr_state_name = '恢复';
            }else if($value->adr_state == 2){//审核通过
                $list_items[$key]->adr_state_name = '通过';
            }else if($value->adr_state == 3){//审核驳回
                $list_items[$key]->adr_state_name = '驳回';
            }
        }
        $data['data'] = $list_items;
        $ret['data'] = $find_data;
        $ret['process_log'] = $data;
        return ['code' => 200, 'msg' => '', 'data' => $ret];
    }

}
