<?php

namespace App\Services\Business;

use App\Http\Controllers\Api\Verify\VerifyExcelpermissController;
use App\Models\OperationLog;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\LoginUserService;
use App\Services\Point\PointService;
use App\Services\Shop\ShopService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use App\Http\Models\Api\Common;
use Chumper\Zipper\Zipper;
use Illuminate\Support\Facades\DB;
use App\Models\Common as Comm;

// 导出权限
class ExcelInfoService extends Service
{

    //获取列表信息
    public static function list($search_data,$user_info,$show_count = 10)
    {
        $list_data = DB::table('admin_excel as e')
            ->leftJoin('role as r', 'e.adex_role_id', '=', 'r.rol_id')
            ->leftJoin('shop as s', 'e.adex_shop_id', '=', 's.shop_id')
            //->where('meml_cid', $user_info->adm_cid)
            ->where('adex_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) { //控制器名字
                if (!empty($search_data['adex_acname'])) {
                    $query->where('adex_acname', $search_data['adex_acname']);
                }
            })
            ->where(function ($query) use ($search_data) { //控制器
                if (!empty($search_data['adex_action'])) {
                    $query->where('adex_action', $search_data['adex_action']);
                }
            })
            ->where(function ($query) use ($search_data) { //店铺id
                if (!empty($search_data['adex_shop_id'])) {
                    $query->where('adex_shop_id', $search_data['adex_shop_id']);
                }
            })->where(function ($query) use ($search_data) { //角色id
                if (!empty($search_data['adex_role_id'])) {
                    $query->where('adex_role_id', $search_data['adex_role_id']);
                }
            })
            ->orderBy('adex_id', 'desc')
            ->select('e.*','r.rol_name','s.shop_store_name')
            ->paginate($show_count);

