<?php
namespace app\workerapi\logic;
use app\common\command\AddAgreementPdf;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\MasterWorkerAgree;
use app\common\service\ConfigService;
use app\common\service\UploadService;
use think\Exception;
use think\facade\Db;
use think\Log;

class MasterWorkerAgreeLogic extends BaseLogic
{
    public static function getAgreeByType($type,$userId)
    {

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

        return [
            'title' => ConfigService::get('master_agreement', $type . '_title', ''),
            'content' => ConfigService::get('master_agreement', $type . '_content', ''),
            'pdf'=>!empty($pdf)?'https://'.$_SERVER['SERVER_NAME'].'/'.$pdf:''
        ];
    }

    public static function getPolicyByType(string $type)
    {
        if($type == 'service'){
            return [
                'title' => ConfigService::get('agreement', $type . '_title', ''),
                'content' => ConfigService::get('agreement', $type . '_content', ''),
            ];
        }else{
            return [
                'title' => ConfigService::get('master_agreement', $type . '_title', ''),
                'content' => ConfigService::get('master_agreement', $type . '_content', ''),
            ];
        }
    }

    /**
     *
     * @param $params
     * @return bool|void
     */
    public static function sign($params)
    {
        try {
            //查询协议
            $agree = MasterWorkerAgree::where(['worker_id'=>$params['user_id'],'agree_type'=>'master_service_content'])->findOrEmpty();
            //保存签名
            if($agree->isEmpty()){
                $agree->code = generate_sn(MasterWorkerAgree::class, 'code');
                $agree->agree_type = 'master_service_content';
                $agree->worker_id = $params['user_id'];
            }
            $result = UploadService::base64Image(4, $params['sign']);
            $sign = $result['url'];
            $agree->sign = $sign;
            $agree->sign_status = 1;
            $agree->sign_time = time();
            $agree->audit_state = 0;
            $agree->save();

            \think\facade\Log::write('签署协议'.$agree->code);

            AddAgreementPdf::addPdf(['code'=>$agree->code,'url'=>'https://'.$_SERVER['SERVER_NAME'].'/index/agreement/index?code='.$agree->code]);

            //pdf队列发送
//            AddAgreementPdf::sendMq($agree->code,'https://'.$_SERVER['SERVER_NAME'].'/index/agreement/index?code='.$agree->code);

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