<?php
/*
|--------------------------------------------------------------------------
| 服务商管理 ((原来的 “系统设置/服务商管理” ) 服务提供商的管理)
|--------------------------------------------------------------------------
|  增删改查导出
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 15:11
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Service;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\AdminAddress;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\AdminKhacclist;
use App\Models\AdminKhaccount;
use App\Models\Certification;
use App\Models\InstallPerson;
use App\Models\SyncStores;
use App\Services\AdminService;
use App\Services\CategoryService;
use App\Services\CommonService;
use App\Services\DownloadService;
use App\Services\PjBrandsService;
use App\Services\ServiceProviderService;
use App\Services\ServiceTypesService;
use App\Services\SysMzStoresService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ServiceProviderExport;
use BlueCity\Core\Sdk\MiscSapi;
use Illuminate\Support\Facades\DB;

class ServiceProviderController extends BaseController
{
    public $dataService = null;
//    public $dataFields = ['admin_acc', 'admin_password', 'admin_name', 'company_name'];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules' => [
            'admin_acc' => 'required',
            'admin_password' => 'required|max:16|min:6',
            'enable' => 'required',
            'admin_name' => 'required',
            'ad_brand' => 'required',
            //'is_lidao' => 'required',
           // 'is_fsix' => 'required',
           // 'brand_service' => 'required',
            //'service_type' => 'required',
            'company_name' => 'required',
            'account' => 'required',
            'accountname' => 'required',
            'opeaccline' => 'required',
            'is_ice' => 'required',
            'admin_province' => 'required',
            'admin_city' => 'required',
           // 'ad_brand' => 'required|array',
         //   'agent_brand' => 'required|array',
           // 'ad_project' => 'required|array',
          //  'attribute' => 'array'
        ],
        'messages' => [
            'unique' => '该 :attribute 已存在'
        ],
        'attributes' => [
            'admin_acc' => '登录名',
            'admin_password' => '登录密码',
            'enable' => '登录密码',
            'admin_name' => '姓名',
            'ad_brand' => '经营品牌',
            //'is_lidao' => '是否为力道门店',
            'company_name' => '公司名称',
            'admin_county' => '所属城市',
            'admin_zuob' => '坐标',
            'account' => '账号',
            'accountname' => '账户名',
            'opeaccline' => '开户行',
            'is_ice' => '发票类型',
            'admin_province' => '所属省份',
            'admin_city' => '所属市',
            //'ad_brand' => '品牌',
          //  'agent_brand' => '代理品牌',
           // 'ad_project' => '经营项目',
          //  'attribute' => '门店属性',
            //'is_fsix' => 'F6类型',
           // 'brand_service' => '品牌服务',
           // 'service_type' => '门店服务类型'
        ]
    ];

    public function __construct()
    {
        $service = new ServiceProviderService();
        $this->bootWithService($service);
    }

    /**
     * @api {post} /api/service/serviceProvider 列表页
     * @apiGroup 服务商管理
     * @apiName 列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 派单系统服务商管理，服务商是为系统提供最终服务的单位，最终工单将派发到服务商手里
     *
     * @apiParam  {string} token 授权token
     * @apiParam  {int} page 页码
     * @apiParam  {int} page_size 每页数量
     * @apiParam  {string} type    结算方式 1：公司；2：个人
     * @apiParam  {string}  unified 统一价格 1：是；2：否
     * @apiParam  {string} company_name  公司名称（搜索）
     * @apiParam  {string}  reward 奖罚设置1.开启2.关闭
     * @apiParam  {string} enable 账号状态（搜索）；1：开启；2：关闭
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "ErrorCode": 1,
     * "ErrorMessage":"成功",
     * "data": {
     * "list": [
     * {
     * "id": 41,
     * "admin_acc": "ceshi-李帅",
     * "admin_name": "ceshi-李帅",
     * "admin_group": 7,
     * "type": null,
     * "invoice": "3",
     * "company_name": "李帅测试冶炼厂",
     * "ptid": "0",
     * "enable": "启用",//账号状态
     * "is_sord": 1,
     * "reward": "关闭",//奖惩设置
     * "phone": "13811333238",
     * "accountname": "",
     * "account": null,
     * "opeaccline": null,
     * "certification_num": null,//门店代码
     * "ser_varcode": null,
     * "bmmc_name": "系统管理员"//所属部门
     * "unified": "非统一价格",//是否统一价格
     * "brand_name": "康师傅",
     * "ser_varcode": "服务商瓦尔塔编号",
     * "ser_yycode": "用友系统编号",
     * "mouth_pay":"月结"
     * },
     * ...
     * ],
     * "page": {
     * "page": 1,//页码
     * "page_size": 2,//每页数量
     * "count": 379,//总数
     * "allPage": 190//总页数
     * }
     * }
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function index(Request $request)
    {
        $searchRequest = Input::all();
        $colums = [
            'admin.id AS id',
            'admin.admin_acc AS admin_acc',
            'admin.admin_name AS admin_name',
            'admin.admin_groupnew AS admin_groupnew',
            'admin.type AS type',
            'admin.invoice AS invoice',
            'admin.company_name AS company_name',
            'admin.ptid AS ptid',
            'admin.mouth_pay AS mouth_pay',
            'admin.enable AS enable',
            'admin.agent_brand as agent_brand',
            'admin.is_sord AS is_sord',
            'admin.unified AS unified',
            'admin.reward AS reward',
            'admin_infor.phone AS phone',
            'admin_infor.accountname AS accountname',
            'admin_infor.account AS account',
            'admin_infor.opeaccline AS opeaccline',
            'admin_infor.service_name as service_name',
            'certification_num',
            'ser_varcode',
            'ser_yycode',
            'admin_province',
            'admin_city',
            'admin_county',
            'admin_infor.admin_address',
            'admin_infor.admin_dressi',
            'verstoreid',
            'verstorename',
            'is_fsix',
            'ad_alias',
            'brand_service',
            'ad_brand',
            'ad_project'

        ];
        $page = Request()->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $pageSize = (int)Request()->input('page_size', 20);

        $result = $this->dataService->search($searchRequest, $colums, $page, $pageSize);


        //导出 start
        $session = $request->get('session_token');
        if ($request->input('is_excel') == 1) {
            $sqls = $result['sqls'];
            $excel = new CommonController();
            return $excel->getExcelOut($request->input('Pri_id'), $sqls, $session);
        }
        unset($result['sqls']);
        //导出 end

        $list = $result['list'];

        $data = $this->dataService->formatPageContent($request->input('token'), $request->input('Pri_id'), $result,$searchRequest['Login_id']);

        if ($list) {
            return $this->success('获取成功', $data);
        } else {
            $data['list'] = [];

            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    /**
     * @api {post} /api/service/serviceProvider/search 服务商名称搜索
     * @apiGroup 服务商管理
     * @apiName 服务商名称搜索
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商名称搜索，没有关键字，按实用度列出前十位，有关键字列出关键字前十位
     *
     * @apiParam {string} keywords  搜索关键字
     * @apiParam  {string} token 授权token
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function search(Request $request)
    {
        $title = $request->get('keywords');

        $whereCondition = ['admin_name', 'LIKE', '%' . $title . '%'];
        $list = $this->dataService->search($whereCondition);
        return $list;
    }

    /**
     * @api {post} /api/service/serviceProvider/export 服务商导出
     * @apiGroup 服务商管理
     * @apiName 服务商导出
     * @apiVersion 1.0.0
     *
     * @apiDescription 派单系统服务商资料导出，这里只负责文件生成部分，下载文件转到 downloadController
     *
     * @apiParam  {string} token 授权token
     * @apiParam  {int} page 页码
     * @apiParam  {int} page_size 每页数量
     * @apiParam  {string} type    结算方式 1：公司；2：个人
     * @apiParam  {string}  unified 统一价格 1：是；2：否
     * @apiParam  {string} company_name  公司名称（搜索）
     * @apiParam  {string}  reward 奖罚设置1.开启2.关闭
     * @apiParam  {string} enable 账号状态（搜索）；1：开启；2：关闭
     *
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function export(Request $request)
    {
        $searchRequest = $request->all();
        $colums = [
            'admin.id AS id',
            'admin.admin_acc AS admin_acc',
            'admin.admin_name AS admin_name',
            'admin.admin_groupnew AS admin_groupnew',
            'admin.type AS type',
            'admin.invoice AS invoice',
            'admin.company_name AS company_name',
            'admin.ptid AS ptid',
            'admin.mouth_pay AS mouth_pay',
            'admin.enable AS enable',
            'admin.agent_brand as agent_brand',
            'admin.is_sord AS is_sord',
            'admin.unified AS unified',
            'admin.reward AS reward',
            'admin_infor.phone AS phone',
            'admin_infor.accountname AS accountname',
            'admin_infor.account AS account',
            'admin_infor.opeaccline AS opeaccline',
            'certification_num',
            'ser_varcode',
            'ser_yycode'
        ];
        $page = Request()->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $pageSize = (int)Request()->input('page_size', 0);
        $result = $this->dataService->search($searchRequest, $colums, $page, $pageSize);
        if ($result['list']->isEmpty()) {
            return $this->error('数据为空无法导出到文件', ErrorInc::DATA_EMPTY);
        }

        $fields = $request->get('export_fields') ?? [];
        //执行导出
        $fileName = '服务商列表导出' . date('Ymdhis');
        $fileExt = '.xlsx';
        $filePath = $this->dataService->export($result['list']->toArray(), $fields, $fileName, $fileExt);
        if (!$filePath) {
            return $this->error('文件存储失败', ErrorInc::MYSQL_FAILED);
        }

        $fileData = [];
        $fileData['file_name'] = $fileName;
        $fileData['file_type'] = 'serviceprovider-export';
        $fileData['file_path'] = $filePath;
        $fileData['file_ext'] = $fileExt;
        $fileData['comments'] = json_encode($request->all());

        $downLoad = (new DownloadService())->create($fileData);
//        $downLoad = true;
        if ($downLoad) {
            $downLoadID = $downLoad->id;

            return $this->success('文件下载生成成功', ['file_id' => $downLoadID]);
        } else {
            return $this->error('文件存储失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @api {post} /api/service/serviceProvider/create 服务商添加界面
     * @apiGroup 服务商管理
     * @apiName 服务商添加界面
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商添加界面需要的数据
     *
     * @apiParam  {string} token 授权token
     *
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "ErrorCode": 1,
     * "ErrorMessage": "获取成功",
     * "data": {
     * "ad_brand": [//品牌
     * {
     * "id": 1,
     * "brand_name": "博世"
     * },
     * {
     * "id": 2,
     * "brand_name": "瓦尔塔"
     * },
     * ...
     * ],
     * "ad_project": {
     * "1": "蓄电池更换",
     * "2": "轮胎更换",
     * "3": "汽车救援",
     * "4": "汽车保养",
     * "5": "汽车保险",
     * "6": "其他"
     * }
     * }
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function create(Request $request)
    {
        $session = Request()->get('session_token');//用户信息
        $brandList = PjBrandsService::getAll(); //品牌
        if($session['com_type'] ==2){
            $agent_brand = trim($session['com_brand'],',');
            $agent_brand = explode(',', $agent_brand);
            $brandList = CommonService::arrayFilterFieldValue($brandList,[['id'=>$agent_brand]]);
        }else{
            $agent_brand = trim($session['com_brand'],',');
            $agent_brand = explode(',', $agent_brand);
            $brandList = CommonService::arrayFilterFieldValue($brandList,[['id'=>$agent_brand]]);
        }
        $serviceTypes = CategoryService::getAll(); //服务类型
//        $serviceItems = ServiceItemsService::getAll(); //服务项目
        $serviceItems = PjBrandsService::dataList(); //门店属性
        $mouthPay = $this->dataService->getMouthPay();//结算方式
        $enable = $this->dataService->getEnable();//账号状态
        $fsix = $this->dataService->getFsixName();//是否为F6
      //  $brandservice = $this->dataService->getBrandService();//服务门店类型
        $serviceType = $this->dataService->getServiceType();//门店服务类型
        if ($brandList) {
            $data['ad_brand'] = $brandList;//经营品牌
            $data['agent_brand'] = $brandList;//代理品牌
            $data['ad_project'] = $serviceTypes;//经营项目
            $data['attrubite'] = $serviceItems;//门店属性
            $data['mouthPay'] = $mouthPay;//结算方式
            $data['enable'] = $enable;//账号状态
           // $data['fsix'] = $fsix;//是否为F6
          //  $data['brandservice'] = $brandservice;//品牌服务
            $data['serviceType'] = $serviceType;//门店服务类型

            return $this->success('获取成功', $data);
        } else {
            return $this->error('请设置商品品牌', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @api {post} /api/service/serviceProvider/store 新增服务商
     * @apiGroup 服务商管理
     * @apiName 新增服务商
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商添加到数据库
     *
     * @apiParam {string} token 授权token
     * @apiParam {string} admin_acc 登录名
     * @apiParam {string} admin_password 密码
     * @apiParam {int} enable 账号状态；1：启用；2：停用
     * @apiParam {string}  admin_name 、用户名
     * @apiParam {string}  phone 手机号
     * @apiParam {int}  type 结算对象；1：公司；2：个人
     * @apiParam {string}  qq QQ号码
     * @apiParam {string}  ad_brand 经营品牌
     * @apiParam {string}  agent_brand 代理品牌
     * @apiParam {string}  ad_project 经营项目
     * @apiParam {string} ad_urgent[] 特殊订单类型；10：加急；20：夜间
     * @apiParam {int}  is_lidao 是否为力道门店；1：普通；2：力道
     * @apiParam {string}  children_id    否    string    力道下属服务商(id以逗号分隔)，为力道门店时必选
     * @apiParam {string} service_name 公司名称
     * @apiParam {string}  company_name 服务中心名称
     * @apiParam {string}  admin_dressi 绑定门店地址
     * @apiParam {string} admin_county 所属城市
     * @apiParam {string}  admin_zuob 坐标
     * @apiParam {string}  account 账号
     * @apiParam {string}  qsaccount 结算号
     * @apiParam {string}  accountname 账户名
     * @apiParam {string}  opeaccline 开户行
     * @apiParam {int}   is_ice 发票 1：是；2：否
     * @apiParam {int}   invoice 1:专票；2：普票
     * @apiParam {int}   fdeduct  发票税点
     * @apiParam {int}   deduct  发票扣点
     * @apiParam {string}  admin_province 服务区域省
     * @apiParam {string}   admin_city 服务区域市
     * @apiParam {string}   sheng[0][ad_sheng] 省
     * @apiParam {string}   sheng[0][ad_shi] 市
     * @apiParam {string}   sheng[0][ad_xian] 县
     * @apiParam {string}   sheng[0][ad_address] 详细地址
     * @apiParam {string}   sheng[0][s_comname] 公司名称
     * @apiParam {string}   sheng[0][s_jingwei] 经纬度
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "ErrorCode": 1,
     * "ErrorMessage": "获取成功",
     * "data": {
     * "ad_brand": [//品牌
     * {
     * "id": 1,
     * "brand_name": "博世"
     * },
     * {
     * "id": 2,
     * "brand_name": "瓦尔塔"
     * },
     * ...
     * ],
     * "ad_project": {//经营项目
     * "1": "蓄电池更换",
     * "2": "轮胎更换",
     * "3": "汽车救援",
     * "4": "汽车保养",
     * "5": "汽车保险",
     * "6": "其他"
     * }
     * }
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function store(Request $request)
    {
        $data = $request->all();
        if ($this->validateRules) {
            $validate = validator()->make($data, $this->validateRules['rules'], $this->validateRules['messages'], $this->validateRules['attributes']);
            if ($validate->fails()) {
                $error = CommonService::validatorToString($validate);
                return $this->error($error, ErrorInc::INVALID_PARAM);
            }
        }
        $session = $request->get('session_token');
        //保存主要信息
        $adminData = $request->only(['enable', 'company_name', 'is_lidao', 'admin_name', 'admin_acc', 'type','brand_service','service_type', 'admin_groupnew']);
        $admin_acc = Admin::where("admin_acc",$adminData['admin_acc'])->where("company_id",$session['company_id'])->first();
        if($admin_acc){
            return $this->error('账户名已存在', ErrorInc::INVALID_PARAM);
        }
        if(is_array($adminData['service_type'])){
            $adminData['service_type'] = implode(',', $adminData['service_type']);
        }

//        $adminData = $request->only(array_keys($this->validateRules['rules']));
        $adminData = $this->_setAdminData($adminData, $request);
        $adminData['company_id'] = $session['company_id'];
        $adminData['company_type'] = $session['com_type'];

        if ($adminData['admin_groupnew'] == 3) {//经销商新增一个公司
            $adminData['admin_groupnew'] = 3;
            $com_data['com_type'] = 2;
            $com_data['com_name'] = $data['service_name'];
            $com_data['com_phone'] = $data['phone'];
            $com_data['com_start_time'] = date('Y-m-d H:i:s');
            $com_data['com_create_time'] = date('Y-m-d H:i:s');
            $com_data['com_end_time'] = date('Y-m-d H:i:s', strtotime('+50 year'));
            $com_data['com_admin_id'] = $session['id'];
            $com_data['com_parent_id'] = $session['com_parent_id'];
            $com_data['com_brand'] = $adminData['agent_brand'];
            $company_id = DB::table('company')->insertGetId($com_data);
            $adminData['company_id'] = $company_id;
            // 新增默认仓库
            $add_ware['shck_ckmc'] = '默认仓库';
            $add_ware['company_id'] = $company_id;
            $ware_id = DB::table('warehouse')->insertGetId($add_ware);
        }
        $adminID = AdminService::insertData($adminData);
        if ($adminID) {
            //保存资料信息
            $adminInfo = $request->only(['phone', 'qq','is_fsix','recom_amount']);
            $adminInfo['admin_id'] = $adminID;
            $adminInfo = $this->_setAdminInfo($adminInfo, $request);
            $infoRes = AdminService::insertAdminInfo($adminInfo);

            //保存地址信息
            if ($request->input('sheng')) {
                $sheng = $request->input('sheng');
                foreach ($sheng as $k => $v) {
                    $jingwei = explode(',', $v['s_jingwei']);
                    $arr['ad_company_name'] = $v['service_name'];
                    $arr['ad_sheng'] = $v['ad_sheng'];
                    $arr['ad_shi'] = $v['ad_shi'];
                    $arr['ad_xian'] = $v['ad_xian'];
                    $arr['ad_address'] = $v['ad_address'];
                    $arr['ad_longitude'] = $jingwei['0'];
                    $arr['ad_latitude'] = $jingwei['1'];
                    $arr['admin_id'] = $adminID;
                    $restAdd = DB::table('admin_address')->insert($arr);
                    if($k<1){
                        $installArr['install_province'] = $v['ad_sheng'];
                        $installArr['install_city'] = $v['ad_shi'];
                        $installArr['install_cuntry'] = $v['ad_xian'];
                        $installArr['install_address'] = $v['ad_address'];
                        $installArr['longitude'] =  $jingwei['0'];
                        $installArr['latitude'] =  $jingwei['1'];
                    }
                }
            }

            //Certification 设置
            $faker = $this->_setCertificate($request);
            $faker['ser_id'] = $adminID;
            $certifRes = AdminService::insertCertification($faker);

            //ose_serid 设置
            $rea = AdminService::insertScoresSend(array('ose_serid' => $adminID));

            if ($infoRes && $certifRes && $rea) {
                $installArr['check_code'] = $faker['certification_num'].'1001';
                $installArr['cd_ids'] = 1;
                $installArr['install_name'] = $adminData['admin_acc'];
                $installArr['install_phone'] = $adminInfo['phone'];
                $installArr['installation'] = 0;
                $installArr['admin_id'] = $adminID;
                $installArr['company_id'] =  $session['company_id'];
                $installArr['affiliation']   = '1';
                $installArr['install_password1'] = $installArr['check_code'];
                $installArr['install_password'] = md5($installArr['check_code']);
                InstallPerson::insert($installArr);

                $content = $session['admin_acc'] . "成员" . $request->input('admin_acc');
                $this->insertingLog('添加，', '', $content, '服务商管理', $request->ip(), $session['admin_acc']);//日志
                DB::commit();
                if ($adminData['admin_groupnew'] == 3) {//经销商新增一个公司
                    CommonService::resetToken($session);
                }
                return response()->json(['Data' => '', 'ErrorMessage' => '添加成功', 'ErrorCode' => 1]);
            } else {
                DB::rollback();
                return response()->json(['Data' => '', 'ErrorMessage' => '添加失败', 'ErrorCode' => 2]);
            }
        } else {
            DB::rollback();
            return response()->json(['Data' => '', 'ErrorMessage' => '添加失败', 'ErrorCode' => 2]);
        }
    }

    private function _setCertificate(Request $request)
    {
        $certification_num = (new Certification())->orderBy('certification_num', 'desc')
            ->value('certification_num');

        if ($certification_num) {
            $doinb = $certification_num + 1;
            $bin = strpos($doinb, "4");
            if ($bin) {
                $faker['certification_num'] = str_replace("4", '5', $doinb);
            } else {
                $faker['certification_num'] = $doinb;
            }
        } else {
            $faker['certification_num'] = "1001";
        }
        $faker['company_name'] = $request->input('company_name');
        $faker['creacter'] = $request->get('session_token')['admin_acc'] ?? '';
        $faker['ser_varcode'] = $request->input('ser_varcode') ?? '';//瓦尔塔编号
        $faker['ser_yycode'] = $request->input('ser_yycode') ?? '';//用友编号

        return $faker;
    }

    private function _setAdminData($adminData, Request $request)
    {
        $adminData['admin_password'] = md5($request->input('admin_password'));//密码
        $adminData['admin_groupnew'] = $request->input('admin_groupnew',2);//2服务商3经销商
        $adminData['mouth_pay'] = $request->input('mouth_pay', 1);//结算状态
        $adminData['unified'] = $request->input('unified', 1);//价格状态
        $adminData['reward'] = $request->input('reward', 1);//奖惩设置
        $adminData['admin_group'] = 2;//旧版服务商

        //经营品牌
      //  $adminData['ad_brand'] = implode(',', $request->input('ad_brand'));

        //代理品牌
        $adminData['agent_brand'] = implode(',', $request->input('ad_brand'));
        //经营项目
       // $adminData['ad_project'] = implode(',', $request->input('ad_project'));
        /*if ($request->input('attribute')) {//门店属性
            $adminData['attribute'] = implode(',', $request->input('attribute'));
        }*/

        if ($request->input('ad_urgent')) {//特殊订单类型
            if ($request->input('ad_urgent') != "") {
                $adminData['ad_urgent'] = ",";
                foreach ($request->input('ad_urgent') as $ku => $vu) {
                    $adminData['ad_urgent'] .= $vu . ",";
                }
            } else {
                if (!empty($adminData)) {
                    $adminData['ad_urgent'] = "";
                }
            }
        }
        if ($request->input('is_ice') == 1) {//发票 是
            $adminData['deduct'] = $request->input('fdeduct') . ',' . $request->input('deduct');//扣点数值.
            $adminData['invoice'] = $request->input('invoice');//增\普票
        }
        if ($request->input('is_ice') == 2) {//发票否
            $adminData['deduct'] = '0,' . $request->input('deduct');//扣点数值.
            $adminData['invoice'] = 3;//增\普票(不开票)
        }

        return $adminData;
    }

    private function _setAdminInfo($adminInfo, $request)
    {
        if ($request->input('is_ice') == 1) {//发票 是
            $adminInfo['service_name'] = trimall($request->input('service_name'));//公司
        }
        if ($request->input('is_ice') == 2) {//发票否
            $adminInfo['service_name'] = trimall($request->input('service_name'));//公司
        }
        $adminInfo['admin_dressi'] = trimall($request->input('admin_dressi'));//门店地址
        $adminInfo['account'] = trimall($request->input('account'));//账号
        $adminInfo['khaccount'] = trimall($request->input('khaccount'));//清算单号
        $adminInfo['accountname'] = trimall($request->input('accountname'));//账户名
        $adminInfo['opeaccline'] = trimall($request->input('opeaccline'));//开户行
        $adminInfo['head_phone'] = trimall($request->input('head_phone'));//派单负责人电话

        if ($request->input('ad_sheng') != '省份' && $request->input('ad_shi') != '地级市' && $request->input('ad_xian') != "市、县级市") {
            $adminInfo['admin_province'] = $request->input('ad_sheng');//省
            $adminInfo['admin_city'] = $request->input('ad_shi');//市
            $adminInfo['admin_county'] = $request->input('ad_xian');//县
        } else {
            $adminInfo['admin_province'] = $request->input('sheng')[0]['ad_sheng'];//省
            $adminInfo['admin_city'] = $request->input('sheng')[0]['ad_shi'];//市
            $adminInfo['admin_county'] = $request->input('sheng')[0]['ad_xian'];//县
        }
        $adminInfo['verstoreid'] = $request->input('verstoreid')??'';//京东门店编号
        $adminInfo['verstorename'] = $request->input('verstorename')??'';//京东名称

        $zuob = trimall($request->input('admin_zuob'));
        if ($zuob) {
            $zuob = explode(',', $zuob);
            $adminInfo['admin_longitude'] = $zuob[0] ?? '';//市
            $adminInfo['admin_latitude'] = $zuob[1] ?? '';//县
        }

        return $adminInfo;
    }

    /**
     * @api {post} /api/service/serviceProvider/edit 编辑服务商界面
     * @apiGroup 服务商管理
     * @apiName 编辑服务商界面
     * @apiVersion 1.0.0
     *
     * @apiDescription 接口描述
     *
     * @apiParam {String} id  id号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     * "Data": "",
     * "ErrorMessage": "编辑成功",
     * "ErrorCode": 1
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function edit(Request $request)
    {
        $id = $request->input('id');
        $result = (new AdminService)->getAdminByID($id);
        if (empty($result)) {
            return $this->error('数据不存在', ErrorInc::DATA_EMPTY);
        }
        $result = $result->toArray();
        if ($result['invoice'] == 3) {//不开票
            $result['is_ice'] = '2';
        } else {
            $result['is_ice'] = '1';
        }
        $result['admin_password'] = '';
        $result['ad_urgent'] = explode(',', trim($result['ad_urgent'], ','));//加急，夜间
        $ad_brand = explode(',', trim($result['ad_brand'], ','));//品牌
        $ad_brands = [];
        foreach ($ad_brand as $kv => $vv) {
            $ad_brands[] = (int)$vv;
        }
        $result['ad_brand'] = $ad_brands;

        $agent_brand = explode(',', trim($result['agent_brand'], ','));//代理品牌
        foreach ($agent_brand as $kv => $vv) {
            $agent_brands[] = (int)$vv;
        }
        $result['agent_brand'] = $agent_brands;

        $ad_project = explode(',', trim($result['ad_project'], ','));//经营项目
        foreach ($ad_project as $kv => $vv) {
            $ad_projects[] = (int)$vv;
        }
        $result['ad_project'] = $ad_projects;

        $attribute = explode(',', trim($result['attribute'], ','));//经营项目
        foreach ($attribute as $kv => $vv) {
            $attributes[] = (int)$vv;
        }

        $result['attribute'] = $attributes;

        $service_type = explode(',', trim($result['service_type'], ','));//经营项目
        foreach ($service_type as $kv => $vv) {
            $service_types[] = (int)$vv;
        }

        $result['service_type'] = $service_types;

        if ($result['children_id'] != '') {
            $para['id_searchin'] = $result['children_id'];
            $list = AdminService::getAdmins($para);

            foreach ($list as $key => $val) {
                $serv[] = array('id' => $val['id'], 'company_name' => $val['company_name']);
            }
            $result['children_id'] = $serv;
        } else {
            $result['children_id'] = [];
        }
        $certification = Certification::where("ser_id", $id)->first();
        if (!empty($certification)) {
            $result['ser_varcode'] = $certification['ser_varcode'];
            $result['ser_yycode'] = $certification['ser_yycode'];
            $result['certification_num'] = $certification['certification_num'];
        } else {
            $result['ser_varcode'] = '';
            $result['ser_yycode'] = '';
            $result['certification_num'] = '';
        }
        $resy = AdminInfor::where('admin_id', $id)->first();
        if ($resy) {
            $resy = $resy->toarray();
            if ($resy['admin_longitude'] && $resy['admin_latitude']) {
                $result['zuob'] = $resy['admin_longitude'] . ',' . $resy['admin_latitude'];
            }
            if (isset($result)) {
                $result = array_merge($resy, $result);
            }
        }

        $deduct = explode(',', $result['deduct']);
        if (count($deduct) > 1) {
            $result['fdeduct'] = $deduct[0];
            $result['deduct'] = $deduct[1];
        } else {
            $result['fdeduct'] = 0;
            $result['deduct'] = 0;
        }

        $address = AdminAddress::where('admin_id', $id)->get();
        if ($address) {
            $address = $address->toArray();

            foreach ($address as $k => $v) {
                $arr[$k]['id'] = $v['id'];
                $arr[$k]['admin_id'] = $v['admin_id'];
                $arr[$k]['ad_sheng'] = $v['ad_sheng'];
                $arr[$k]['ad_shi'] = $v['ad_shi'];
                $arr[$k]['ad_xian'] = $v['ad_xian'];
                $arr[$k]['ad_address'] = $v['ad_address'];
                $arr[$k]['addresstext'] = $v['ad_sheng'] . $v['ad_shi'] . $v['ad_xian'] . $v['ad_address'];
                $arr[$k]['longitudelatitude'] = $v['ad_longitude'] . ',' . $v['ad_latitude'];
                $arr[$k]['s_jingwei'] = $v['ad_longitude'] . ',' . $v['ad_latitude'];
                $arr[$k]['service_name'] = $v['ad_company_name'];
            }
            $result['sheng'] = $arr;
        } else {
            $result['sheng'] = [];
        }
//        $data['result'] = $result;
//        $brandList = PjBrandsService::getAll(); //品牌
//        $serviceTypes = CategoryService::getAll(); //服务类型
//        $serviceItems = PjBrandsService::dataList(); //门店属性
//        $mouthPay = $this->dataService->getMouthPay();//结算方式
//        $enable = $this->dataService->getEnable();//账号状态
//        if ($brandList) {
//            $result['ad_brands'] = $brandList;//经营品牌
//            $result['agent_brands'] = $brandList;//代理品牌
//            $result['ad_projects'] = $serviceTypes;//经营项目
//            $result['attrubites'] = $serviceItems;//经营项目
//            $result['mouthPay'] = $mouthPay;//结算方式
//            $result['enable'] = $enable;//账号状态
//        }

        return $this->success('获取成功', $result);
    }

    /**
     * @api {post} /api/service/serviceProvider/update 更新服务商信息
     * @apiGroup 服务商管理
     * @apiName 更新服务商信息
     * @apiVersion 1.0.0
     *
     * @apiDescription 接口描述
     *
     * @apiParam {String} id  id号
     * @apiParam {string} token 授权token
     * @apiParam {string} admin_acc 登录名
     * @apiParam {string} admin_password 密码
     * @apiParam {int} enable 账号状态；1：启用；2：停用
     * @apiParam {string}  admin_name 、用户名
     * @apiParam {string}  phone 手机号
     * @apiParam {int}  type 结算对象；1：公司；2：个人
     * @apiParam {string}  qq QQ号码
     * @apiParam {string}  ad_brand 经营品牌
     * @apiParam {string}  agent_brand 代理品牌
     * @apiParam {string}  ad_project 经营项目
     * @apiParam {string} ad_urgent[] 特殊订单类型；10：加急；20：夜间
     * @apiParam {int}  lidao 是否为力道门店；1：普通；2：力道
     * @apiParam {string}  children_id    否    string    力道下属服务商(id以逗号分隔)，为力道门店时必选
     * @apiParam {string} service_name 公司名称
     * @apiParam {string}  company_name 服务中心名称
     * @apiParam {string}  admin_dressi 绑定门店地址
     * @apiParam {string} admin_county 所属城市
     * @apiParam {string}  admin_zuob 坐标
     * @apiParam {string}  account 账号
     * @apiParam {string}  accountname 账户名
     * @apiParam {string}  opeaccline 开户行
     * @apiParam {int}   is_ice 发票 1：是；2：否
     * @apiParam {int}   invoice 1:专票；2：普票
     * @apiParam {int}   fdeduct  发票税点
     * @apiParam {int}   deduct  发票扣点
     * @apiParam {string}  admin_province 服务区域省
     * @apiParam {string}   admin_city 服务区域市
     * @apiParam {string}   sheng[][ad_sheng] 省
     * @apiParam {string}   sheng[][ad_shi] 市
     * @apiParam {string}   sheng[][ad_xian] 县
     * @apiParam {string}   sheng[][ad_address] 详细地址
     * @apiParam {string}   sheng[][s_comname] 公司名称
     * @apiParam {string}   sheng[][s_jingwei] 经纬度
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     * "Data": "",
     * "ErrorMessage": "编辑成功",
     * "ErrorCode": 1
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function update(Request $request)
    {
        $id = $request->input('id');
        if(!$request->filled('id')){
            return $this->error('缺少数据编号', ErrorInc::INVALID_PARAM);
        }
        $data = $request->all();
        if ($this->validateRules) {
            $rules = $this->validateRules['rules'];
            $rules['admin_acc'] = 'required';
            unset($rules['admin_password']);
            $validate = validator()->make($data, $rules , $this->validateRules['messages'], $this->validateRules['attributes']);
            if ($validate->fails()) {
                $error = CommonService::validatorToString($validate);

                return $this->error($error, ErrorInc::INVALID_PARAM);
            }
        }
        $session = $request->get('session_token');
        $admin_acc = Admin::where("admin_acc",$request->input('admin_acc'))->where("company_id",$session['company_id'])->where("id","!=",$id    )->first();
        if($admin_acc){
            return $this->error('账户名已存在', ErrorInc::INVALID_PARAM);
        }
        if ($request->filled('admin_password')) {
            if (!preg_match("/^[a-zA-Z\d_]{8,}$/", $request->input('admin_password'), $array)) {
                return response()->json(['Data' => '', 'ErrorMessage' => '密码格式不正确', 'errorCode' => 8]);
            }
            $post['admin_password'] = md5($request->input('admin_password'));//密码
            $poss['back_pass'] = $request->input('admin_password');
        }

        $post['enable'] = $request->input('enable');//是否启用
        $post['is_lidao'] = $request->input('is_lidao');//是否为立到门店
        $post['admin_name'] = $request->input('admin_name');//姓名
        $post['admin_acc'] = $request->input('admin_acc');

        if ($request->filled('admin_password')) {
            $post['admin_password'] = md5($request->input('admin_password'));
            $poss['back_pass'] = $request->input('admin_password');
        }

        if ($request->input('is_lidao') == 1) {
            $post['owner'] = '2';
        } else {
            if ($request->input('owner') == 1) {//是力道总店
                $post['owner'] = '1';
                $post['children_id'] = implode(',', $request->input('children_id'));
            } else {//不是力道总店
                $post['owner'] = '2';
                $post['children_id'] = "";
            }

        }
        $poss['phone'] = $request->input('phone');//电话
        $poss['qq'] = $request->input('qq');//QQ


        if ($request->input('ad_brand')) {
            $post['ad_brand'] = ","; //经营品牌
            foreach ($request->input('ad_brand') as $kb => $vb) {
                $post['ad_brand'] .= $vb . ",";
            }
        }

        if ($request->input('agent_brand')) {
            $post['agent_brand'] = ",";//代理品牌
            foreach ($request->input('agent_brand') as $kb => $vb) {
                $post['agent_brand'] .= $vb . ",";
            }
        }
        if ($request->input('ad_project')) {
            $post['ad_project'] = ",";//经营项目
            foreach ($request->input('ad_project') as $kp => $vp) {
                $post['ad_project'] .= $vp . ",";
            }
        }

        if ($request->input('ad_urgent')) {//特殊订单类型
            if ($request->input('ad_urgent') != "") {
                $post['ad_urgent'] = ",";
                foreach ($request->input('ad_urgent') as $ku => $vu) {
                    $post['ad_urgent'] .= $vu . ",";
                }
            } else {
                $post['ad_urgent'] = "";
            }
        }
        $post['company_name'] = trimall($request->input('company_name'));//服务中心名称
        if ($request->input('is_ice') == 1) {
            $poss['service_name'] = trimall($request->input('service_name'));//公司
            $post['deduct'] = $request->input('fdeduct') . ',' . $request->input('deduct');//扣点数值.
            $post['invoice'] = $request->input('invoice');//增\普票
        }
        if ($request->input('is_ice') == 2) {
            $poss['service_name'] = trimall($request->input('service_name'));//公司
            $post['deduct'] = '0,' . $request->input('deduct');//扣点数值.
            $post['invoice'] = 3;//增\普票(不开票)
        }
        $post['type'] = $request->input('type');//结算对象
        $post['mouth_pay'] = $request->input('mouth_pay');//结算对象
        $post['brand_service'] = $request->input('brand_service');//品牌服务
        if(is_array($request->input('service_type'))){
            $post['service_type'] = implode(',',$request->input('service_type'));//门店服务类型
        }else {
            $post['service_type'] = $request->input('service_type');//门店服务类型
        }

        $poss['admin_dressi'] = trimall($request->input('admin_dressi'));//门店地址
        $poss['account'] = trimall($request->input('account'));//账号
        $poss['khaccount'] = trimall($request->input('khaccount'));//账号
        $poss['accountname'] = trimall($request->input('accountname'));//账户名
        $poss['opeaccline'] = trimall($request->input('opeaccline'));//开户行
        $poss['admin_province'] = $request->input('admin_province');//省
        $poss['admin_city'] = $request->input('admin_city');//市
        $poss['admin_county'] = $request->input('admin_county');//县
        $poss['head_phone'] = trimall($request->input('head_phone'));
        $zuob = trimall($request->input('admin_zuob'));
        $zuob = explode(',', $zuob);
        $poss['admin_longitude'] = $zuob[0];//市
        $poss['admin_latitude'] = $zuob[1];//县
        $poss['verstoreid'] = $request->input('verstoreid')??'';//京东门店编号
        $poss['verstorename'] = $request->input('verstorename')??'';//京东名称
        $poss['is_fsix'] = $request->input('is_fsix');//是否为F6
        $poss['recom_amount'] = $request->input('recom_amount');//推荐服务费

        try {
            DB::beginTransaction(); //开启事务

            $upAdm = Admin::where('id', $id)->update($post);
            $upInf = AdminInfor::where('admin_id', $id)->update($poss);
            $adRes = DB::table('admin_address')->where('admin_id', $id)->delete();

            if ($upAdm || $upInf || $adRes) {
                DB::commit();

                //省份地址更新
                $sheng = $request->input('sheng');
                foreach ($sheng as $k => $v) {
                    $jingwei = explode(',', $v['s_jingwei']);
                    $arr[$k]['ad_company_name'] = $v['service_name'];
                    $arr[$k]['ad_sheng'] = $v['ad_sheng'];
                    $arr[$k]['ad_shi'] = $v['ad_shi'];
                    $arr[$k]['ad_xian'] = $v['ad_xian'];
                    $arr[$k]['ad_address'] = $v['ad_address'];
                    $arr[$k]['ad_longitude'] = $jingwei['0'];
                    $arr[$k]['ad_latitude'] = $jingwei['1'];
                    $arr[$k]['admin_id'] = $id;
                    $restAdd = DB::table('admin_address')->insert($arr[$k]);
                }

                // certification更新
                $faker['ser_varcode'] = $request->input('ser_varcode');//瓦尔塔编号
                $faker['ser_yycode'] = $request->input('ser_yycode');//用友编号
                $certifRes = DB::table('certification')->where('ser_id', $id)->update($faker);

                //操作记录更新
                $session = $request->get('session_token');
                $content = $session['admin_acc'] . "成员";
                $this->insertingLog('编辑，', '', $content, '服务商管理', $request->ip(), $session['admin_acc']);//日志

                return $this->success('编辑成功');
            } else {
                DB::rollback();

                return $this->error('编辑失败', 2);
            }
        } catch (\Exception $e) {
            DB::rollback();

            return $this->error($e->getMessage(), 2);
        }
    }

    /**
     * @api {post} /api/service/serviceProvider/jingwei 获取经纬度
     * @apiGroup 服务商管理
     * @apiName 获取经纬度
     * @apiVersion 1.0.0
     *
     * @apiDescription 派单系统获取某个地址的经纬度
     *
     * @apiParam {String} address  地址信息
     * @apiParam {int} city  城市
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function jingwei(Request $request)
    {
        if(!$request->filled('address') || !$request->filled('city')){
            return $this->error('缺少必要地址参数', ErrorInc::INVALID_PARAM);
        }
        $address = $request->input('address');
        $city = $request->input('city');
        $url = "http://restapi.amap.com/v3/geocode/geo?key=bf7919b601432722e4353ba6358e9c10&address='" . $city . $address . "'&city='" . $city . "'&output='json'";
        $result = $this->http_get($url);

        $arr = json_decode($result, true);
        if ($arr['status'] == '1') {
            if (isset($arr['geocodes'][0]['location'])) {
                return $this->success('获取成功', $arr['geocodes'][0]['location']);
            } else {
                return $this->error('该地址无效', 2, []);
            }
        } else {
            return $this->error('获取失败', 2, []);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取门店信息
     * @param string shop_store_name 门店名称
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022-11-17 017 上午 10:48:58
     * |---------------------------------------------------------------------------------
     */
    public function searchShop ( Request $request ){
        $pop['shop_store_name'] = $request->input('shop_store_name');
        $store = SysMzStoresService::sysStore($pop, 'searchShop');
        return $store;
        if($store['ErrorCode']!=1){
            return $this->error('获取失败', ErrorInc::DATA_EMPTY, []);
        }else{
            return $store;
        }
    }

    /**
     * @api {post} /api/service/serviceProvider/bindRadius 绑定区域
     * @apiGroup 服务商管理
     * @apiName 绑定区域
     * @apiVersion 1.0.0
     *
     * @apiDescription 派单系统为某个服务商绑定可服务区域
     *
     * @apiParam {String} secretKey  地址信息
     * @apiParam {int} type  城市
     * @apiParam {int} id  城市
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function bindRadius(Request $request)
    {
        if ($request->filled('secretKey') && $request->filled('type') && $request->input('id')) {
            if($request->input('type')==3){
                $pop['shop_id'] = $request->input('secretKey');
                $pop['ser_id'] = $request->input('id');
                $resp = SysMzStoresService::sysStore($pop, 'correlation');
                if ($resp['ErrorCode'] != 1) {
                    return $this->error($resp['ErrorMessage'], $resp['ErrorCode']);
                }else{
                    $stores['secretKey'] = $request->input('secretKey');
                    $stores['ser_id'] = $request->input('id');
                    $stores['creact_time'] = date("Y-m-d H:i:s");
                    $stores['type'] = 3;
                    SyncStores::insert($stores);
                    $company = AdminService::getAdminBy('id', $request->input('id'), ['company_name']);
                    $content = '同步门店系统绑定：' . $company;
                    $this->insertingLog('添加，', '', $content, '服务商管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志
                    return $this->success('成功', $resp['data']);
                }
            }else {
                $url = "http://mktest.bluearp.com/index.php/api/v3/OtherSystemShop/secretKey";
                $time = date("Y-m-d H:i:s");
                $param = [
                    'ser_id' => $request->input('id'),
                    'type' => $request->input('type'),
                    'time' => $time,
                    'token' => md5(md5($time . 'c883e5e641818d993a2d8d966ca450bf')),
                    'secretKey' => $request->input('secretKey'),
                ];
                $resp = (new MiscSapi())->httpPost($url, $param);
                $resp = json_decode($resp, true);
                if ($request->input('type') == '2') {
                    $stores['secretKey'] = $request->input('secretKey');
                    $stores['ser_id'] = $request->input('id');
                    $stores['creact_time'] = date("Y-m-d H:i:s");
                    $stores['type'] = 2;
                    DB::beginTransaction();

                    SyncStores::insert($stores);
                }
                if ($resp['code'] != 200) {
                    if ($request->input('type') == '2') {
                        DB::rollback();
                    }
                    return $this->error($resp['msg'], $resp['code']);
                } else {
                    if ($request->input('type') == '2') {
                        DB::commit();
                    }
                    $company = AdminService::getAdminBy('id', $request->input('id'), ['company_name']);
                    $content = '同步门店系统绑定：' . $company;
                    $this->insertingLog('添加，', '', $content, '服务商管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志
                    return $this->success('成功', $resp['data']);
                }
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {post} /api/service/serviceProvider/delete 服务商删除
     * @apiGroup 服务商管理
     * @apiName 服务商删除
     * @apiVersion 1.0.0
     *
     * @apiDescription 派单系统服务商删除，软删除设置隐藏属性
     *
     * @apiParam {int} id  指定要删除的id
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $entity = (new AdminService)->getAdminByID($id);
        if ($entity) {
            $this->dataService->setEnable($id, 0);

            return $this->success('删除成功');
        } else {
            return $this->error('该内容不存在', ErrorInc::DATA_EMPTY);
        }
    }


    /**
     * name 修改密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/12/29
     */
    public function editServicePassword(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('ID不正确',ErrorInc::FAILED_PARAM);exit;
        }
        $pass = trim($request->input('admin_password'));
        $pass_two = trim($request->input('admin_password_confirmation'));
        if($pass!=$pass_two){
            return $this->error('两次密码不相同', ErrorInc::FAILED_PARAM);exit;
        }
        if (!preg_match("/^[a-zA-Z\d_]{8,}$/", $pass, $array)) {
            return response()->json(['Data' => '', 'ErrorMessage' => '密码格式不正确', 'errorCode' => 8]);
        }

        $id = intval(trim($request->input('id')));
        $exsit = Admin::where('id', $id)->value('admin_acc');
        if(!$exsit){
            return $this->error('不存在此用户', ErrorInc::MYSQL_FAILED);exit;
        }

        $post['admin_password'] = md5($pass);//密码
        $post['update_time'] = time();
        $upAdm = Admin::where('id', $id)->update($post);
        if($upAdm){
            $this->insertingLog("修改密码，",'',$exsit."，密码修改了","服务商管理",$request->ip(), $request->get('session_token')['admin_acc']);//日志
           // ($type, $order_number, $content, $model, $ip, Re);
            return $this->success('修改成功');exit;
        }else{
            return $this->error('修改失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 查看结算信息
     * @param string id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/1/24 18:11
     * |---------------------------------------------------------------------------------
    */
    public function getSettleData ( Request $request ){
        if($request->filled('id')){
            $db = new AdminInfor();
            $data = CommonService::getMysqlData($db, ['admin_id'=>$request->input('id')],['accountname','account','opeaccline'],[],'first');
            if(empty($data)){
                return $this->error('暂无数据', ErrorInc::FAILED_PARAM);exit;
            }else{
                return $this->success('获取成功',$data);
            }

        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取账号列表
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/8 18:33
     * |---------------------------------------------------------------------------------
    */
    public function getAccountList ( Request $request ){
        if($request->filled('id')) {
            $admininfor = new AdminInfor();
            $default = CommonService::getMysqlData($admininfor, ['admin_id'=>$request->input('id')],['accountname as akl_accountname','account as akl_account','khaccount as akl_khaccount','id as akl_id','opeaccline as akl_opeaccline','admin_id as akl_adminid']);
            if($default){
                foreach( $default as $k => $v ){
                    $default[$k]['akl_state'] = 1;
                    $default[$k]['statename'] = '启用';
                    $default[$k]['akl_type'] = 1;
                    $default[$k]['typename'] = '银行卡';
                    $default[$k]['akl_wat'] = '';
                }
            }
            $adminkhacclist = new AdminKhacclist();
            $list = CommonService::getMysqlData($adminkhacclist, ['akl_adminid'=>$request->input('id')],['akl_account','akl_accountname','akl_khaccount','akl_opeaccline','akl_state','akl_type','akl_wat','akl_id','akl_adminid']);
            $stateName = ServiceProviderService::getAklStateName(true);
            $typeName = ServiceProviderService::getAklTypeName(true);
            $watType = ServiceProviderService::getWatType(true);
            if($list){
                foreach($list as $k => $v){
                    $list[$k]['statename'] = $stateName[$v['akl_state']]??'未定义';
                    $list[$k]['typename'] = $typeName[$v['akl_type']]??'未定义';
                    $list[$k]['watType'] = $watType[$v['akl_wat']]??'未定义';
                }
            }
            $data['default'] = $default;
            $data['list'] = $list;
            $data['typeName'] = ServiceProviderService::getAklTypeName();
            $data['stateName'] = ServiceProviderService::getAklStateName();
            $data['watType'] = ServiceProviderService::getWatType();
            return $this->success('获取成功',$data);
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
        }
        exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加门店结算账号
     * @param int akl_adminid 对应门店id
     * @param int company_name 门店名称
     * @param string akl_account 账号
     * @param string akl_accountname 账户名
     * @param string akl_opeaccline 开户行
     * @param string akl_khaccount 开户行行号
     * @param int akl_state 数据状态1正常2停用
     * @param int akl_type 数据类型1银行卡2支付宝3微信
     * @param string akl_wat 结算单类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/9 9:36
     * |---------------------------------------------------------------------------------
    */
    public function addOtherAccount ( Request $request ){
        $input = $request->only('akl_adminid','akl_account','akl_accountname','akl_opeaccline','akl_khaccount','akl_state','akl_type','akl_wat','company_name');
        $checkKey=CommonService::checkKey(['akl_adminid','akl_account','akl_accountname','akl_state','akl_type','akl_wat','company_name'],$input,array('akl_adminid'=>'门店id','akl_account'=>'账号','akl_accountname'=>'账户名','akl_state'=>'数据状态','akl_type'=>'数据类型','akl_wat'=>'结算单类型','company_name'=>'门店名称'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if($input['akl_type'] == 1 && !$request->filled('akl_opeaccline')){
            return $this->error('银行卡类型必须填写开户行', ErrorInc::INVALID_PARAM);exit;
        }
        $company_name = $input['company_name'];
        unset($input['company_name']);
        $rea = AdminKhacclist::where('akl_adminid',$input['akl_adminid'])->where('akl_wat',$input['akl_wat'])->first();
        if(!$rea){
            $stateName = ServiceProviderService::getAklStateName(true);
            $typeName = ServiceProviderService::getAklTypeName(true);
            if($input['akl_type'] != 1){
                $input['akl_opeaccline'] = $typeName[$input['akl_type']];
            }
            $session = $request->get('session_token');
            $ip = $request->ip();
            $input['akl_creactor'] = $session['admin_acc'];
            $input['akl_creactid'] = $session['id'];
            $res = AdminKhacclist::insert($input);
            if ($res) {
                $content = $company_name.',添加新账号:('.$input['akl_account'].')，类型：'.$stateName[$input['akl_state']].',状态：'.$typeName[$input['akl_type']];
                $this->insertingLog('添加账户信息，', $input['aka_account'], $content, '服务商管理', $ip, $session['admin_acc']);
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED);
            }
        }else{
            return $this->error('该结算单类型数据已存在', ErrorInc::REPEAT_SUBMIT);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑门店结算账号
     * @param int akl_adminid 对应门店id
     * @param int company_name 门店名称
     * @param string akl_account 账号
     * @param string akl_accountname 账户名
     * @param string akl_opeaccline 开户行
     * @param string akl_khaccount 开户行行号
     * @param int akl_state 数据状态1正常2停用
     * @param int akl_type 数据类型1银行卡2支付宝3微信
     * @param string akl_wat 结算单类型
     * @param int id 数据id
     * @param int type 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/9 14:08
     * |---------------------------------------------------------------------------------
    */
    public function editOtherAccount ( Request $request ){
        $input = $request->only('akl_adminid','akl_account','akl_accountname','akl_opeaccline','akl_khaccount','akl_state','akl_type','akl_wat','company_name','id','type');
        $checkKey=CommonService::checkKey(['akl_adminid','akl_account','akl_accountname','akl_state','akl_type','id','type'],$input,array('akl_adminid'=>'门店id','akl_account'=>'账号','akl_accountname'=>'账户名','akl_state'=>'数据状态','akl_type'=>'数据类型','id'=>'数据编号','type'=>'编辑类型'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if(!in_array($input['type'], ['1','2'])){
            return $this->error('编辑类型错误', ErrorInc::INVALID_PARAM);exit;
        }
        if($input['akl_type'] == 1 && !$request->filled('akl_opeaccline')){
            return $this->error('银行卡类型必须填写开户行', ErrorInc::INVALID_PARAM);exit;
        }
        $company_name = $input['company_name'];
        $id = $input['id'];
        unset($input['id']);
        unset($input['company_name']);
        if($input['type'] == '1') {
            $poss['accountname'] = $input['akl_accountname'];
            $poss['account'] = $input['akl_account'];
            $poss['khaccount'] = $input['akl_khaccount'];
            $poss['opeaccline'] = $input['akl_opeaccline'];
            $res = AdminInfor::where('id',$id)->update($poss);
            if($res) {
                return $this->success('操作成功');
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED);
            }
        }else{
            if(!isset($input['akl_wat'])){
                return $this->error('结算单类型未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
            }
            unset($input['type']);
            $akl_id = AdminKhacclist::where('akl_id',$id)->value('akl_id');
            if(!$akl_id){
                return $this->error('数据不存在', ErrorInc::DATA_EMPTY);exit;
            }
            $rea = AdminKhacclist::where('akl_adminid', $input['akl_adminid'])->where('akl_wat', $input['akl_wat'])->where('akl_id','!=',$id)->first();
            if (!$rea) {
                $stateName = ServiceProviderService::getAklStateName(true);
                $typeName = ServiceProviderService::getAklTypeName(true);
                if ($input['akl_type'] != 1) {
                    $input['akl_opeaccline'] = $typeName[$input['akl_type']];
                }
                $input['akl_updatetime'] = date("Y-m-d H:i:s");
                $session = $request->get('session_token');
                $ip = $request->ip();
                $res = AdminKhacclist::where('akl_id',$id)->update($input);
                if ($res) {
                    $content = $company_name . ',编辑账号:(' . $input['akl_account'] . ')，类型：' . $stateName[$input['akl_state']] . ',状态：' . $typeName[$input['akl_type']];
                    $this->insertingLog('编辑账户信息，', $input['aka_account'], $content, '服务商管理', $ip, $session['admin_acc']);
                    return $this->success('操作成功');
                } else {
                    return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED);
                }
            } else {
                return $this->error('该结算单类型数据已存在', ErrorInc::REPEAT_SUBMIT);
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加数据
     * @param string aka_account 开户行账号
     * @param string aka_name 开户行名称
     * @param string aka_type 数据状态1启用2停用
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/7 19:30
     * |---------------------------------------------------------------------------------
     */
    public function addKhAccount ( Request $request ){
        $input = $request->only('aka_account','aka_name');
        $checkKey=CommonService::checkKey(['aka_account','aka_name'],$input,array('aka_account'=>'开户行账号','aka_name'=>'开户行名称'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $session = $request->get('session_token');
        $ip = $request->ip();
        $list = AdminKhaccount::where('aka_account',$input['aka_account'])->whereOr('aka_name',$input['aka_name'])->first();
        if(!$list) {
            $input['aka_creactor'] = $session['admin_acc'];
            $input['aka_creactid'] = $session['id'];
            $input['aka_type'] = 1;
            $input['aka_creactime'] = date("Y-m-d H:i:s");
            $res = AdminKhaccount::insert($input);
            $content = "添加" . $input['aka_name'] . "(" . $input['aka_account'] . ")";
            if ($res) {
                $this->insertingLog('添加开户行信息，', $input['aka_account'], $content, '服务商管理', $ip, $session['admin_acc']);
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED);
            }
        }else{
            $list = CommonService::dataToArray($list);
            return $this->error('数据已存在,系统名称:'.$list['aka_name'].'('.$list['aka_account'].')', ErrorInc::REPEAT_SUBMIT);
        }
        exit;
    }

}
