<?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\master_worker_register;


use app\common\enum\notice\NoticeEnum;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAuth;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\logic\BaseLogic;
use app\common\service\ConfigService;
use think\facade\Config;
use think\facade\Db;


/**
 * MasterWorkerRegister逻辑
 * Class MasterWorkerRegisterLogic
 * @package app\adminapi\logic\master_worker_register
 */
class MasterWorkerRegisterLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/09 19:45
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {

            $master = MasterWorkerRegister::where('mobile',$params['mobile'])->findOrEmpty();

            if(!$master->isEmpty() and $master->status==1){
                throw new \Exception('该手机号已入驻');
            }

            if(!$master->isEmpty() and $master->status==0){
                throw new \Exception('该手机号后台审核中');
            }

            MasterWorkerRegister::create([
                'maintain_exp_type' => isset($params['maintain_exp_type'])?$params['maintain_exp_type']:0,
                'other_exp_type' => isset($params['other_exp_type'])?$params['other_exp_type']:'',
                'city' => $params['city'],
                'vehicle_type' => $params['vehicle_type'],
                'name' => $params['name'],
                'age' => $params['age'],
                'mobile' => $params['mobile'],
                'status' => $params['status'],
                'is_credential' => !empty($params['is_credential'])?$params['is_credential']:0,
                'credential_name' => !empty($params['is_credential'])?implode(',', $params['credential_name']):'',
                'address' => !empty($params['address'])?$params['address']:'',
            ]);

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


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/09 19:45
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            $updata = [
                'maintain_exp_type' => isset($params['maintain_exp_type'])?$params['maintain_exp_type']:0,
                'other_exp_type' => isset($params['other_exp_type'])?$params['other_exp_type']:'',
                'city' => $params['city'],
                'vehicle_type' => $params['vehicle_type'],
                'name' => $params['name'],
                'age' => $params['age'],
                'mobile' => $params['mobile'],
                'status' => $params['status'],
                'is_credential' => !empty($params['is_credential'])?$params['is_credential']:0,
                'credential_name' => !empty($params['is_credential'])?implode(',', $params['credential_name']):'',
                'address' => !empty($params['address'])?$params['address']:'',
                'update_time'=> time(),
            ];

            //审批通过逻辑处理
            if($params['status'] == 1){
                $updata['worker_id'] = self::createMasterWorker($params);
            }
            MasterWorkerRegister::where('id', $params['id'])->update($updata);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function createMasterWorker(array $params)
    {
        $where = ['mobile' => $params['mobile']];
        $masterWorker = MasterWorker::where($where)->findOrEmpty();
        if ($masterWorker->isEmpty()) {
            $number = MasterWorker::count();
            $number += 1;
            if ($number < 100000) {
                $number = str_pad($number, 6, '0', STR_PAD_LEFT);
            }
            $userSn = MasterWorker::createUserSn();
            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password($params['mobile'], $passwordSalt);
            $avatar = ConfigService::get('default_image', 'user_avatar');
            $masterWorker = MasterWorker::create([
                'sn' => $userSn,
                'worker_number' => $number,
                'avatar' => $avatar,
                'nickname' => '用户' . $userSn,
                'account' => $params['mobile'],
                'mobile' => $params['mobile'],
                'password' => $password,
                'channel' => 1,
                'lon' => $params['lon']??0,
                'lat' => $params['lat']??0,
            ]);
        }
        return $masterWorker->id;
    }
    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/09 19:45
     */
    public static function delete(array $params): bool
    {
        return MasterWorkerRegister::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/09 19:45
     */
    public static function detail($params): array
    {
        return MasterWorkerRegister::findOrEmpty($params['id'])->toArray();
    }

    public static function eventNotice($params): bool
    {
        $registerInfo = MasterWorkerRegister::findOrEmpty($params['id'])->toArray();
        if ($registerInfo && $registerInfo['worker_id']) {
            $account = MasterWorker::where('id',$registerInfo['worker_id'])->value('account');
            event('Notice',  [
                'scene_id' => 107,
                'params' => [
                    'user_id' => $registerInfo['worker_id'],
                    'mobile' => $registerInfo['mobile'],
                    'account' => $account,
                    'password' => $registerInfo['mobile'],
                ]
            ]);
            return true;
        }
        return false;
    }


}