ProjectLogic.php 25.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
<?php

namespace App\Http\Logic\Aside\Project;

use App\Enums\Common\Code;
use App\Exceptions\AsideGlobalException;
use App\Models\Com\NoticeLog;
use App\Models\Devops\ServerConfig;
use App\Models\Project\ProjectRenew;
use App\Models\Template\BSettingTemplate;
use App\Models\Template\Setting;
use App\Models\User\ProjectMenu;
use App\Models\User\ProjectRole;
use App\Services\SyncService;
use App\Utils\HttpUtils;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Arr as SupArr;
use App\Helper\Arr;
use App\Helper\Common;
use App\Helper\FormGlobalsoApi;
use App\Http\Logic\Aside\BaseLogic;
use App\Models\Channel\Channel;
use App\Models\Channel\User;
use App\Models\Channel\Zone;
use App\Models\Domain\DomainInfo;
use App\Models\Inquiry\InquirySet;
use App\Models\Manage\Manage;
use App\Models\Project\After;
use App\Models\Project\DeployBuild;
use App\Models\Project\DeployOptimize;
use App\Models\Project\Payment;
use App\Models\Project\Project;
use App\Models\Task\Task;
use App\Services\ProjectServer;
use Hashids\Hashids;
use App\Models\User\User as UserModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use App\Http\Logic\Aside\Domain\DomainInfoLogic;

/**
 * Class ProjectLogic
 * @package App\Http\Logic\Aside\Project
 * @author zbj
 * @date 2023/4/26
 */
class ProjectLogic extends BaseLogic
{
    public function __construct()
    {
        parent::__construct();
        $this->param = $this->requestAll;
        $this->model = new Project();
    }

    /**
     * @remark :获取当前数据详情
     * @name   :getProjectInfo
     * @author :lyh
     * @method :post
     * @time   :2023/7/28 17:11
     */
    public function getProjectInfo($id){
        $info = $this->model->with('payment')->with('deploy_build')->with('deploy_optimize')->with('online_check')
            ->with('project_after')->where(['id'=>$id])->first()->toArray();
        $info['online_check']['name'] = (new Manage())->getName(!empty($info['online_check']['created_manage_id']) ?? '');
        $info['deploy_optimize']['minor_keywords'] = !empty($info['deploy_optimize']['minor_keywords']) ? json_decode($info['deploy_optimize']['minor_keywords']) : [];
        $info['init_domain'] = $this->getInitDomain($info['serve_id'])['domain'];
        if($info['extend_type'] != 0){
            $info['type'] = $info['extend_type'];
        }
        //升级项目初始上传配置
        if(empty($info['upload_config'])){
            $info['upload_config'] =["upload_max_num"=>100, "allow_file_type"=>"doc,docx,xls,xlsx,pdf,txt,csv,png,jpg,jpeg", "upload_max_size"=>5];
        }
        if(empty($info['channel'])){
            $info['channel'] = ["user_id"=>"", "zone_id"=>"", "channel_id"=>""];
        }
        if(empty($info['payment']['renewal_record'])){
            $info['payment']['renewal_record'] = [["amount"=> null, "remark"=> null, "expire_at"=> null]];
        }
        if(isset($info['is_customized']) && $info['is_customized'] == 1){
            $info['is_visualization'] = json_decode($info['is_visualization']);
        }
        return $this->success($info);
    }

    /**
     * @remark :获取初始域名
     * @name   :getInitDomain
     * @author :lyh
     * @method :post
     * @time   :2023/9/16 9:40
     */
    public function getInitDomain($serve_id = ''){
        $domain = '';
        if(!empty($serve_id)){
            $serveModel = new ServerConfig();
            $info = $serveModel->read(['id'=>$serve_id]);
            if($info !== false){
                $domain = $info['init_domain'];
            }
        }
        return $this->success(['domain'=>$domain]);
    }

