<?php

namespace app\api\controller;


use think\Exception;
use think\exception\FileException;
use app\common\library\Upload;
use app\common\controller\Frontend;
use think\facade\Db;
use think\facade\Log;
use app\admin\model\ReqOrder;
class Ajax extends Frontend
{
    protected $noNeedLogin = ['area', 'buildSuffixSvg','saveFirstForm'];

    public function initialize()
    {
        parent::initialize();
    }

    public function saveFirstForm(){
        $user_id  = $this->auth->id;

        $user_id = 1;
        
        $post = $this->request->post();
        $reqOrder = new ReqOrder();
        $validate = new \app\admin\validate\ReqOrder;
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }

        $data = [
            //'sn' => 'as'.date('YmdH').rand(1000,9999).substr(md5($user_id),-5),
            'req_user_id' => $user_id,
            'req_endtime' => date('Y-m-d 00:00:00',time()*3600*24*5), //默认5天截止
            'city' => $post['city'],
            'act_time' => $post['act_date'],
            'act_day_count' => 1,
            'budget' => $post['budget'],
            'participant'=> $post['participant'],
            'require_item' => '',
            'req_corp' => '',
            'req_tel' => $post['phone'],

        ];
        $res = $reqOrder->save($data);

        //print log post
        //Log::write($post,'error');
       
        if(!$res){
            $this->error('保存失败');
        }
        
        $this->success('保存成功');
    }

    public function listFirstForm(){
        //get user id
        $user_id = $this->auth->id;
        $res = Db::name('req_order')->where('user_id',$user_id)->find();
        if(!$res){
            $this->error('没有数据');
        }
        $this->success('获取成功',$res);
    }
    public function upload()
    {
        $file = $this->request->file('file');
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload(null, 0, $this->auth->id);
            unset($attachment['createtime'], $attachment['quote']);
        } catch (Exception|FileException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    public function area()
    {
        $this->success('', get_area());
    }

    public function buildSuffixSvg()
    {
        $suffix     = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content    = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }
}