<?php
namespace app\workerapi\logic;

use app\common\logic\BaseLogic;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\model\tenant\Tenant;
use app\common\model\tenant\TenantRegister;
use think\facade\Db;


/**
 * TenantRegisterLogic逻辑
 * Class TenantRegisterLogic
 * @package app\workerapi\logic\master_worker_register
 */
class TenantRegisterLogic extends BaseLogic
{
    /**
     *  添加
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $info = TenantRegister::where('mobile',$params['mobile'])->findOrEmpty();
            if(!$info->isEmpty()){
                throw new \Exception('手机号已入驻门店');
            }
            $info = Tenant::where('tel',$params['mobile'])->findOrEmpty();
            if(!$info->isEmpty()){
                throw new \Exception('手机号已存在租户');
            }
            // $info = MasterWorkerRegister::where('mobile',$params['mobile'])->findOrEmpty();
            // if(!$info->isEmpty()){
            //     throw new \Exception('手机号已注册工程师');
            // }
            // $info = MasterWorker::where('mobile',$params['mobile'])->findOrEmpty();
            // if(!$info->isEmpty()){
            //     throw new \Exception('手机号已占用');
            // }
            isset($params['city']) && $params['province'] = getProvinceByCityId($params['city']);
            //$params['province'] && $params['area_name'] = $postageRegion[$params['province']]['name'].$postageRegion[$params['city']]['name'];
            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']??0,
                'city' => $params['city']??0,
                'area_name' => $params['area_name']??'',
                'lon' => $params['lon']??0,
                'lat' => $params['lat']??0,
                'status' => $params['status']??0,
                'sale_id' => $params['sale_id'],
                'openid' => $params['openid']??''
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * 获取详情
     */
    public static function detail($params): array
    {
        return TenantRegister::findOrEmpty($params['id'])->append(['city_text'])->toArray();
    }


}