    /**
     * @remark :保存项目数据
     * @name   :projectSave
     * @author :lyh
     * @method :post
     * @time   :2023/8/30 11:57
     */
    public function projectSave(){
        DB::beginTransaction();
        try {
            if($this->param['type'] == Project::TYPE_SEVEN){
                //错误单直接返回,单独处理
                $this->setTypeSevenEdit($this->param);
            }else{
                //初始化项目
                $this->createProjectData($this->param);
                //保存项目信息
                $this->saveProject($this->param);
                //保存建站部署信息
                $this->saveProjectDeployBuild($this->param['deploy_build']);
                //保存付费信息
                $this->saveProjectPayment($this->param['payment']);
                //保存优化信息
                $this->saveProjectDeployOptimize($this->param['deploy_optimize']);
                //保存售后信息
                $this->saveProjectAfter($this->param['project_after']);
                //创建站点
//                $this->createSite($this->param);
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            $this->fail('请填写完整后再提交');
        }
        (new SyncService())->projectAcceptAddress($this->param['id']);
        return $this->success();
    }

    /**
     * @remark :保存项目
     * @name   :setExtendType
     * @author :lyh
     * @method :post
     * @time   :2023/8/30 12:14
     */
    public function saveProject($param){
        if($param['type'] == Project::TYPE_FIVE){
            $param['extend_type'] = Project::TYPE_FIVE;
            unset($param['type']);
        }
        if(isset($param['level']) && !empty($param['level'])){
            $param['level'] = Arr::arrToSet($param['level']);
        }
        if(isset($param['channel']) && !empty($param['channel'])){
            $param['channel'] = Arr::a2s($param['channel']);
        }
        if(isset($param['notice_file']) && !empty($param['notice_file'])){
            foreach ($param['notice_file'] as &$v1) {
                if(isset($v1['url']) && !empty($v1['url'])){
                    $v1['url'] = str_replace_url($v1['url']);
                }
            }
            $param['notice_file'] = Arr::a2s($param['notice_file']);
        }
        if(isset($param['confirm_file']) && !empty($param['confirm_file'])){
            foreach ($param['confirm_file'] as &$v2) {
                if(isset($v2['url']) && !empty($v2['url'])){
                    $v2['url'] = str_replace_url($v2['url']);
                }
            }
            $param['confirm_file'] = Arr::a2s($param['confirm_file']);
        }
        unset($param['payment'],$param['deploy_build'],$param['deploy_optimize'],$param['online_check'],$param['project_after']);

        //文件上传默认值
        if($param['is_upload_manage']){
            $param['upload_config'] = [
                'upload_max_num' => $param['upload_config']['upload_max_num'] ?? 100,
                'allow_file_type' => $param['upload_config']['allow_file_type'] ?? 'doc,docx,xls,xlsx,pdf,txt,csv,png,jpg,jpeg',
                'upload_max_size' => $param['upload_config']['upload_max_size'] ?? 5,
            ];
        }
        if(isset($param['is_customized']) && ($param['is_customized'] == 1)){
            if(!empty($param['is_visualization'])){
                $param['is_visualization'] = json_encode($param['is_visualization']);
            }
        }
        $this->model->edit($param,['id'=>$param['id']]);
        Common::del_user_cache($this->model->getTable(),$param['id']);
        return $this->success();
    }

    /**
     * @remark :保存付款续费
     * @name   :savePayment
     * @author :lyh
     * @method :post
     * @time   :2023/8/29 16:19
     */
    protected function saveProjectPayment($payment){
        $paymentModel = new Payment();
        if(isset($payment['contract']) && !empty($payment['contract'])){
            $payment['contract'] = Arr::a2s($payment['contract']);
        }
        if(isset($payment['bill']) && !empty($payment['bill'])){
            $payment['bill'] = Arr::a2s($payment['bill']);
        }
        if(isset($payment['renewal_record']) && !empty($payment['renewal_record'])){
            $payment['renewal_record'] = Arr::a2s($payment['renewal_record']);
        }
        $paymentModel->edit($payment,['id'=>$payment['id']]);
        return $this->success();
    }

    /**
     * @remark :保存建站部署
     * @name   :saveDeployBuild
     * @author :lyh
     * @method :post
     * @time   :2023/8/29 16:19
     */
    protected function saveProjectDeployBuild($deploy_build){
        $deployBuildModel = new DeployBuild();
        $deploy_build['configuration'] = Arr::a2s(!empty($deploy_build['configuration']) ? $deploy_build['configuration'] : []);
        $deployBuildModel->edit($deploy_build,['id'=>$deploy_build['id']]);
        return $this->success();
    }

    /**
     * @remark :保存优化部署
     * @name   :saveDeployOptimize
     * @author :lyh
     * @method :post
     * @time   :2023/8/30 13:45
     */
    protected function saveProjectDeployOptimize($deploy_optimize){
        $deployOptimizeModel = new DeployOptimize();
        if(isset($deploy_optimize['domain']) && !empty($deploy_optimize['domain'])){
            //更改域名
            $this->editDomainStatus($deploy_optimize['domain'],$deploy_optimize['project_id']);
        }
        $deploy_optimize['minor_languages'] = Arr::a2s(!empty($deploy_optimize['minor_languages']) ? $deploy_optimize['minor_languages'] : []);
        $deploy_optimize['minor_keywords'] = Arr::a2s(!empty($deploy_optimize['minor_keywords']) ? $deploy_optimize['minor_keywords'] : []);
        $deploy_optimize['special'] = !empty($deploy_optimize['special']) ? ','.trim($deploy_optimize['special'],',').',' : '';
        //是否更新了api_no
        $api_no = DeployOptimize::where('id', $deploy_optimize['id'])->value('api_no');
        if($api_no != $deploy_optimize['api_no']){
            NoticeLog::createLog(NoticeLog::TYPE_RANK_DATA, ['api_no' => $deploy_optimize['api_no']]);
        }
        $deployOptimizeModel->edit($deploy_optimize,['id'=>$deploy_optimize['id']]);
        return $this->success();
    }

    /**
     * @remark :保存为售后部署
     * @name   :saveProjectAfter
     * @author :lyh
     * @method :post
     * @time   :2023/8/30 13:57
     */
    protected function saveProjectAfter($project_after){
        //查询数据是否存在
        $afterModel = new After();
        $afterModel->edit($project_after,['id'=>$project_after['id']]);
        return $this->success();
    }

    /**
     * @remark :创建初始数据
     * @name   :createProjectData
     * @author :lyh
     * @method :post
     * @time   :2023/8/30 14:30
     */
    public function createProjectData($param){
        //查看当前项目状态是否为初始项目
        $info = $this->model->read(['id'=>$param['id']]);
        //项目为初始项目时,只能选择建站中
        if(($info['type'] == Project::TYPE_ZERO) && ($info['type'] != Project::TYPE_FIVE)){
            $param['type'] = Project::TYPE_ONE;
        }
        //创建默认数据库
        if($param['type'] == Project::TYPE_ONE){
            //改为异步
            NoticeLog::createLog(NoticeLog::TYPE_INIT_PROJECT, ['project_id' => $param['id']]);
        }
        return $this->success();
    }

    /**
     * @remark :根据类型状态设置
     * @name   :setTypeStatusEdit
     * @author :lyh
     * @method :post
     * @time   :2023/9/12 11:20
     */
    public function setTypeSevenEdit($param){
        $info = $this->model->read(['id'=>$param['id']]);
        if($info['delete_status'] == 0){
            //删除原始项目
            $this->edit(['delete_status' => 1], ['id' => $param['id']]);
            //添加到续费单
            $data = [
                'title' => '【续费单】' . $param['title'],
                'company' => $param['company'],
                'lead_name' => $param['lead_name'],
                'mobile' => $param['mobile'],
                'qq' => $param['qq'],
                'channel' => json_encode($param['channel']),
                'requirement' => $param['requirement'],
                'cooperate_date' => $param['cooperate_date'],
                'service_duration' => $param['deploy_build']['service_duration'],
                'plan' => $param['deploy_build']['plan'],
                'amount' => $param['payment']['amount'],
                'contract' => json_encode($param['payment']['contract']),
                'bill' => json_encode($param['payment']['bill']),
            ];
            $renewModel = new ProjectRenew();
            $renewModel->add($data);
        }
        return $this->success();
    }

    /**
     * @remark :初始化数据库
     * @name   :initializationMysql
     * @author :lyh
     * @method :post
     * @time   :2023/8/4 15:08
     */
    public function initializationMysql($project_id){
        //切换数据库配置
        $project = ProjectServer::useProject($project_id);
        //创建数据库
        ProjectServer::createDatabase($project);
        //创建表
        ProjectServer::initTable();
        //初始数据
        ProjectServer::saveInitParam($project_id);
        return $this->success();
    }


    /**
     * @remark :更新服务器为已使用
     * @name   :updateServe
     * @author :lyh
     * @method :post
     * @time   :2023/8/28 10:50
     */
    public function updateServe($serve_id){
        $serverModel = new ServerConfig();
        $serverModel->edit(['status'=>$serverModel::STATUS_ONE],['id'=>$serve_id]);
        return $this->success();
    }



    /**
     * @remark :创建用户
     * @name   :createUser
     * @author :lyh
     * @method :post
     * @time   :2023/8/28 18:03
     */
    public function createUser($mobile,$project_id,$lead_name){
        $userModel = new UserModel();
        //查看当前用户是否存在
        $info = $userModel->read(['mobile'=>$mobile,'project_id'=>$project_id]);
        if($info === false){
            $data = [
                'mobile'=>$mobile,
                'password'=>base64_encode(md5('123456')),
                'project_id'=>$project_id,
                'name'=>$lead_name,
                'type'=>UserModel::TYPE_ONE,
                'operator_id'=>$this->manager['id'] ?? 0,
                'create_id'=>$this->manager['id'] ?? 0,
            ];
            $userModel->add($data);
        }
        return $this->success();
    }

    /**
     * @remark :创建角色
     * @name   :createdRole
     * @author :lyh
     * @method :post
     * @time   :2023/9/6 11:16
     */
    public function createdRole($project_id){
        $roleModel = new ProjectRole();
        //查看当前用户是否存在
        $info = $roleModel->read(['project_id'=>$project_id]);
        if($info === false){
            $menuModel = new ProjectMenu();
            $ids = $menuModel->where(['status'=>0])->pluck('id')->toArray();
            $data = [
                'name'=>'管理员',
                'role_menu'=>implode(',',$ids),
                'project_id'=>$project_id,
                'type'=>1,
                'operator_id'=>$this->manager['id'],
                'create_id'=>$this->manager['id'],
            ];
            $roleModel->add($data);
        }
        return $this->success();
    }

    public function clearCache($id)
    {
        parent::clearCache($id);
        parent::setWith(['payment', 'deploy_build', 'deploy_optimize', 'online_check']);
        parent::clearCache($id);
    }

    /**
     * 保存询盘通知设置
     * @author zbj
     * @date 2023/5/17
     */
    public function saveInquirySet($param)
    {
        $project = $this->getCacheInfo($param['project_id']);
        //同步到接口
        $domain = parse_url((!empty($project['deploy_optimize']['domain']) ? ((new DomainInfo())->getDomain($project['deploy_optimize']['domain'])) :  ''))['host'];
        $emails = Arr::arrToSet($param['emails']??'', 'trim');
        $phones = Arr::arrToSet($param['phones']??'', 'trim');
        $form_global_api  = new FormGlobalsoApi();
        $res = $form_global_api->setInquiry($domain, $emails, $phones);
        if (!$res) {
            $this->fail('保存失败');
        }
        if ($res['status'] != 200) {
            $this->fail($res['message'] ?? '保存失败');
        }
        //保存
        $set = InquirySet::where('project_id', $param['project_id'])->first();
        if (!$set) {
            $set = new InquirySet();
        }
        $set->project_id = $param['project_id'];
        $set->emails = $emails;
        $set->phones = $phones;
        $set->save();
        return $this->success();
    }

    public function dataSource(){
        $data = [];
        $data['level'] = $this->model::levelMap();
        $data['type'] = $this->model::typeMap();
        $data['special'] = $this->model::specialMap();
        $data['plan'] = $this->model::planMap();
        return $this->success($data);
    }


    public function channelSource($param){
        switch ($param['type']){
            case Project::TYPE_ONE:
                return Zone::pluck('title', 'id')->toArray();
            case Project::TYPE_TWO:
                return Channel::where('zone_id', $param['zone_id']??0)->pluck('alias', 'id')->toArray();
            case Project::TYPE_THREE:
                return User::where('channel_id', $param['channel_id']??0)->pluck('name', 'id')->toArray();
        }
        return $this->success();
    }


    /**
     * @remark :修改域名时,同时更改其状态
     * @name   :domainStatus
     * @author :lyh
     * @method :post
     * @time   :2023/9/4 14:29
     */
    public function editDomainStatus($domain,$project_id){
        $domainModel = new DomainInfo();
        //先清空上一次所绑定的域名
        $info = $domainModel->read(['project_id'=>$project_id]);
        if($info !== false){
            $domainModel->edit(['project_id'=>0,'status'=>DomainInfo::STATUS_ZERO],['id'=>$info['id']]);
        }
        //重新设置域名
        $domainModel->edit(['status'=>DomainInfo::STATUS_ONE,'project_id'=>$project_id],['id'=>$domain]);
        return $this->success();
    }

    /**
     * @remark :删除
     * @name   :projectDel
     * @author :lyh
     * @method :post
     * @time   :2023/9/8 15:23
     */
    public function projectDel(){
        $rs = $this->edit(['delete_status'=>1],['id'=>$this->param['id']]);
        if($rs === false){
            $this->fail('error');
        }
        return $this->success();
    }

    /**
     * 创建站点
     * @param $param
     * @throws AsideGlobalException
     * @author Akun
     * @date 2023/10/17 10:04
     */
    public function createSite($param){
        if(isset($param['serve_id']) && $param['serve_id'] && isset($param['deploy_optimize']['domain']) && $param['deploy_optimize']['domain']){
            $server_model = new ServerConfig();
            $server_info = $server_model->read(['id'=>$param['serve_id']],['init_domain','host']);

            $domain_model = new DomainInfo();
            $domain_info = $domain_model->read(['id'=>$param['deploy_optimize']['domain']],'domain');

            if($server_info && $domain_info){
                //验证解析
                if ($domain_info['domain'] && !DomainInfoLogic::instance()->check_cname($domain_info['domain'], $server_info)) {
                    throw new AsideGlobalException(Code::SYSTEM_ERROR,'域名' . $domain_info['domain'] . '未解析至目标服务器');
                }
                $api_url = 'http://'.$server_info['init_domain'].'/api/createSite';
                $api_param = ['domain'=>$domain_info['domain']];
                try {
                    HttpUtils::get($api_url, $api_param);
                } catch (\Exception | GuzzleException $e) {
                    errorLog('创建站点', $api_param, $e);
                }
            }
        }
    }

    /**
     * @remark :复制项目
     * @name   :copyProject
     * @author :lyh
     * @method :post
     * @time   :2023/11/8 14:23
     */
    public function copyProject(){
        DB::beginTransaction();
        try {
            //复制初始项目
            $data = $this->model::where('id', $this->param['project_id'])->first();
            $data = $data->getAttributes();
            $type = $data['type'];
            $data['type'] = 0;
            $data['title'] = $data['title'].'-copy';
            unset($data['id']);
            $project_id = $this->model->insertGetId($data);
            //复制部署表
            $buildModel = new DeployBuild();
            $buildData = $buildModel::where('project_id', $this->param['project_id'])->first();
            if(!empty($buildData)){
                $buildData = $buildData->getAttributes();
                $buildData['project_id'] = $project_id;
                $hashids = new Hashids('test_domain', 5, 'abcdefghjkmnpqrstuvwxyz1234567890');
                $code = $hashids->encode($project_id);
                $buildData['test_domain'] = 'https://v6-' . $code . '.globalso.site/';
                unset($buildData['id']);
                $buildModel->insert($buildData);
            }
            //复制优化表
            $optimizeModel = new DeployOptimize();
            $optimizeData = $optimizeModel::where('project_id', $this->param['project_id'])->first();
            if(!empty($optimizeData)){
                $optimizeData = $optimizeData->getAttributes();
                unset($optimizeData['id'],$optimizeData['domain']);
                $optimizeData['project_id'] = $project_id;
                $optimizeModel->insert($optimizeData);
            }
            //复制付费表
            $paymentModel = new Payment();
            $paymentData = $paymentModel::where('project_id', $this->param['project_id'])->first();
            if(!empty($paymentData)){
                $paymentData = $paymentData->getAttributes();
                unset($paymentData['id']);
                $paymentData['project_id'] = $project_id;
                $paymentModel->insert($paymentData);
            }
            //复制售后表
            $afterModel = new After();
            $afterData = $afterModel::where('project_id', $this->param['project_id'])->first();
            if(!empty($afterData)){
                $afterData = $afterData->getAttributes();
                unset($afterData['id']);
                $afterData['project_id'] = $project_id;
                $afterModel->insert($afterData);
            }
            //复制用户
            $userModel = new UserModel();
            $userData = $userModel::where('project_id', $this->param['project_id'])->where('role_id',0)->first();
            if(!empty($userData)){
                $userData = $userData->getAttributes();
                unset($userData['id']);
                $userData['project_id'] = $project_id;
                $userModel->insert($userData);
            }
            //复制设置的模版
            $settingTemplateModel = new Setting();
            $settingData = $settingTemplateModel::where('project_id', $this->param['project_id'])->first();
            if(!empty($settingData)){
                $settingData = $settingData->getAttributes();
                unset($settingData['id']);
                $settingData['project_id'] = $project_id;
                $settingTemplateModel->insert($settingData);
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            $this->fail('error');
        }
        if($type != 0){
            $this->copyMysql($this->param['project_id'],$project_id);
        }
        return $this->success($data);
    }

    //复制数据库
    public function copyMysql($project_id,$new_project_id){
        //切换数据库配置
        $project = ProjectServer::useProject($new_project_id);
        //创建数据库
        ProjectServer::createDatabase($project);
        //创建表
        $this->initTable($project_id,$new_project_id);
    }


    /**
     * @param $project
     * @return bool
     * @author zbj
     * @date 2023/4/23
     */
    public  function initTable($project_id,$news_project_id)
    {
        config(['database.connections.custom_tmp_mysql_copy.database' => 'gl_data_'.$project_id]);
        $database_name = DB::connection('custom_tmp_mysql_copy')->getDatabaseName();
        $tables = Schema::connection('custom_tmp_mysql_copy')->getAllTables();
        $tables = array_column($tables, 'Tables_in_' . $database_name);
        foreach ($tables as $table) {
            $has_table = Schema::connection('custom_mysql')->hasTable($table);
            if (!$has_table) {
                $sql = DB::connection('custom_tmp_mysql_copy')->select("SHOW CREATE TABLE {$table}");
                DB::connection('custom_mysql')->statement(get_object_vars($sql[0])['Create Table']);
            }
            DB::connection('custom_mysql')->table($table)->truncate(); // 清空目标表数据
            DB::connection('custom_mysql')->table($table)->insertUsing(
                [], // 列名数组,留空表示插入所有列
                function ($query) use ($table,$project_id) {
                    $name = 'gl_data_'.$project_id.'.'.$table;
                    $query->select('*')->from("{$name}");
                }
            );

            if (Schema::connection('custom_mysql')->hasColumn($table, 'project_id')) {
                DB::connection('custom_mysql')->table($table)->update(['project_id' => $news_project_id]);
            }
        }
        return true;
    }

    /**
     * 对外接口token
     * @param $data
     * @return string
     * @author zbj
     * @date 2023/11/10
     */
    public function getSiteToken($data){
        $project = $this->getCacheInfo($data['project_id']);
        if(empty($project['site_token']) || !empty($data['refresh'])){
            $token = strtolower(base64_encode("6.0") . md5('project_' . $data['project_id'] . '_' . time()));
            $project->site_token = $token;
            $project->save();
        }
        return $project->site_token;
    }

}