        $list_items = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
        //获取top按钮
        $top_button = CommonService::getTopButton('excelAdd',[],$list_button);
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $adex_data = json_decode($value->adex_data,true);
                foreach ($adex_data as $k => $v){
                    $data_arr[] = $v['field_name'];
                }
                $list_items[$key]->adex_data_name = implode(',',$data_arr);
                unset($data_arr);
                //按钮
                $buttonData[] = 'excelEdit';//编辑
                $buttonData[] = 'excelDel';//删除
                $button = CommonService::getListButton($buttonData,$list_button);
                $list_items[$key]->button_one = $button['button_one']??[];
                $list_items[$key]->button_two = $button['button_two']??[];
                $list_items[$key]->button_three = $button['button_three']??[];
                unset($buttonData);
            }
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = 1;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        $data_info['top_button'] = $top_button;
        if ($list_data) {
            return ['code' => 200, 'msg' => '成功', 'data' => $data_info];
        } else {
            return ['code' => 200, 'msg' => '暂无数据', 'data' => '暂无数据'];
        }
    }

    //添加
    public static function add($user_info,$request)
    {
        // 验证数据
        $verify_data = new VerifyExcelpermissController;
        $error_message = $verify_data->addValidator($request);
        if ($error_message) {
            return ['code' => 500, 'msg' => '参数错误', 'data' => '参数错误', 'error_message' => $error_message];
        }
        $shop_id = $request['adex_shop_id']??$user_info->adm_shop_id;
        $data = DB::table('admin_excel')
            ->where('adex_action', $request['adex_action'])
            ->where('adex_acname', $request['adex_acname'])
            ->where('adex_shop_id', $shop_id)
            ->where('adex_role_id', $request['adex_role_id'])
            ->count();
        if($data > 0){
            return ['code' => 500, 'msg' => '该权限已添加,请勿重复添加', 'data' => ''];
        }
        //$request['adex_data'] = [['field_name'=>'订单单号','field_value'=>'ord_id'],['field_name'=>'订单状态','field_value'=>'ord_order_number']];
        $add_data['adex_shop_id'] = $shop_id;//门店id
        $add_data['adex_role_id'] = $request['adex_role_id'];//角色id
        $add_data['adex_action'] = $request['adex_action'];//对应key
        $add_data['adex_acname'] = $request['adex_acname'];//控制器名称
        $add_data['adex_data'] = json_encode($request['adex_data'], JSON_UNESCAPED_UNICODE);//所需数据
        $ret_id =  DB::table('admin_excel')->insertGetId($add_data);
        if ($ret_id) {
            return ['code' => 200, 'msg' => '新增成功', 'data' =>''];
        } else {
            return ['code' => 500, 'msg' => '新增失败', 'data' => '新增失败'];
        }
    }

    //删除
    public static function excelDel($request)
    {
        // 验证数据
        $verify_data = new VerifyExcelpermissController;
        $error_message = $verify_data->delValidator($request); //验证编辑id是否存在
        if ($error_message) {
            return ['code' => 500, 'msg' => '参数错误', 'data' => '参数错误', 'error_message' => $error_message];
        }
        $data = DB::table('admin_excel')
            ->where('adex_id', $request['adex_id'])
            ->count();
        if($data <= 0){
            return ['code' => 500, 'msg' => '数据不存在', 'data' => ''];
        }
        $del_res = DB::table('admin_excel')
            ->where('adex_id', $request['adex_id'])
            ->delete();
        if ($del_res) {
            return ['code' => 200, 'msg' => '删除成功', 'data' =>''];
        } else {
            return ['code' => 500, 'msg' => '删除失败', 'data' => ''];
        }
    }

    //编辑
    public static function excelEdit($request)
    {
        // 验证数据
        $verify_data = new VerifyExcelpermissController;
        $error_message = $verify_data->editValidator($request); //验证编辑id是否存在
        if ($error_message) {
            return ['code' => 500, 'msg' => '参数错误', 'data' => '参数错误', 'error_message' => $error_message];
        }
        $find_data = DB::table('admin_excel')
            ->where('adex_id', $request['adex_id'])
            ->first();
        if(empty($find_data)){
            return ['code' => 500, 'msg' => '数据不存在', 'data' => ''];
        }
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $request['adex_shop_id']??$user_info->adm_shop_id;
        $update_data['adex_action'] = $request['adex_action'];//对应key
        $update_data['adex_acname'] = $request['adex_acname'];//控制器名称
        $update_data['adex_shop_id'] = $shop_id;//门店id
        $update_data['adex_role_id'] = $request['adex_role_id'];//角色id
        $update_data['adex_data'] = json_encode($request['adex_data'], JSON_UNESCAPED_UNICODE);
        $data = DB::table('admin_excel')
            ->where('adex_id', $request['adex_id'])
            ->update($update_data);
        return ['code' => 200, 'msg' => '编辑成功', 'data' =>''];
    }

    /**
     * @name 获取列表
     * @param $input
     * @param $session
     * @return array
     * @author du
     * @date 2021/8/25
     */
    public static function getList($search_data,$user_info,$show_count){
        // $where = [];
        // $Db = DB::table('excel_list');

        /*if($session['admin_groupnew']!=7){
            $where['exl_adminid'] = $session['id'];
        }*/
        /*if (isset($input['exl_adminid'])){//操作人
            $where['exl_adminid'] = $input['exl_adminid'];
        }*/
       /* if (isset($input['exl_action'])){//导出模块
            $where['exl_dataname_rlike'] = $input['exl_action'];
        }
        if (isset($input['datatime'])){//导出模块
            $creatData = $input['datatime'];
            $time_arr[0] = $creatData[0];
            $time_arr[1] = $creatData[1].' 23:59:59';
            $where['exl_creactime_between'] = $time_arr;
        }*/

        $list_data = DB::table('excel_list')
            ->where('el_adminid', $user_info->adm_id)
            ->where(function ($query) use ($search_data) { //操作人
                if (!empty($search_data['el_adminid'])) {
                    $query->where('el_adminid', $search_data['el_adminid']);
                }
            })
            ->where(function ($query) use ($search_data) { //导出模块
                if (!empty($search_data['el_action'])) {
                    $query->where('el_action','like','%'.$search_data['el_action'].'%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                if (!empty($search_data['datatime'])) {
                    $query->whereBetween('el_creactime', [$search_data['datatime'][0], $search_data['datatime'][1] . ' 23:59:59']);
                }
                // 如果选择开始时间并且选择结束时间
                /*if (!empty($search_data['datatime'][0]) && !empty($search_data['datatime'][1])) {
                    $query->whereBetween('el_creactime', [$search_data['start_time'][0], $search_data['end_time'][1] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('recpay_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('recpay_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }*/
            })
            ->orderBy('el_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $list_items[$key]->el_state_name = '';
                //按钮
                $buttonData = [];
                if($value->el_state == 2){
                    $buttonData[] = 'addDownloudnum';//下载
                    $list_items[$key]->el_state_name = '可下载';
                }
                if($value->el_state == 1){
                    $buttonData[] = 'execExcelOut';//执行
                    $list_items[$key]->el_state_name = '执行中';
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $list_items[$key]->button_one = $button['button_one']??[];
                $list_items[$key]->button_two = $button['button_two']??[];
                $list_items[$key]->button_three = $button['button_three']??[];
                unset($buttonData);
                unset($list_items[$key]->el_sql);
                unset($list_items[$key]->el_path);
            }
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $show_count;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        if ($list_data) {
            return ['code' => 200, 'msg' => '成功', 'data' => $data_info];
        } else {
            return ['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据'];
        }
    }

    //申请人列表
    public static function userList($request, $user_info){
        $data = DB::table('admin')
            ->where('adm_shop_id', $user_info->adm_shop_id)
            ->select('adm_id as el_adminid', 'adm_name as el_adminname')
            ->get()->toArray();
        // $data = DB::table("excel_list")
        //     ->select("el_adminid","el_adminname")
        //     ->groupBy('el_adminid')
        //     ->get()->toArray();
        return ['code' => 200, 'msg' => '成功', 'data' => $data];

    }

    //角色列表
    public static function roleList($request){
        $user_info = Common::getUserInfo($request['api_token']);
        $adm_role = DB::table("admin_shop_role")
            ->where('adm_id',$user_info->adm_id)
            ->where('shop_id',$user_info->adm_shop_id)
            ->value('role_id');
        if($adm_role == 5){//如果是超级总管理
            if($request['adex_shop_id']){
                $shop_id = $request['adex_shop_id'];
            }else{
                $shop_id = $user_info->adm_shop_id;
            }
            $data = DB::table("role")
                ->where('rol_shop_id',$shop_id)
                ->where('rol_state',1)
                ->select("rol_id","rol_name")
                ->orderBy('rol_id','ASC')->get()->toArray();
            return ['code' => 200, 'msg' => '成功', 'data' => $data];
        }else{
            $role_type = DB::table("role")
                ->where('rol_shop_id',$user_info->adm_shop_id)
                ->where('rol_id',$adm_role)
                ->value('rol_type');
            if($role_type == 1){
                $data = DB::table("role")
                    ->where('rol_shop_id',$user_info->adm_shop_id)
                    ->where('rol_state',1)
                    ->select("rol_id","rol_name")
                    ->orderBy('rol_id','ASC')->get()->toArray();
                return ['code' => 200, 'msg' => '成功', 'data' => $data];
            }else{
                $data = DB::table("role")
                    ->where('rol_shop_id',$user_info->adm_shop_id)
                    ->where('rol_state',1)
                    ->where('rol_type','>','1')
                    ->select("rol_id","rol_name")
                    ->orderBy('rol_id','ASC')->get()->toArray();
                return ['code' => 200, 'msg' => '成功', 'data' => $data];
            }

        }

    }

    //门店列表
    public static function shopList($request){

        $data = DB::table("shop")
            ->where(function ($query) use ($request) { //控制器名字
                if (!empty($request['shop_name'])) {
                    $query->where('shop_store_name','like','%'.$request['shop_name'].'%');
                }
            })
            ->select("shop_id","shop_store_name")
            ->orderBy('shop_id','desc')->get()->toArray();
        return ['code' => 200, 'msg' => '成功', 'data' => $data];

    }
    
    /**|---------------------------------------------------------------------------------
     * @name 个人导出权限
     * @param string type 请求类型 1获取列表 2获取可操作字段 3添加 4编辑
     * @param string amp_id 数据id
     * @param string amp_action 对应控制器
     * @param string amp_acname 控制器名称
     * @param string amp_data 字段
     * @param string amp_type 模板说明
     * @retrun /multitype:array
     * @author dou 2025/3/5 14:58
     * |---------------------------------------------------------------------------------
    */
    public static function excelPerson ( $input,$user_info,$ip ){
        $user_infos = CommonService::dataToArray($user_info);
        $type = $input['type'];
        switch ( $type ){
            case 1:
                if(!isset($input['amp_action']) || empty($input['amp_action'])){
                    return ['code' => ErrorInc::INVALID_PARAM, 'msg' => '对应控制器未填写', 'data' => []];
                }
                $list = DB::table('admin_excel_person')
                    ->where('amp_admin_id',$user_infos['adm_id'])
                    ->where('amp_shop_id',$user_infos['adm_shop_id'])
                    ->where('amp_action',$input['amp_action'])
                    ->get();
                $list = CommonService::dataToArray($list);
                if($list){
                    foreach($list as $k => $v){
                        $list[$k]['amp_data'] = json_decode($v['amp_data'],true);
                    }
                }
                return ['code' => 200, 'msg' => '操作成功', 'data' => $list];
            case 2:
                if(!isset($input['amp_action']) || empty($input['amp_action'])){
                    return ['code' => ErrorInc::INVALID_PARAM, 'msg' => '对应控制器未填写', 'data' => []];
                }
                $role_id = DB::table('admin_shop_role')
                    ->where('adm_id',$user_infos['adm_id'])
                    ->where('superior_shop_id',$user_infos['adm_shop_id'])->value('role_id');
                $list = DB::table('admin_excel')
                    ->where('adex_role_id',$role_id)
                    ->where('adex_shop_id',$user_infos['adm_shop_id'])
                    ->where('adex_action',$input['amp_action'])
                    ->value('adex_data');
                if($list){
                    $list = json_decode($list,true);
                }
                return ['code' => 200, 'msg' => '操作成功', 'data' => $list];
            case 3:
                $checkKey = CommonService::checkKey(['amp_action', 'amp_acname', 'amp_data', 'amp_type'],$input);
                if($checkKey['code']!=1){
                    return $checkKey;
                }else{
                    $add['amp_action'] = $input['amp_action'];
                    $add['amp_acname'] = $input['amp_acname'];
                    $add['amp_data'] = is_array($input['amp_data'])?json_encode($input['amp_data'],JSON_UNESCAPED_UNICODE):$input['amp_data'];
                    $add['amp_type'] = $input['amp_type'];
                    $add['amp_shop_id'] = $user_infos['adm_shop_id'];
                    $add['amp_admin_id'] = $user_infos['adm_id'];
                    $res = DB::table('admin_excel_person')->insert($add);
                    if($res){
                        OperationLog::addLog($user_info, $ip, '导出模板', '添加模板', '模板名称：'.$input['amp_type']."(".$input['amp_acname'].")");
                        return ['code' => 200, 'msg' => '操作成功', 'data' => []];
                    }else{
                        return ['code' => ErrorInc::MYSQL_FAILED, 'msg' => '操作失败', 'data' => []];
                    }
                }
            case 4:
                $checkKey = CommonService::checkKey(['amp_action', 'amp_acname','amp_data','amp_type','amp_id'],$input);
                if($checkKey['code']!=1){
                    return $checkKey;
                }else{
                    $update['amp_acname'] = $input['amp_acname'];
                    $update['amp_data'] = is_array($input['amp_data'])?json_encode($input['amp_data'],JSON_UNESCAPED_UNICODE):$input['amp_data'];
                    $update['amp_type'] = $input['amp_type'];
                    $res = DB::table('admin_excel_person')
                        ->where('amp_id',$input['amp_id'])
                        ->where('amp_admin_id',$user_infos['adm_id'])
                        ->where('amp_shop_id',$user_infos['adm_shop_id'])
                        ->where('amp_action',$input['amp_action'])
                        ->update($update);
                    if($res){
                        OperationLog::addLog($user_info, $ip, '导出模板', '编辑模板', '模板名称：'.$input['amp_type']."(".$input['amp_acname'].")");
                        return ['code' => 200, 'msg' => '操作成功', 'data' => []];
                    }else{
                        return ['code' => ErrorInc::MYSQL_FAILED, 'msg' => '操作失败', 'data' => []];
                    }
                }
            case 5:
                $checkKey = CommonService::checkKey(['amp_id','amp_type','amp_acname','amp_action'],$input);
                if($checkKey['code']!=1){
                    return $checkKey;
                }else{
                    $res = DB::table('admin_excel_person')
                        ->where('amp_id',$input['amp_id'])
                        ->where('amp_admin_id',$user_infos['adm_id'])
                        ->where('amp_shop_id',$user_infos['adm_shop_id'])
                        ->where('amp_action',$input['amp_action'])
                        ->delete();
                    if($res){
                        OperationLog::addLog($user_info, $ip, '导出模板', '删除模板', '模板名称：'.$input['amp_type']."(".$input['amp_acname'].")");
                        return ['code' => 200, 'msg' => '操作成功', 'data' => []];
                    }else{
                        return ['code' => ErrorInc::MYSQL_FAILED, 'msg' => '操作失败', 'data' => []];
                    }
                }
            default:
                return ['code' => ErrorInc::INVALID_PARAM, 'msg' => '参数异常', 'data' => []];
                break;
        }
    }
}