<?php
namespace app\workerapi\logic;

use app\common\command\AddAgreementPdf;
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\TenantAgree;
use app\common\model\tenant\TenantRegister;
use app\common\service\ConfigService;
use app\common\service\UploadService;
use think\facade\Db;


/**
 * TenantAgreeLogic逻辑
 * Class TenantAgreeLogic
 * @package app\workerapi\logic\
 */
class TenantAgreeLogic extends BaseLogic
{
    public static function getAgreeByType($type,$userId)
    {

        //合作协议是否存在pdf
        if($type=='tenant_cooperate'){
            $pdf = TenantAgree::where(['agree_type'=>'tenant_cooperate','worker_id'=>$userId])->value('pdf_url');
        }

        return [
            'title' => ConfigService::get('tenant_agreement', $type . '_title', ''),
            'content' => ConfigService::get('tenant_agreement', $type . '_content', ''),
            'pdf'=>!empty($pdf)?'https://'.$_SERVER['SERVER_NAME'].'/'.$pdf:''
        ];
    }
    /**
     *
     * @param $params
     * @return bool|void
     */
    public static function sign($params)
    {
        try {
            //查询协议
            $agree = TenantAgree::where(['worker_id'=>$params['user_id'],'agree_type'=>'tenant_cooperate'])->findOrEmpty();
            //保存签名
            if($agree->isEmpty()){
                $agree->code = generate_sn(TenantAgree::class, 'code');
                $agree->agree_type = 'tenant_cooperate';
                $agree->worker_id = $params['user_id'];
            }
            $result = UploadService::base64Image(4, $params['sign']);
            $sign = $result['url'];
            $agree->sign = $sign;
            $agree->audit_state = 0;
            $agree->save();

            \think\facade\Log::write('团队签署协议'.$agree->code);
            AddAgreementPdf::addTenantAgreePdf(['code'=>$agree->code,'url'=>'https://'.$_SERVER['SERVER_NAME'].'/index/tenant_agreement/index?code='.$agree->code]);
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * 获取详情
     */
    public static function detail($params): array
    {
        return TenantRegister::findOrEmpty($params['id'])->toArray();
    }


}