<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\tenant;


use app\adminapi\logic\master_worker\MasterWorkerTeamLogic;
use app\adminapi\logic\master_worker_register\MasterWorkerRegisterLogic;
use app\adminapi\logic\training\TrainingBlockConfigLogic;
use app\adminapi\logic\training\TrainingWorkerTaskLogic;
use app\common\model\dict\DictData;
use app\common\model\tenant\TenantRegister;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * TenantRegister逻辑
 * Class TenantRegisterLogic
 * @package app\adminapi\logic
 */
class TenantRegisterLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            TenantRegister::create([
                'name' => $params['name'],
                'head_name' => $params['head_name'],
                'mobile' => $params['mobile'],
                'door_images' => $params['door_images'],
                'business_images' => $params['business_images'],
                'province' => $params['province'],
                'city' => $params['city'],
                'area_name' => $params['area_name'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'status' => $params['status'],
                'sale_id' => $params['sale_id'],
                'openid' => $params['openid']??''
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            TenantRegister::where('id', $params['id'])->update([
                'name' => $params['name'],
                'head_name' => $params['head_name'],
                'mobile' => $params['mobile'],
                'door_images' => $params['door_images'],
                'business_images' => $params['business_images'],
                'province' => $params['province'],
                'city' => $params['city'],
                'area_name' => $params['area_name'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'status' => $params['status'],
                'sale_id' => $params['sale_id'],
                'openid' => $params['openid']??''
            ]);

            if((int)$params['status'] === 1){
                /* domain_alias training_task_id task_list
                 域名绑定好且能正常访问
                 工程师添加(工程师负责人和注册表信息)--自动添加
                团队添加(工程师负责人、门店名称做团队名称)--自动添加
                培训课程(工程师负责人)--自动添加 */

                $tenant_id = TenantLogic::add([
                    'name'                => $params['name'],
                    'avatar'              => '',
                    'tel'                 => $params['mobile'],
                    'domain_alias_enable' => 1,
                    'domain_alias'        => $params['domain_alias']??'',
                ])->id;
                TenantRegister::where('id', $params['id'])->update([
                    'tenant_id' => $tenant_id
                ]);
                //mobile real_name lon lat province city area_name
                $worker_id = MasterWorkerRegisterLogic::createMasterWorker([
                    'mobile' => $params['mobile'],
                    'real_name' => $params['head_name'],
                    'lon' => $params['lon'],
                    'lat' => $params['lat'],
                    'province' => $params['province'],
                    'city' => $params['city'],
                    'area_name' => $params['area_name'],
                    'identity_source_id' => 2
                ]);
                //master_worker_id tenant_id team_name
                $res = MasterWorkerTeamLogic::add([
                    'master_worker_id' => $worker_id,
                    'tenant_id' => $tenant_id,
                    'team_name' => $params['name'],
                    'lon' => $params['lon'],
                    'lat' => $params['lat'],
                ]);
                if($res === false){
                    throw new \Exception(MasterWorkerTeamLogic::getError());
                }
                $block_setting = TrainingBlockConfigLogic::getBlockConfig(2);
                if($block_setting['training_task_id']){
                    $res = TrainingWorkerTaskLogic::add([
                        'master_worker_id' => $worker_id,
                        'shop_goods_id' => $block_setting['shop_goods_id']??0,
                        'training_task_id' => $block_setting['training_task_id']??0,
                        'task_list' => $block_setting['task_list']??0,
                    ]);
                    if($res === false){
                        throw new \Exception(TrainingWorkerTaskLogic::getError());
                    }
                }

                $res = TenantAdminLogic::add([
                    'name'             => $params['mobile'],
                    'root'             => 1,
                    'tenant_id'        => $tenant_id,
                    'account'          => $params['mobile'],
                    'avatar'           => '',
                    'password'         => $params['mobile'],
                    'disable'          => 0,
                    'multipoint_login' => 1,
                ]);
                if($res === false){
                    throw new \Exception(TrainingWorkerTaskLogic::getError());
                }


                Db::query('call CopyMenusToTenantOne(:in_param1,:in_param2,:in_param3,:in_param4)', [
                    'in_param1' => 1,
                    'in_param2' => $tenant_id,
                    'in_param3' => 0,
                    'in_param4' => 0,
                ]);

            }


            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public static function delete(array $params): bool
    {
        return TenantRegister::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public static function detail($params): array
    {
        return TenantRegister::findOrEmpty($params['id'])->toArray();
    }
}