 package Tool::mmt::Controller::App_submit;
 use Mojo::Base 'Tool::mmt::Controller::Json';
 use Mojo::Util 'b64_encode';
 use Mojo::JSON qw(decode_json encode_json);

 #民間サービス事業者認定
 sub authenticate_provider{
     my $s = shift;
     my $perl_object = { 'result'=> {'access_key' => 'newkwy0001'}};
     $s->json_or_jsonp( $s->render_to_string(json => $perl_object)
         );
 }
 #申請データ受信
 sub submit_application_set{
     my $s = shift;
     my $perl_object = { 'result'=> {'temporary_reference_number' => '202204090909'}};
     $s->json_or_jsonp( $s->render_to_string(json => $perl_object)
         );
 }
 #申請データ処理照会
 sub reference_number{
     my $s = shift;
     my $perl_object = { 'result'=> {
                            'status_code' => '003',
                            'file_for_signatuer' => 'xxxxxxxxxxxxxxxxxxxxxxxxx'}
                    };
     $s->json_or_jsonp( $s->render_to_string(json => $perl_object)
         );
 }
 #電子署名データ送信
 sub submit_signedapplication_set{
     my $s = shift;
     my $perl_object = { 'result'=> {'temporary_reference_number' => '202204090909'}};
     $s->json_or_jsonp( $s->render_to_string(json => $perl_object)
         );
 }
 sub json_or_jsonp{
     my $s = shift;
     my $headers = $s->res->headers;
     $headers->access_control_allow_origin('*');
     $s->SUPER::json_or_jsonp(@_);
 } 
 #税額シミュレーション
 sub taxSimulation{
     my $s = shift;
     my $token = $s->param('token');
     if($token != ''){
         $s->session('token',$token);
     }
     if($s->param('_action') eq 'Upload'){
         $s->upload2s3();
     }
 }
 sub upload2s3{
     my $s = shift;
     my $upload   = $s->param('upload_file');
     my $filename = $upload->filename;
     my $bytes = $upload->slurp;
     my $b64 =  b64_encode($bytes);
     $s->stash('filename'=>$filename);
#     $s->stash('b64'=>$b64);
     my $i = 0;
     my $ret = '';
     while( my $t = substr($b64,0,1000 * 1000 * 5,'')){
         $i++;
         my $ua = Mojo::UserAgent->new;
         my $req = {
             "key" =>'XXXXXX1',
             "file" =>{
                 "name" => $filename,
                 "index" => $i,
                 "data" => $t
             }
         };
         my $data = $ua->put('https://mk1nxfsfih.execute-api.ap-northeast-1.amazonaws.com/v1/upload' =>
            {
                Accept => '*/*',
                'yb-application-token' => $s->param('token')
            } =>
            json => $req);
         if(my $res = $data->success){
            $ret .= "$i [OK] ";
         }else{
             my ($err, $code) = $data->error;
            $ret .= "$i @{[encode_json($data->error)]} token:" . $s->session('token') ."\n ".$s->param('token').encode_json($req);
         }
     }
     $s->stash('ret'=> $ret);

 }

 1;
