<?php

namespace app\api\controller;


use app\common\controller\Backend;
use think\Exception;
use think\exception\FileException;
use app\common\library\Upload;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Event;
use app\admin\model\ReqOrder;
use app\admin\validate\ReqOrder as ReqOrderValidate;use think\facade\Validate;
class Ajax extends Backend
{
    protected $noNeedLogin = ['area', 'buildSuffixSvg','saveFirstForm','listFirstForm','FirstFormInfo'];

    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 ReqOrderValidate();
        try{
        $validate->scene("add")->check($post);
        }catch (ValidateException $e){
        	$this->error($e->getMessage());
        }

        $data = [
            'reqCode' => 'REQ'.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'],
            'name' => $post['name'],
            'act_time' => $post['act_time'],
            'act_day_count' => $post['act_day_count'],
            'budget' => $post['budget'],
            'participant'=> $post['participant'],
            'require_item' =>$post['require_item'],
            'req_corp' =>$post['req_corp'],
            'req_tel' => $post['phone'],

        ];
        $res = $reqOrder->save($data);
        if(!$res){
            $this->error('保存失败');
        }
         Event::trigger("ReOrderAdd",$data);
        $this->success('保存成功',["reqCode"=>$data['reqCode']]);
    }

    public function listFirstForm(){
		$post = $this->request->post();
        $user_id = $this->auth->id;
        $where =[['req_user_id',"=",$user_id]];
        if ($post['status']!='')$where[]=["status","=",$post['status']];
        if ($post['flow_stage']!='')$where[]=["flow_stage","=",$post['flow_stage']];
        $res = Db::name('req_order')
        ->where($where)
        ->paginate($post['limit'])
        ->order("id desc");
         $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function FirstFormInfo(){
		$post = $this->request->post();
		$valide =Validate::rule(["reqCode|订单编号"=>"require|max:255"]);
		if($valide->check($post)==false)$this->error($valide->getError());
        $user_id = $this->auth->id;
        $res = Db::name('req_order')->where('req_user_id',$user_id)->where("reqCode",$post['reqCode'])->findOrEmpty();
		 if(!$res){
            $this->error('信息获取失败');
        }
		 $res['supplierName'] = Db::name("supplier")->where(["id"=>$res['supplier_id']])->value("name","");
		 $res['city_area'] = Db::name("area")->where(["id"=>$res['city']])->value("mergename","");
		 $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');
    }
}