<?php
declare (strict_types = 1);

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\facade\Config;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;

class downredinvres extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('downredinvres')
            ->setDescription('the downredinvres command');
    }

    protected function execute(Input $input, Output $output)
    {
		$GetOrderInfoAndInvoiceInfo= Cache::store("redis")->get("downredinvres");
       if($GetOrderInfoAndInvoiceInfo==0) Cache::store("redis")->set("downredinvres",1,180);
        Db::startTrans();
        $date= date("Y-m-d H:i:s");
        $row =Db::name("invoice_red")->where(["status"=>1,"is_del"=>0])->where("updatetime","<=",date("Y-m-d H:i:s"))
        ->lock(true)->findOrEmpty();
        try{
		$data=["updatetime"=>date("Y-m-d H:i:s",time()+600)];
        $opendatetime =date("Ymd",strtotime($row['addtime']));
		$invoice=Config::get("invoice");
		$Tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
		$result=$Tax->DownloadRedInvoiceApplicationResult($row['SQBSCQQPCH'],$row['XHFSBH'],$row['FPLXDM'],$opendatetime);
		$data['status']=5;
		$data['remark']='红冲申请提交失败';
		if(isset($result['ZTDM']) && $result['ZTDM']=='060000'){
			$resultChild=$result['HZSQDXZZXX'][0]['HZSQDXZTXX'];
			if($resultChild['ZTDM']=='060000'){
				$data['status']=2;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='申请表审核结果下载下载成功!';
			}
			if($resultChild['ZTDM']=='060111'){
				$data['status']=1;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='申请表审核结果下载正在下载中!';
			}
		}
		if($data['status']==5){
			throw new \Exception($result['ZTXX'], 10006);
		}
		Db::name("invoice_red")->where($row)->update($data);
		Db::commit();
		$output->writeln("[$date] ".$row['invRed'].'发票申请表获取成功');
        }catch (\Exception $e){
			Db::rollback();
			$output->writeln("[$date] ".$row['invRed'].$e->getMessage());
        }

    }



}