<?php


namespace app\admin\controller;
use app\admin\BaseController;
use app\admin\model\ReportCode;
use think\App;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Cache;use think\facade\Validate;

class OrderInv extends BaseController{
	protected $typename;
	protected $invoiceType;
    protected $invName;
    protected $kingInvoice;
    public function __construct(App $app) {
        parent::__construct($app);
        $invoice =Config::get("invoiceType");
        $this->invoiceType = $invoice['invoiceName'];
        $this->invName = $invoice['invoiceType'];
        $this->typename = $invoice['KingName'];
        $this->kingInvoice = $invoice['KingInvoice'];
    }
    /**
     * 新建销售单开票申请
     */
   public function create(){
	        $companyType = isset($this->post['companyType'])&&$this->post['companyType']!=='' ? trim($this->post['companyType']):"";
	        if ($companyType==''){
	              return error_show(1004,"参数 companyType 不能为空");
	        }
        	$buy_id = isset($this->post['buy_id'])&&$this->post['buy_id']!=='' ? intval($this->post['buy_id']):"";
	       if($buy_id==''){
	           return error_show(1004,"参数 buy_id 不能为空");
	       }
           $buyinfo =Db::name("customer_invoice")->where(['id'=>$buy_id,"is_del"=>0])->find();
           if($buyinfo==false){
                 return error_show(1004,"购买方发票信息未找到");
           }

		if($this->level==1){
			$companyNo = isset($this->post['companyNo'])&&$this->post['companyNo']!=='' ? trim($this->post['companyNo']):"";
		}
		else{
		 $companyNo = isset($this->post['relaComNo'])&&$this->post['relaComNo']!=='' ? trim($this->post['relaComNo'])
		 :"";
		}
       if($companyNo==''){
           return error_show(1004,"业务公司不能为空");
       }
        $company = Db::name("company_info")->where(["companyNo"=>$companyNo])->find();
       if($company==false){
           return error_show(1004,"销售方信息未找到");
       }
//        $khNo = isset($this->post['khNo'])&&$this->post['khNo']!=='' ? trim($this->post['khNo']):"";
//       if($khNo==''){
//           return error_show(1004,"参数 khNo 不能为空");
//       }
       $supplier = Db::name("supplier_info")->where(["code"=>$companyNo])->find();
       if($supplier==false){
           return error_show(1004,"业务公司信息未找到");
       }
       $invtype = isset($this->post['invtype'])&&$this->post['invtype']!=='' ? trim($this->post['invtype']):"";
        if($invtype==''){
           return error_show(1004,"参数 invtype 不能为空");
       }
        if(!in_array($invtype,$this->invName)) return error_show(1004,"发票类型有误");

        $email = isset($this->post['email'])&&$this->post['email']!=='' ? trim($this->post['email']):"";
        $remark = isset($this->post['remark'])&&$this->post['remark']!=='' ? trim($this->post['remark']):"";
        $exam_remark = isset($this->post['exam_remark'])&&$this->post['exam_remark']!=='' ? trim($this->post['exam_remark']):"";
        $orderArr = isset($this->post['orderArr'])&&!empty($this->post['orderArr']) ? $this->post['orderArr']:[];
        if(empty($orderArr)){
           return error_show(1004,"参数 orderArr 不能为空");
        }
        $temp =[];
        $good=[];
        $invNo=makeNo("INV");
        $invfee=array_sum(array_column($orderArr,'inv_fee'));
        if($company['denomination']!=''&& $invfee>intval($company['denomination'])*10000){
                return error_show(1004,"开票面额不能超过{$company['denomination']}万元");
        }
        $platform = array_column($orderArr,'platform_type');
        if(count(array_unique($platform))!=1){
            return error_show(1004,"订单平台类型不一致");
        }
        Db::startTrans();
        try{
               foreach ($orderArr as $value){
                    if(!isset($value['sequenceNo']) ||$value['sequenceNo']==''){
                        Db::rollback();
                           return error_show(1004,"参数 sequenceNo 不能为空");
                    }
                    $qrd = Db::name("qrd_info")->where(["sequenceNo"=>$value['sequenceNo']])->find();
                    if($qrd['status']==2){
                        Db::rollback();
                     return error_show(1004,"确认单{$value['sequenceNo']}不参与对账");
                    }
                    if(!isset($value['inv_fee']) || $value['inv_fee']===''){
                        Db::rollback();
                           return error_show(1004,"参数 inv_fee 不能为空");
                    }
                    if($qrd['winv_fee']<$value['inv_fee']){
                    	Db::rollback();
                        return error_show(1004,"确认单{$value['sequenceNo']}待开票金额不足");
                    }
                   $ainv = Db::name("invoice_pool")
                       ->alias("a")
                       ->leftJoin("invoice_good b", "a.invNo=b.invNo and b.is_del=0")
                       ->where(["a.status" => [0, 1, 2, 3, 4], "b.orderCode" => $value['sequenceNo']])
                       ->sum("b.goodNum");
                    if($ainv+$value['num']>($qrd['goodNum']-$qrd['thNum'])) {
                    	Db::rollback();
                        return error_show(1004,"确认单{$value['sequenceNo']}待开票数量不足");
                    }
                    $good_info = Db::name("good")->where(["spuCode"=>$qrd["goodNo"],"status"=>1])->findOrEmpty();
                    if(empty($good_info)){
                     Db::rollback();
                     return error_show(1004,"确认单{$value['sequenceNo']}商品未确认开票类目");
                    }

                   $num = Db::name("assoc")
                       ->alias("a")
                       ->leftJoin("invoice_good b", "a.viceCode=b.invNo AND b.orderCode=a.orderCode")
                       ->where(["a.status" => [1, 2], "a.is_del" => 0, "a.type" => 1, "a.orderCode" => $value['sequenceNo']])
                       ->sum("b.goodNum");
                    if($qrd['goodNum']-$qrd['thNum']-$num<$value['num']){
                    	Db::rollback();
                        return error_show(1004,"确认单{$value['sequenceNo']}待开票数量不足");
                    }
                   $ascc=[
                       "assocNo"=>makeNo("AS"),
                       "apply_id"=>$this->uid,
                       "apply_name"=>$this->uname,
                       "type"=>1,
                       "orderCode"=>$value['sequenceNo'],
                       "customerNo"=>$qrd['customerNo'],
                       "viceCode"=>$invNo,
                       "order_total"=>$qrd['totalPrice'],
                       "vice_total"=>$invfee,
                       "cancel_fee"=>$value['inv_fee'],
                       "status"=>1,
                        "addtime"=>date("Y-m-d H:i:s"),
                        "updatetime"=>date("Y-m-d H:i:s")
                    ];
                    $invoice_good=[
                       "invNo"=>$invNo,
                        "orderCode"=>$value['sequenceNo'],
                        "goodNo"=>$qrd['goodNo'],
                        "goodName"=>$good_info['inv_good_name']??$qrd['goodName'] ,
                        "catName"=>$good_info['inv_cat_name']??$qrd['thirdCat'],
                        "catNo"=>$good_info['inv_cat_code']??"",
                        "goodPrice"=>round($value['inv_fee']/$value['num'],8),
                        "unitName"=>$qrd['goodUnit'],
                        "goodNum"=>$value['num'],
                        "specInfo"=>$value['sequenceNo'],
                        "totalPrice"=>$value['inv_fee'],
                        "totalTax"=>$value['inv_fee'],
                        "tax"=>$good_info['inv_tax']??$qrd['tax'],
                        "is_discount"=>$good_info['is_discount']??0,
                        "addTax"=>$good_info['addTax']??'',
                        "inv_tag"=>$good_info['inv_tag']??"",
                        "taxPrice"=>round($value['inv_fee']*($good_info['inv_tax']??$qrd['tax']),2),
                        "addtime"=>date("Y-m-d H:i:s"),
                        "updatetime"=>date("Y-m-d H:i:s")
                    ];
                    $update = [
                        "inv_fee"=>$qrd['inv_fee']+$value['inv_fee'],
                        "winv_fee"=>$qrd['winv_fee']-$value['inv_fee'],
                        "inv_status"=>2,
                        "status"=>1,
                        "updatetime"=>date("Y-m-d H:i:s")
                    ];
                    $up = Db::name("qrd_info")->where($qrd)->update($update);
                    if($up==false){
                        Db::rollback();
                        return error_show(1005,"确认单{$value['sequenceNo']} 更新失败");
                    }
                    $temp[]=$ascc;
                    $good[]=$invoice_good;
                    $report=ReportCode::where(["qrdNo"=>$value['sequenceNo']])->find();
                    if($report)$report->setField("invNo",$invNo);
                }
                $associn = Db::name("assoc")->insertAll($temp);
                if($associn==0){
                    Db::rollback();
                     return error_show(1005,"确认单申请开票失败");
                }
                 $goodin = Db::name("invoice_good")->insertAll($good);
                if($goodin==0){
                    Db::rollback();
                     return error_show(1005,"确认单申请开票失败");
                }

          $inv=[
            "invNo"=>$invNo,
            "inv_value"=>$invfee,
            "inv_out"=> $companyNo,
            "inv_company"=> $supplier['name']??"",
            "apply_id"=>$this->uid,
            "apply_name"=>$this->uname,
            "inv_type"=>$invtype,//发票类型  专用 普通 电子专用 电子普通 全电子票
            "open_type"=>0, //开票类型 金税开票 金税线下 纯线下
            "platform_type"=>$platform[0]??0, //开票类型 金税开票 金税线下 纯线下
            "is_ticket"=>$company['out_ticket'], //是否支持金税开票
            "company_type"=> $buyinfo['company_type']??'01', //类型01 企业,02 机关事业单位,03 个人, 04 其他
            "remark"=>$remark, //申请备注
            "exam_remark"=>$exam_remark, //审核备注
            "ainv_fee"=>0,//已核销金额
            "winv_fee"=>$invfee,//未核销金额
            "status"=>1,// 带财务审核
            "is_del"=>0,
            "email"=>$email,
            "addtime"=>date("Y-m-d H:i:s"),
            "updatetime"=>date("Y-m-d H:i:s")
        ];
        $invin = Db::name("invoice_pool")->insert($inv);
        if($invin){
            $invinfo=[
               "buyer_title"=>$buyinfo['invoice_title'],
               "buyer_code"=>$buyinfo['invoice_code'],
               "buyer_addr"=>$buyinfo['invoice_addr'],
               "buyer_mobile"=>$buyinfo['invoice_mobile'],
               "buyer_bank"=>$buyinfo['invoice_bank'],
               "buyer_bankNo"=>$buyinfo['invoice_bankNo'],
               "seller_title"=>$company['company_name'],
               "seller_code"=>$company['company_license'],
               "seller_addr"=>$company['company_address'],
               "seller_mobile"=>$company['mobile'],
               "seller_bank"=>$company['bank_name'],
               "seller_bankNo"=>$company['bankNo'],
               "invNo"=>$invNo,
               "voider"=>$company['voider'],
               "payee"=>$company['payee'],
               "drawer"=>$company['drawer'],
               "reviewer"=>$company['reviewer'],
               "ownerPlace"=>$company['ownerPlace'],
               "addtime"=>date("Y-m-d H:i:s")
            ];
            $poolinfo =Db::name("invoice_pool_info")->insert($invinfo);
            if($poolinfo){
                 Db::commit();
                return app_show(0,"确认单发票申请成功",["invNo"=>$invNo]);
            }
        }
         Db::rollback();
        return error_show(1004,"确认单发票申请失败");
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1004,$e->getMessage());
        }
   }
    //   1财务审核通过 2 金税开票中/验票中 3 开票成功 4 财务驳回 5 开票失败 6 发票退票/废弃 7取消申请
    //   1财务审核通过 2 待财务上传发票 3 金税开票中/验票中 4 开票成功  5 开票失败 6发票退票/废弃 7取消申请 8 财务驳回 9验票失败
   public  function  status(){
        $invNo = isset($this->post['invNo'])&&$this->post['invNo']!=''?trim($this->post['invNo']):"";
        if($invNo==""){
            return error_show(1004,"参数 invNo 不能为空");
        }
        $invinfo = Db::name("invoice_pool")->where(["invNo"=>$invNo,"is_del"=>0])->find();
        if($invinfo==false){
            return error_show(1004,"发票申请数据未找到");
        }
        $status=  isset($this->post['status'])&&$this->post['status']!==''?intval($this->post['status']):"";
        if($status===''){
            return error_show(1004,"参数 status 不能为空");
        }

        //open_type 1 金税开票 2 金税线下开票 3 线下开票
        $open_type = isset($this->post['open_type'])&&$this->post['open_type']!==''?intval($this->post['open_type']):"";
        $remark = isset($this->post['remark'])&&$this->post['remark']!=''?trim($this->post['remark']):"";
        $invCode =isset($this->post['invCode'])&&$this->post['invCode']!=''?trim($this->post['invCode']):"";
        $invNum =isset($this->post['invNum'])&&$this->post['invNum']!=''?trim($this->post['invNum']):"";
        $open_date =isset($this->post['open_date'])&&$this->post['open_date']!=''?trim($this->post['open_date']):"";
        $subtotal_fee =isset($this->post['subtotal_fee'])&&$this->post['subtotal_fee']!=''?floatval($this->post['subtotal_fee']):"";
        $total_fee =isset($this->post['total_fee'])&&$this->post['total_fee']!=''?floatval($this->post['total_fee']):"0";
        $checkCode =isset($this->post['checkCode'])&&$this->post['checkCode']!=''?trim($this->post['checkCode']):"";
        $seller_id =isset($this->post['seller_id'])&&$this->post['seller_id']!=''?trim($this->post['seller_id']):"";
        $seller_title =isset($this->post['seller_title'])&&$this->post['seller_title']!=''?trim($this->post['seller_title']):"";
        $seller_addr =isset($this->post['seller_addr'])&&$this->post['seller_addr']!=''?trim($this->post['seller_addr']):"";
        $seller_mobile =isset($this->post['seller_mobile'])&&$this->post['seller_mobile']!=''?trim($this->post['seller_mobile']):"";
        $seller_bank =isset($this->post['seller_bank'])&&$this->post['seller_bank']!=''?trim($this->post['seller_bank']):"";
        $seller_bankNo =isset($this->post['seller_bankNo'])&&$this->post['seller_bankNo']!=''?trim($this->post['seller_bankNo']):"";
        $buyer_id =isset($this->post['buyer_id'])&&$this->post['buyer_id']!=''?trim($this->post['buyer_id']):"";
        $buyer_title =isset($this->post['buyer_title'])&&$this->post['buyer_title']!=''?trim($this->post['buyer_title']):"";
        $buyer_addr =isset($this->post['buyer_addr'])&&$this->post['buyer_addr']!=''?trim($this->post['buyer_addr']):"";
        $buyer_mobile =isset($this->post['buyer_mobile'])&&$this->post['buyer_mobile']!=''?trim($this->post['buyer_mobile']):"";
        $buyer_bank =isset($this->post['buyer_bank'])&&$this->post['buyer_bank']!=''?trim($this->post['buyer_bank']):"";
        $buyer_bankNo =isset($this->post['buyer_bankNo'])&&$this->post['buyer_bankNo']!=''?trim($this->post['buyer_bankNo']):"";
        $tax_fee =isset($this->post['tax_fee'])&&$this->post['tax_fee']!=''?trim($this->post['tax_fee']):"";
        $invimg =isset($this->post['invimg'])&&$this->post['invimg']!=''?trim($this->post['invimg']):"";
	     $update=[
	            "status"=> $status,
	            "exam_remark"=>$remark,
	            "updatetime" => date("Y-m-d H:i:s")
	            ];

        if($status==3){
			$open_type = $invinfo['open_type'];
           if($open_type!=1){

               if($invNum==='') return error_show(1004,"参数 invNum 不能为空");
               if($open_date==='') return error_show(1004,"参数 open_date 不能为空");
               if(in_array($invinfo['inv_type'],['normal','roll',"toll",'electronic'])){
               	    if($checkCode==='') return error_show(1004,"参数 checkCode 不能为空");
               }
               //全电子发票
	           if(in_array($invinfo['inv_type'],['fully_digitalized_special_electronic','fully_digitalized_normal_electronic'])){
	           	    //全电发票传含税金额
	              if($total_fee=='') return error_show(1004,"参数 total_fee 不能为空");
	           }else{
	           	//全电发票无invCode
	           	 if($invCode==='') return error_show(1004,"参数 invCode 不能为空");
	           	 if($subtotal_fee==='') return error_show(1004,"参数 subtotal_fee 不能为空");
	           }
           }

        }
	  if($status==2){
		        if($open_type==='')return error_show(1004,"参数 open_type 不能为空");
	            $update['open_type']=$open_type;
	             if($open_type==1)$status=3;
	  }
        if($status==7){
        	if(!in_array($invinfo['status'],[1,2,3,5,8,9]))  return error_show(1004,"开票申请状态有误");
        }
		$update['status']=$status;
        Db::startTrans();
        try{

          $invup =Db::name("invoice_pool")->where($invinfo)->update($update);
        if($invup){
            if(($status==3&& $open_type!=1) || ($invinfo['inv_type']==5 &&$status==3)){
            		 $invpool=[
                        "invNo"=>$invinfo['invNo'],
                        "inv_type"=>$this->kingInvoice[$invinfo['inv_type']],
                        "inv_code"=>$invCode,
                        "inv_number"=>$invNum,
                        "check_code"=>$checkCode,
                        "inv_total"=>$total_fee,
                        "inv_subtotal"=>$subtotal_fee,
                        "open_date"=>$open_date,
                        'pdfstream'=>'',
                        "item"=>'',
                        "status"=>$invinfo['inv_type']==5?1:0,
                        "addtime"=>date("Y-m-d H:i:s"),
                        "updatetime"=>date("Y-m-d H:i:s")
                     ];
					if($invinfo['inv_type']==5){
					$invpool['seller_id'] = $seller_id??"";
		            $invpool['seller_title'] = $seller_title??"";
		            $invpool['seller_addr'] = $seller_addr??"";
		            $invpool['seller_mobile'] = $seller_mobile??"";
		            $invpool['seller_bank'] = $seller_bank??"";
		            $invpool['seller_bankNo'] = $seller_bankNo??"";
		            $invpool['buyer_id'] = $buyer_id??"";
		            $invpool['buyer_title'] = $buyer_title??"";
		            $invpool['buyer_addr'] = $buyer_addr??"";
		            $invpool['buyer_mobile'] = $buyer_mobile??"";
		            $invpool['buyer_bank'] = $buyer_bank??"";
		            $invpool['buyer_bankNo'] = $buyer_bankNo??"";
		            $invpool['tax_fee'] = $tax_fee??"";
		            $invpool['pdfstream'] = $invimg ??"";
					}
                $in = Db::name("invoice_ticket")->insert($invpool);
	                if($in==false){
	                    Db::rollback();
	                   return error_show(1004,"发票信息添加失败");
	                }
            	}
            if($status==3 && $open_type==1){
            		$invpoolinfo =Db::name("invoice_pool_info")->where(["invNo"=>$invNo])->findOrEmpty();
            		if(empty($invpoolinfo)){
            		    Db::rollback();
	                   return error_show(1004,"开票信息未找到");
            		}
            		$goodinfo =Db::name("invoice_good")
            		->where(["invNo"=>$invNo,"is_del"=>0])
            		->field("0 as FPHXZ,
									catNo  as SPBM,
									id as ZXBM,
									is_discount as YHZCBS,
									if(inv_tag=0,'',inv_tag) as  LSLBS,
									addTax	as ZZSTSGL,
									goodName as XMMC,
									specInfo as GGXH,
									unitName as DW,
									goodNum as SPSL,
									goodPrice as DJ,
									totalPrice as JE,
									1 HSBZ,
									tax as SL,
									taxPrice as SE")
									->select()->toArray();
					if(empty($goodinfo)){
						Db::rollback();
	                    return error_show(1004,"开票商品信息未找到");
					}
//					$taxArr=array_column($goodinfo,"SL");
//					if(count(array_unique($taxArr))>1){
//						array_walk($goodinfo,function (&$v){
//								$v['SL']='';
//						});
//					}
						$data=[
							"invNo"=>$invNo,
							"KPLX"=>"0",
							"XHFSBH"=>$invpoolinfo['seller_code'],
							"XHFMC"=>$invpoolinfo['seller_title'],
							"XHFDZ"=>$invpoolinfo['seller_addr'],
							"XHFDH"=>$invpoolinfo['seller_mobile'],
							"XHFYH"=>$invpoolinfo['seller_bank'],
							"XHFZH"=>$invpoolinfo['seller_bankNo'],
							"GMFBM"=>"",
							"GMFSBH"=>$invpoolinfo['buyer_code'],
							"GMFMC"=>$invpoolinfo['buyer_title'],
							"GMFDZ"=>$invpoolinfo['buyer_addr'],
							"GMFDH"=>$invpoolinfo['buyer_mobile'],
							"GMFYH"=>$invpoolinfo['buyer_bank'],
							"GMFZH"=>$invpoolinfo['buyer_bankNo'],
							"GMFLX"=>$invinfo['company_type'],
							"GMFSJH"=>"",
							"GMFDZYX"=>$invinfo['email'],
							"KPR"=>$invpoolinfo['drawer'],
							"SKR"=>$invpoolinfo['payee'],
							"FHR"=>$invpoolinfo['reviewer'],
							"QDBZ"=>"0",
							"JSHJ"=>$invinfo['inv_value'],
							"HJJE"=>"0",
							"HJSE"=>"0",
							"BZ"=>$invinfo['remark'],
							"DDMXXX"=>json_encode($goodinfo,JSON_UNESCAPED_UNICODE),
							"FPLXDM"=>$this->kingInvoice[$invinfo['inv_type']],
							"DDQQPCH"=>"",
							"DDQQLSH"=>randomkeys(26).date("YmdHis"),
							"status"=>"0",
							"result"=>"",
							"addtime"=>date("Y-m-d H:i:s"),
							"updatetime"=>date("Y-m-d H:i:s")
						];
					$invoice=Db::name("invoice_interface")->insert($data);
					if($invoice==false){
						Db::rollback();
                       return error_show(1003,"开票信息生成失败");
					}

            	}
            if( $update['status']==4){
            	$qrdArr=Db::name("assoc")->where(["viceCode"=>$invNo,"is_del"=>0])->column("id,orderCode,cancel_fee");
                 if(!empty($qrdArr)){
                      foreach ($qrdArr as $value){
                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                          if($qrdinfo==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息未找到");
                          }
                          if($qrdinfo['inv_fee']<$value['cancel_fee']){
                               Db::rollback();
                              return error_show(1003,"确认单信息开票金额不足");
                          }
                          $update =[
                              "ainv_fee"=>$qrdinfo['ainv_fee']+$value['cancel_fee'],
                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
                              "invtime"=>date("Y-m-d H:i:s"),
                              "inv_status"=>$qrdinfo['winv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 3 : 2,
                              "updatetime"=>date("Y-m-d H:i:s"),
                          ];
                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                          if($qrdup==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息更新失败");
                          }
                          $assoc=["status"=>2,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
                          $assocup =Db::name("assoc")->where($value)->update($assoc);
                          if($assocup==false){
                              Db::rollback();
                              return error_show(1003,"确认单关联信息更新失败");
                          }
                      }
                 }
            }
            if($status==7||$status==8){
               $qrdArr=Db::name("assoc")->where(["viceCode"=>$invNo,"is_del"=>0])->column("id,orderCode,cancel_fee");
                 if(!empty($qrdArr)){
                      foreach ($qrdArr as $value){
                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                          if($qrdinfo==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息未找到");
                          }
                          if($qrdinfo['inv_fee']<$value['cancel_fee']){
                               Db::rollback();
                              return error_show(1003,"确认单信息开票金额不足");
                          }
                          $update =[
                              "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
                              "inv_status"=>$qrdinfo['ainv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 1 : 2,
                              "status"=>$qrdinfo['ainv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0&&$qrdinfo['pay_status']==1 ?0 : 1,
                              "updatetime"=>date("Y-m-d H:i:s"),
                          ];
                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                          if($qrdup==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息更新失败");
                          }
                          $assoc=["status"=>3,"updatetime"=>date("Y-m-d H:i:s")];
                          $assocup =Db::name("assoc")->where($value)->update($assoc);
                          if($assocup==false){
                              Db::rollback();
                              return error_show(1003,"确认单关联信息更新失败");
                          }
                           $report=ReportCode::where(["qrdNo"=>$value['orderCode']])->find();
                           if($report)$report->rmField("invNo",$invinfo['invNo']);

                          //将数量加回去
                          Db::name('invoice_good')
                              ->where([
                                  'is_del' => 0,
                                  'invNo' => $invNo,
                                  'orderCode' => $value['orderCode']
                              ])->update(["goodNum"=>0,"updatetime"=>date("Y-m-d H:i:s")]);
                      }
                 }
            }
            Db::commit();
            return app_show(0,"审核成功");
        }
                Db::rollback();
              return error_show(1004,"审核失败");
        }catch (\Exception $e){
              Db::rollback();
              return error_show(1004,$e->getMessage());
        }

   }
    /**
     * 发票设置物流
     */
    public function SetPost(){
     //  @param invNo postCompany postCode postFee;
        $invNo =isset($this->post['invNo'])&&$this->post['invNo']!="" ? trim($this->post['invNo']):"";
        if($invNo==''){
            return error_show(1004,"参数invNo不能为空");
        }
        $invinfo =Db::name("invoice_pool")->where(["invNo"=>$invNo,"is_del"=>0])->find();
        if($invinfo==false){
            return error_show(1004,"发票申请信息未找到");
        }
        if($invinfo['status']!=4) return error_show(1004,"发票审核未完成");
        $post_company =isset($this->post['post_company'])&&$this->post['post_company']!="" ? trim($this->post['post_company']):"";
        if($post_company==''){
            return error_show(1004,"参数 post_company 不能为空");
        }
         $post_code =isset($this->post['post_code'])&&$this->post['post_code']!="" ? trim($this->post['post_code']):"";
        if($post_code==''){
            return error_show(1004,"参数 post_code 不能为空");
        }
        $post_fee =isset($this->post['post_fee'])&&$this->post['post_fee']!="" ? floatval($this->post['post_fee']):"0";
        Db::startTrans();
        try{
            $data=[
                "post_company"=>$post_company,
                "post_code"=>$post_code,
                "post_fee"=>$post_fee,
                "updatetime"=>date("Y-m-d H:i:s")
            ];
            $up =Db::name("invoice_pool")->where($invinfo)->update($data);
            if($up){
                 $qrdArr=Db::name("assoc")->where(["viceCode"=>$invNo,"status"=>1,"is_del"=>0])->column("id,orderCode,cancel_fee");
                 if(!empty($qrdArr)){
                      foreach ($qrdArr as $value){
                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                          if($qrdinfo==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息未找到");
                          }
                          if($qrdinfo['inv_fee']<$value['cancel_fee']){
                               Db::rollback();
                              return error_show(1003,"确认单信息开票金额不足");
                          }
                          $update =[
                              "ainv_fee"=>$qrdinfo['ainv_fee']+$value['cancel_fee'],
                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
                              "invtime"=>date("Y-m-d H:i:s"),
                              "inv_status"=>$qrdinfo['winv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 3 : 2,
                              "updatetime"=>date("Y-m-d H:i:s"),
                          ];
                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                          if($qrdup==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息更新失败");
                          }
                          $assoc=["status"=>2,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
                          $assocup =Db::name("assoc")->where($value)->update($assoc);
                          if($assocup==false){
                              Db::rollback();
                              return error_show(1003,"确认单关联信息更新失败");
                          }
                      }
                 }
                Db::commit();
                return app_show(0,"更新成功");
            }
             Db::rollback();
             return error_show(1003,"发票申请信息更新失败");
        }catch (\Exception $e){
         Db::rollback();
         return error_show(1004,$e->getMessage());
        }
    }
	/**
	* @return \think\response\Json|void
	* @throws \think\db\exception\DbException
	 */
    public function batchCheck(){
    	$param =$this->request->only(["invNos"=>[],"status"=>'',"open_type"=>0,"remark"=>''],"post");
    	$valid=Validate::rule([
    		"invNos|发票编号"=>"require|array",
    	    "status|审核状态"=>"require|number|in:2,8",
    	    "open_type|开票方式"=>"require|number|in:0,1,2,3",
    	    "remark|审核备注"=>"max:255",
    	    ]);
    	if($valid->check($param)==false) return error_show(1004,$valid->getError());
    	$list =Db::name("invoice_pool")->where(["invNo"=>$param['invNos'],"status"=>1,"is_del"=>0])->column("id");
    	if(empty($list)) return error_show(1004,"未找到有效数据");
		$up =Db::name("invoice_pool")
		->where(["id"=>$list,"status"=>1,"is_del"=>0])
		->update([
			"status"=>$param['status'],
			"open_type"=>$param['open_type'],
			"exam_remark"=>$param['remark'],
			"updatetime"=>date("Y-m-d H:i:s")
			]);
		if($up==false) return error_show(1004,"数据审核失败");
		 return app_show(0,"数据审核成功");
    }
    /**
    * 发票废弃使用
    */
    public function  Discard(){
		$invNo = isset($this->post['invNo'])&&$this->post['invNo']!=''?trim($this->post['invNo']):"";
		if($invNo=='') return error_show(1004,"参数invNo不能为空");
		$invinfo =Db::name("invoice_pool")->where(["invNo"=>$invNo,"is_del"=>0])->find();
		if($invinfo==false) return  error_show(1004,"未找到对应发票申请数据");
		if(!in_array($invinfo['status'],[1,2,3,4,5,8]))return  error_show(1004,"发票状态无法废弃");
		$company =Db::name("company_info")->where(["companyNo"=>$invinfo['inv_out']])->find();
		if($company==false)return  error_show(1004,"开票业务公司未找到");
		$invoiceinfo =Db::name("invoice_ticket")->where(["invNo"=>$invNo])->find();
		if($invoiceinfo==false)return  error_show(1004,"发票详细信息未找到");
		Db::startTrans();
		try{
		$invoice=Config::get("invoice");
    	$tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
		 $result=$tax->DeprecateInvoices($company['company_license'],$this->kingInvoice[$invoiceinfo['inv_type']],$invoiceinfo['inv_code'],$invoiceinfo['inv_number'],1);
		 if(isset($result['ZTDM']) && $result['ZTDM']=='050000'){
			 $up =Db::name("invoice_pool")->where($invinfo)->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
			 if($up){

			    $qrdArr=Db::name("assoc")->where(["viceCode"=>$invNo,"is_del"=>0,"status"=>[1,2]])->column("id,orderCode,cancel_fee");
	                 if(!empty($qrdArr)){
	                      foreach ($qrdArr as $value){
	                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
	                          if($qrdinfo==false){
	                              Db::rollback();
	                              return error_show(1003,"确认单信息未找到");
	                          }
	                          if ($invinfo['status']==3){
								 if($qrdinfo['ainv_fee']<$value['cancel_fee']){
	                               Db::rollback();
	                              return error_show(1003,"确认单信息开票金额不足");
	                            }
								  $update =[
	                              "ainv_fee"=>$qrdinfo['ainv_fee']-$value['cancel_fee'],
	                              "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
	                              "inv_status"=>$qrdinfo['ainv_fee']==0 &&$qrdinfo['inv_fee'] ==0 ? 1: 2,
	                              "updatetime"=>date("Y-m-d H:i:s"),
	                          ];
	                          }else{
                                if($qrdinfo['inv_fee']<$value['cancel_fee']){
	                               Db::rollback();
	                              return error_show(1003,"确认单信息开票金额不足");
	                          }
                                 $update =[
	                              "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
	                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
	                              "inv_status"=>$qrdinfo['ainv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee']) ==0 ?1 : 2,
	                              "updatetime"=>date("Y-m-d H:i:s"),
	                          ];
	                        }


	                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
	                          if($qrdup==false){
	                              Db::rollback();
	                              return error_show(1003,"确认单信息更新失败");
	                          }
	                          $assoc=["status"=>3,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
	                          $assocup =Db::name("assoc")->where($value)->update($assoc);
	                          if($assocup==false){
	                              Db::rollback();
	                              return error_show(1003,"确认单关联信息更新失败");
	                          }
	                      }
	                 }

			 	Db::commit();
			 	return app_show(0,"发票废弃成功");
			 }
		 }
		 Db::rollback();
		return  error_show(1004,"发票废弃失败");
		}catch (\Exception $e){
			Db::rollback();
			return  error_show(1004,$e->getMessage());
		}


    }
    /**@param invNo return_reason remark  退票申请
    * @return \think\response\Json|void
     */
    public function ReturnAdd(){
     $invNo = isset($this->post['invNo']) &&  $this->post['invNo']!=''? trim($this->post['invNo']) :'';
     if($invNo==""){
         return error_show(1004,"参数 invNo 不能为空");
     }
     $return_reason = isset($this->post['return_reason']) &&  $this->post['return_reason']!=''? trim($this->post['return_reason']) :'';
     $remark = isset($this->post['remark']) &&  $this->post['remark']!=''? trim($this->post['remark']) :'';
     if($return_reason==""){
          return error_show(1004,"参数 return_reason 不能为空");
     }
     if($remark==""){
          return error_show(1004,"参数 remark 不能为空");
     }
      $invinfo = Db::name("invoice_pool")->where(["invNo"=>$invNo,"is_del"=>0])->find();
        if($invinfo==false){
            return error_show(1004,"发票申请数据未找到");
        }
        if($invinfo['status']!=4){
         return error_show(1004,"发票申请未完成");
        }
     $qrd =Db::name("assoc")->where(["viceCode"=>$invNo,"status"=>2,"is_del"=>0])->column("orderCode");
     if(empty($qrd)){
           return error_show(1004,"未找到开票的销售单信息");
     }
      $isT= Db::name("invoice_return")->where(["invNo"=>$invNo,"status"=>[0,1,2,5]])->findOrEmpty();
        if(!empty($isT)) return error_show(1004,"发票退回流程已存在");

     $returnCode = makeNo("RIN");
     $data=[
         "returnCode"=>$returnCode,
         "invNo"=>$invNo,
         "reason"=>$return_reason,
         "remark"=>$remark,
         "status"=>0,
         "apply_id"=>$this->uid,
         "apply_name"=>$this->uname,
         "addtime"=>date("Y-m-d H:i:s"),
         "updatetime"=>date("Y-m-d H:i:s")
         ];
     Db::startTrans();
     try{

     	$inter = Db::name("invoice_return")->insert($data);
         if($inter){
             foreach ($qrd as $value){
                  $report=ReportCode::where(["qrdNo"=>$value])->find();
                  if($report)$report->setField("returnInv",$returnCode);
             }
             Db::commit();
             return app_show(0,"退票申请新建成功",["returnCode"=>$returnCode]);
         }else{
         	Db::rollback();
             return error_show(1005,"退票申请新建失败");
         }
     }catch (\Exception $e){
     	Db::rollback();
     	return error_show(1006,$e->getMessage());
     }

    }
    // 0 待审核 1 待退票 2 退票成功 3 驳回4 退票失败 5 退票进行中
	// 红冲说明 1100000000 已抵扣  1010000000未抵扣 0000000100尚未寄出
    public function ReturnStatus(){
        $returnCode = isset($this->post['returnCode'])&&$this->post['returnCode']!="" ? trim($this->post['returnCode']):"";
        if($returnCode==""){
            return error_show(1005,"参数 returnCode 不能为空");
        }
        $status = isset($this->post['status'])&&$this->post['status']!="" ? intval($this->post['status']):"";
        if ($status==""){
              return error_show(1005,"参数 status 不能为空");
        }
        $remark =isset($this->post['remark'])&&$this->post['remark']!="" ? trim($this->post['remark']):"";
        $return_reason =isset($this->post['return_reason'])&&$this->post['return_reason']!="" ? trim($this->post['return_reason']):"2";
        $return= Db::name("invoice_return")->where(["returnCode"=>$returnCode])->find();
        if($return==false){
            return error_show(1005,"退票申请信息未找到");
        }
        $red_desc =isset($this->post['red_desc'])&&$this->post['red_desc']!="" ? trim($this->post['red_desc']):"0000000100";
        $invinfo = Db::name("invoice_pool")->where(["invNo"=>$return['invNo'],"is_del"=>0])->find();
        if($invinfo==false){
            return error_show(1004,"发票申请数据未找到");
        }
        if($invinfo['status']!=4){
         return error_show(1004,"发票申请未完成");
        }
         $qrd =Db::name("assoc")->where(["viceCode"=>$return['invNo'],"status"=>2,"is_del"=>0])->column("orderCode");
         if(empty($qrd)){
               return error_show(1004,"未找到开票的销售单信息");
         }
         $ticket = Db::name("invoice_ticket")->where(["invNo"=>$return['invNo'],"type"=>0,"status"=>1,"is_del"=>0])
         ->findOrEmpty();
		 if(empty($ticket)){
		        return error_show(1004,"未找到开票的票面信息");
		  }
		 $ticket['inv_out'] = $invinfo['inv_out']??"";
		 $return_type = isset($this->post['return_type'])&&$this->post['return_type']!="" ? intval($this->post['return_type']):0;
		  if($status==1){
	        if ($return_type==""){
	              return error_show(1005,"参数 return_type 不能为空");
	        }
	       if ($red_desc==""){
	              return error_show(1005,"参数 red_desc 不能为空");
	        }
	        if($return_type==2){
				$invCode =isset($this->post['invCode'])&&$this->post['invCode']!=''?trim($this->post['invCode']):"";
	            $invNum =isset($this->post['invNum'])&&$this->post['invNum']!=''?trim($this->post['invNum']):"";
	            $open_date =isset($this->post['open_date'])&&$this->post['open_date']!=''?trim($this->post['open_date']):"";
	            $checkCode =isset($this->post['checkCode'])&&$this->post['checkCode']!=''?trim($this->post['checkCode']):"";
	            $subtotal_fee =isset($this->post['subtotal_fee'])&&$this->post['subtotal_fee']!=''?floatval($this->post['subtotal_fee']):"";
	            if($invCode==='') return error_show(1004,"参数 invCode 不能为空");
	            if($invNum==='') return error_show(1004,"参数 invNum 不能为空");
	            if($open_date==='') return error_show(1004,"参数 open_date 不能为空");
	            if(in_array($invinfo['inv_type'],['normal','roll',"toll",'electronic'])){
               	    if($checkCode==='') return error_show(1004,"参数 checkCode 不能为空");
               }
	            if($subtotal_fee==='') return error_show(1004,"参数 subtotal_fee 不能为空");
            }
        }
//电子普票 只能红冲 不能作废
//电子专票 只能红冲 不能作废
//纸质专票 当月可以作废 次月红冲
//纸质普票  当月作废 次月红冲
//专票 红冲先做红字申请

         Db::startTrans();
         try{
         	$isoutmonth =date("Y-m",strtotime($ticket["open_date"]))==date("Y-m")?0:1;
             $update=[
             	"status"=>$status,
                "remark"=>$remark,
                "updatetime"=>date("Y-m-d H:i:s")
                ];
             if($status==1) {
             	$update['is_out_month']=$isoutmonth;
             	$update['red_desc']=$red_desc;
             	$update['return_reason']=$return_reason;
             	$update['return_type']=$return_type;
             }
             $up =Db::name("invoice_return")->where($return)->update($update);
            if($up){
            	if($status==1){
            		if($return_type==1){
//            			$discard=0;
//	                    if(date("Y-m-d",strtotime($ticket["open_date"]))==date("Y-m-d")){
//	                    	//当月纸质普通发票+纸质专用发票 作废
//	                    	if(in_array($ticket['inv_type'],['004','007'])){
//			                    $discard=1;
////			                    $result= $this->addDiscard($ticket,$returnCode);
//			                    if(in_array($ticket['inv_type'],['007','026'])) $result= $this->addRedOpen($ticket,2, $invinfo['company_type'], $returnCode);
//
//		                    }
//
//	                    	//当月电子普票红冲
//	                    	if($ticket['inv_type']=='026')$result= $this->addRedOpen($ticket,$return_reason,$invinfo['company_type'], $returnCode);
//	                    	//当月电子专票红冲
//	                    	if($ticket['inv_type']=='028')$result=  $this->addApplyRed($ticket,$returnCode);
//	                    }else{
//	                    	//跨月票都走红冲
//	                    	if(in_array($ticket['inv_type'],['007','026'])) $result= $this->addRedOpen($ticket,$return_reason,$invinfo['company_type'], $returnCode);
//	                    	if(in_array($ticket['inv_type'],['004','028'])) $result= $this->addApplyRed($ticket,$returnCode);
//	                    }
	                    if(in_array($ticket['inv_type'],['007','026'])) $result= $this->addRedOpen($ticket,$return_reason,$invinfo['company_type'],$returnCode,$red_desc);
	                    if(in_array($ticket['inv_type'],['004','028'])) $result= $this->addApplyRed($ticket,$return_reason,$returnCode,$red_desc);
						if(isset($result['code'])){
							if(isset($result['data']) &&$result['invRed']!='' ){
								$upd=Db::name("invoice_return")->where(["returnCode"=>$returnCode])->update(['red_inv'=>$result['invRed'],"updatetime"=>date("Y-m-d H:i:s")]);
								if($upd==false) throw  new \Exception("退票更新失败");
							}
						}

		                    }else{
								 $invpool=[
		                        "invNo"=>$invinfo['invNo'],
		                        "type"=>1,
		                        "inv_type"=>$ticket['inv_type'],
		                        "inv_code"=>$invCode,
		                        "inv_number"=>$invNum,
		                        "check_code"=>$checkCode,
		                        "inv_total"=>0,
		                        "inv_subtotal"=>$subtotal_fee,
		                        "open_date"=>$open_date,
		                        "item"=>'',
		                        'pdfstream'=>'',
		                        "status"=>0,
		                        "addtime"=>date("Y-m-d H:i:s"),
		                        "updatetime"=>date("Y-m-d H:i:s")
		                     ];
		                    $in = Db::name("invoice_ticket")->insert($invpool);
			                if($in==false)throw  new \Exception("退票信息添加失败");
		                }
            		}
                if($status==2){
                	    $infoup =Db::name("invoice_good")->where(["invNo"=>$return['invNo'],"is_del"=>0])->update(["goodNum"=>0,"updatetime"=>date("Y-m-d H:i:s")]);
                	    if($infoup==false)throw  new \Exception("退票商品信息修改失败");
                	    $poolup=Db::name("invoice_pool")->where(["invNo"=>$return['invNo'],"is_del"=>0,"status"=>4])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
						if($poolup==false)throw new \Exception($return['invNo']."开票票数据更新失败");
                      $qrdArr=Db::name("assoc")->where(["viceCode"=>$return['invNo'],"is_del"=>0,"status"=>2])->column("id,orderCode,cancel_fee");
                     if(!empty($qrdArr)){
                          foreach ($qrdArr as $value){
                              $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                              if($qrdinfo==false){
                                throw  new Exception("确认单信息未找到");
//                                  return error_show(1003,"确认单信息未找到");
                              }
                              if($qrdinfo['ainv_fee']<$value['cancel_fee']){
                                   throw  new Exception("确认单信息开票金额不足");
//                                  return error_show(1003,"确认单信息开票金额不足");
                              }
                              $update =[
                                  "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
                                  "ainv_fee"=>$qrdinfo['ainv_fee']-$value['cancel_fee'],
                                  "inv_status"=>$qrdinfo['inv_fee']==0 &&$qrdinfo['ainv_fee']-$value['cancel_fee']==0 ? 1 : 2,
                                  "status"=>$qrdinfo['ainv_fee']==0 &&$qrdinfo['inv_fee']-$value['cancel_fee']==0&&$qrdinfo['pay_status']==1 ?0 : 1,
                                  "updatetime"=>date("Y-m-d H:i:s"),
                              ];
                              $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                              if($qrdup==false){
                                  throw  new Exception("确认单信息更新失败");
//                                  return error_show(1003,"确认单信息更新失败");
                              }
                              $assoc=["status"=>3,"updatetime"=>date("Y-m-d H:i:s")];
                              $assocup =Db::name("assoc")->where($value)->update($assoc);
                              if($assocup==false){
                                  throw  new Exception("确认单关联信息更新失败");
//                                  return error_show(1003,"确认单关联信息更新失败");
                              }
                          }
                     }else{
                     	throw  new Exception("未找到关联订单数据信息");
                     }
                }
                if($status==3 || $status==4){
                     foreach ($qrd as $value){
                      $report=ReportCode::where(["qrdNo"=>$value])->find();
                      if($report)$report->rmField("returnInv",$returnCode);
                 }
                }
                Db::commit();
                return app_show(0,"退票申请信息更新成功");
            }
            Db::rollback();
            return error_show(1005,"退票申请信息更新失败");

         }catch (\Exception $e){
              Db::rollback();
            return error_show(1005,$e->getMessage());
         }

    }
    //红冲票

    private  function addDiscard($ticket=[],$returnCode){
		$invoice=Config::get("invoice");
    	$tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
    	$result=$tax->DeprecateInvoices($ticket['seller_id'],$ticket['inv_type'],$ticket['inv_code'],$ticket['inv_number'],1);
    	 if(isset($result['ZTDM']) && ($result['ZTDM']=='050000' || $result['ZTDM']=='053000')){
    	 	    if($result['ZTDM']=='053000'){
	                $up= Db::name("invoice_return")->where(['returnCode'=>$returnCode])->update(["discard"=>2,"updatetime"=>date("Y-m-d H:i:s")]);
	                if($up==false)throw new \Exception('发票废弃中,信息更新失败', 1006);
	                return ["code"=>1,"message"=>"发票废弃中"];
    	 	    }else{
    	 	    	$ups=Db::name("invoice_return")->where(['returnCode'=>$returnCode])->update(["status"=>2,"discard"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
    	 	        if($ups==false)throw new \Exception('发票已废弃,信息更新失败', 1006);
			        $up =Db::name("invoice_pool")->where(['invNo'=>$ticket['invNo']])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
				    if($up==false)throw new \Exception('发票已废弃,信息更新失败', 1006);
				 	return ["code"=>0,"message"=>"发票废弃成功"];
    	 	    }

		 }else{
    	 	throw new \Exception($result['ZTXX'], 1006);
		 }
    }
    //退票详情

    /**
	* @param array $ticket
	 * @return \think\response\Json|void
	* @throws \think\Exception
	 */
    private function  addRedOpen($ticket=[],$return_reason,$company_type,$returnCode,$red_desc){

    	$goodinfo =Db::name("invoice_good")
            		->where(["invNo"=>$ticket['invNo'],"is_del"=>0])
            		->field("0 as FPHXZ, 
									catNo  as SPBM,
									id as ZXBM,
									is_discount as YHZCBS,
									if(inv_tag=0,'',inv_tag) as  LSLBS,
									addTax	as ZZSTSGL,
									goodName as XMMC,
									'' as DW,
									'' as SPSL,
									'' as DJ,
									(-totalPrice) as JE,
									0 HSBZ,
									tax as SL,
									-taxPrice as SE")->select()->toArray();
					if(empty($goodinfo)){
						throw new \Exception("开票商品信息未找到", 10006);

					}
		if(count($goodinfo)>8){
		$len =array_unique(array_column($goodinfo,'SL'));
	    $qdmx=["FPHXZ"=>6,
		    "SPBM"=>'',
		    "XMMC"=>"详见对应正数发票及清单",
		    "YHZCBS"=>0,
		    "LSLBS"=>'',
		    "ZZSTSGL"=>'',
		    "DW"=>'',
		    "SPSL"=>'',
		    "DJ"=>'',
		    "JE"=>sprintf("%01.2f", (array_sum(array_column($goodinfo,'JE')))),
		    "HSBZ"=>'0',
		    "SL"=>count($len)>1?'':$len[0],
		    "SE"=>sprintf("%01.2f",array_sum(array_column($goodinfo,'SE'))),
	        ];
		}else
		{$qdmx=$goodinfo;}
        $invRed=makeNo("IRE");
		$reddata=[
			'invNo'=>$ticket['invNo'],
			"invRed"=>$invRed,
			"inv_out"=>$ticket['inv_out'],
			"returnCode"=>$returnCode,
			"apply_id"=>$this->uid,
			"apply_name"=>$this->uname,
			"status"=>3,
			"remark"=>'',
			"addtime"=>date("Y-m-d H:i:s"),
			"updatetime"=>date("Y-m-d H:i:s"),
			"SQBSCQQLSH"=>'',
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>$red_desc, //申请说明 1100000000 已抵扣  1010000000未抵扣 0000000100尚未寄出
			 "XXBTSBS"=>"0",
			 "red_reason"=>$return_reason,
			 "DDMXXX"=>json_encode($goodinfo,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>'',
			 "FPLXDM"=>$ticket['inv_type'],
		];

							$data=[	"invNo"=>$invRed,
							"KPLX"=>"1",
							"XHFSBH"=>$ticket['seller_id'],
							"XHFMC"=>$ticket['seller_title'],
							"XHFDZ"=>$ticket['seller_addr'],
							"XHFDH"=>$ticket['seller_mobile'],
							"XHFYH"=>$ticket['seller_bank'],
							"XHFZH"=>$ticket['seller_bankNo'],
							"GMFBM"=>"",
							"GMFSBH"=>$ticket['buyer_id'],
							"GMFMC"=>$ticket['buyer_title'],
							"GMFDZ"=>$ticket['buyer_addr'],
							"GMFDH"=>$ticket['buyer_mobile'],
							"GMFYH"=>$ticket['buyer_bank'],
							"GMFZH"=>$ticket['buyer_bankNo'],
							"GMFLX"=>$company_type,
							"GMFSJH"=>"",
							"GMFDZYX"=>'',
							"KPR"=>$ticket['issuer'],
							"SKR"=>$ticket['reciver'],
							"FHR"=>$ticket['reviewer'],
							"QDBZ"=>"0",
							"YFPDM"=>$ticket['inv_code'],
							"YFPHM"=>$ticket['inv_number'],
							"YFPLX"=>$ticket['inv_type'],
							"YFPKPRQ"=>date("Y-m-d",strtotime($ticket['open_date'])),
							"CHYY"=>$return_reason,
							"TSCHBZ"=>"0",
							"JSHJ"=>"-".$ticket['inv_total'],
							"HJJE"=>"-".$ticket['inv_subtotal'],
							"HJSE"=>"-".$ticket['tax_fee'],
							"BZ"=>  "对应正数发票代码:{$ticket['inv_code']} 号码:{$ticket['inv_number']}",
							"DDMXXX"=>json_encode($qdmx,JSON_UNESCAPED_UNICODE),
							"FPLXDM"=>$ticket['inv_type'],
							"DDQQPCH"=>"",
							"DDQQLSH"=>randomkeys(26).date("YmdHis"),
							"status"=>"0",
							"result"=>"",
							"addtime"=>date("Y-m-d H:i:s"),
							"updatetime"=>date("Y-m-d H:i:s")
						];
		$invoice=Db::name("invoice_interface")->insert($data);
		if($invoice==false){
			throw new Exception("红冲提交失败",1006);
		}
		$upred=Db::name("invoice_red")->save($reddata);
		if($upred==false){
			throw new Exception("红冲提交失败",1006);
		}
		return ["code"=>0,"message"=>"红冲申请提交成功","invRed"=>$invRed];
    }

	/**
	* @param array $ticket
	 * @return \think\response\Json|void
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
    private function  addApplyRed($ticket=[],$return_reason,$returnCode,$red_desc){
    	$invoice=Config::get("invoice");
		$Tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
		$redticketList=[];
		$redticketArry=[
			"SQBSCQQPCH"=>randomkeys(26).date("YmdHis"),
			"NSRSBH"=>$ticket['seller_id'],
			"FPLXDM"=>$ticket['inv_type'],
		];
		$goodinfo =Db::name("invoice_good")
            		->where(["invNo"=>$ticket['invNo'],"is_del"=>0])
            		->field("0 as FPHXZ, 
									catNo  as SPBM,
									id as ZXBM,
									is_discount as YHZCBS,
									if(inv_tag=0,'',inv_tag) as  LSLBS,
									addTax	as ZZSTSGL,
									goodName as XMMC,
									'' as DW,
									'' as SPSL,
									'' as DJ,
									(-totalPrice) as JE,
									0 HSBZ,
									tax as SL,
									-taxPrice as SE")->select()->toArray();
					if(empty($goodinfo)){
						throw new \Exception("开票商品信息未找到", 10006);

					}
		if(count($goodinfo)>8){
			$len =array_unique(array_column($goodinfo,'SL'));
	    $qdmx=["FPHXZ"=>6,
		    "SPBM"=>'',
		    "XMMC"=>"详见对应正数发票及清单",
		    "YHZCBS"=>0,
		    "LSLBS"=>'',
		    "ZZSTSGL"=>'',
		    "DW"=>'',
		    "SPSL"=>'',
		    "DJ"=>'',
		    "JE"=>sprintf("%01.2f", (array_sum(array_column($goodinfo,'JE')))),
		    "HSBZ"=>'0',
		    "SL"=>count($len)>1?'':$len[0],
		    "SE"=>sprintf("%01.2f",array_sum(array_column($goodinfo,'SE'))),
	        ];
		}else
			{
				$qdmx=$goodinfo;
			}

		$info=[
			"SQBSCQQLSH"=>randomkeys(26).date("YmdHis"),
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>$red_desc, //申请说明
			 "XXBTSBS"=>"0",
			 //0: 正常;1:成品油发票,涉及销售数量 变更(销货退回、开票有误等原因);2: 成品油发票,仅涉及销售金额变更(销 售折让);3:机动车发票,仅涉及销售数
//量变更(销货退回、开票有误等原因);4: 机动车发票,仅涉及销售金额变更(销 售折让)
		];
		$invRed=makeNo("IRE");
		$data=[
			'invNo'=>$ticket['invNo'],
			"invRed"=>$invRed,
			"inv_out"=>$ticket['inv_out'],
			"returnCode"=>$returnCode,
			"apply_id"=>$this->uid,
			"apply_name"=>$this->uname,
			"status"=>0,
			"remark"=>'',
			"addtime"=>date("Y-m-d H:i:s"),
			"updatetime"=>date("Y-m-d H:i:s"),
			"SQBSCQQLSH"=>$info['SQBSCQQLSH'],
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>$red_desc, //申请说明
			 "red_reason"=>$return_reason,
			 "XXBTSBS"=>"0",
			 "DDMXXX"=>json_encode($qdmx,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>$redticketArry['SQBSCQQPCH'],
			 "FPLXDM"=>$ticket['inv_type'],
		];
	    $redticketList[]=["HZSQDTXX"=>$info,"DDMXXX"=>$qdmx];
		$result=$Tax->AllocateRedInvoiceApplication($redticketArry,$redticketList);
		$data['status']=5;
		$data['remark']='红冲申请提交失败';

		if(isset($result['ZTDM']) && $result['ZTDM']=='060000'){
			$resultChild=$result['HZSQDSCJG'][0];
			if($resultChild['ZTDM']=='060000'){
				$data['status']=2;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='红冲申请审核通过';
			}
			if($resultChild['ZTDM']=='060001'){
				$data['status']=1;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='红冲申请审核中';
			}
		}
		if($data['status']==5){
			throw new \Exception($result['ZTXX'], 10006);
		}
		$up =Db::name("invoice_red")->insert($data);
		if($up) return ["code"=>0,"message"=>"红冲发票申请新建成功","invRed"=>$invRed];
		else throw new \Exception($result['ZTXX'], 1006);
    }
    //获取发票详情

    public function returnRed(){
        $returnCode = isset($this->post['returnCode'])&&$this->post['returnCode']!="" ? trim($this->post['returnCode']):"";
        if($returnCode==""){
            return error_show(1005,"参数 returnCode 不能为空");
        }
        $return= Db::name("invoice_return")->where(["returnCode"=>$returnCode])->find();
        if($return==false){
            return error_show(1005,"退票申请信息未找到");
        }
        $redinv =isset($this->post['redinv'])&&$this->post['redinv']!="" ? trim($this->post['redinv']):"";
        if($redinv==""){
            return error_show(1005,"参数 redinv 不能为空");
        }
		$red =Db::name("invoice_red")->where(["invRed"=>$redinv,"is_del"=>0])->findOrEmpty();
        if(empty($red)) return error_show(1005,"红冲发票信息未找到");
        if($red['status']!=4) return error_show(1005,"红冲发票开票未完成");

         $invinfo = Db::name("invoice_pool")->where(["invNo"=>$return['invNo'],"is_del"=>0])->find();
         if($invinfo==false){
            return error_show(1005,"发票申请信息未找到");
         }
        Db::startTrans();
        try{

        $update=["status"=>2,"red_inv"=>$redinv,"updatetime"=>date("Y-m-d H:i:s")];
        $up =Db::name("invoice_return")->where($return)->update($update);
        if($up){
            $invup = ["status"=>6,"updatetime"=>date("Y-m-d H:i:s")];
            $inv=Db::name("invoice_pool")->where($invinfo)->update($invup);
            if($inv){
                 $qrdArr=Db::name("assoc")->where(["viceCode"=>$return['invNo'],"is_del"=>0])->column("id,orderCode,cancel_fee");
                 if(!empty($qrdArr)){
                      foreach ($qrdArr as $value){
                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                          if($qrdinfo==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息未找到");
                          }
                          if($qrdinfo['ainv_fee']<$value['cancel_fee']){
                               Db::rollback();
                              return error_show(1003,"确认单信息开票金额不足");
                          }
                          $update =[
                              "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
                              "ainv_fee"=>$qrdinfo['ainv_fee']-$value['cancel_fee'],
                              "inv_status"=>$qrdinfo['inv_fee']==0 &&$qrdinfo['ainv_fee']-$value['cancel_fee']==0 ?
                              1 : 2,
                              "status"=>$qrdinfo['inv_fee']==0 &&$qrdinfo['ainv_fee']-$value['cancel_fee']==0 && $qrdinfo['pay_status']==1 ?0 : 1,
                              "updatetime"=>date("Y-m-d H:i:s"),
                          ];
                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                          if($qrdup==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息更新失败");
                          }
                          $assoc=["status"=>3,"updatetime"=>date("Y-m-d H:i:s")];
                          $assocup =Db::name("assoc")->where($value)->update($assoc);
                          if($assocup==false){
                              Db::rollback();
                              return error_show(1003,"确认单关联信息更新失败");
                          }
                      }
                 }
              Db::commit();
              return app_show(0,"退票申请信息更新成功");
            }
        }
            Db::rollback();
            return error_show(1005,"退票申请信息更新失败");
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1005,$e->getMessage());
        }
    }
	//开票异常失败后修改票面信息

    public function  returnInfo(){
        $returnCode = isset($this->post['returnCode'])&&$this->post['returnCode']!="" ? trim($this->post['returnCode']):"";
        if($returnCode==""){
            return error_show(1005,"参数 returnCode 不能为空");
        }
        $return= Db::name("invoice_return")->where(["returnCode"=>$returnCode])->find();
        if($return==false){
            return error_show(1005,"退票申请信息未找到");
        }
        $invinfo = Db::name("invoice_pool")->where(["invNo"=>$return['invNo'],"is_del"=>0])->find();
        $return['inv_out']= $invinfo['inv_out']??"";
        $return['inv_value']= $invinfo['inv_value']??"";
        $return['inv_apply_id']= $invinfo['apply_id']??"";
        $return['inv_apply_name']= $invinfo['apply_name']??"";
        $return['inv_type']= $invinfo['inv_type']??"";
        $return['open_type']= $invinfo['open_type']??"";
        $return['is_ticket']= $invinfo['is_ticket']??"";
        $return['email']= $invinfo['email']??"";
        $return['post_code']= $invinfo['post_code']??"";
        $return['post_company']= $invinfo['post_company']??"";
        $return['check_remark']= $invinfo['check_remark']??"";
        $poolinfo =  Db::name("invoice_pool_info")->where(["invNo"=>$return['invNo']])->find();
        $return['buyer_title'] = $poolinfo['buyer_title']??'';
        $return['buyer_title'] = $poolinfo['buyer_title']??'';
        $return['buyer_code'] = $poolinfo['buyer_code']??'';
        $return['buyer_addr'] = $poolinfo['buyer_addr']??'';
        $return['buyer_mobile'] = $poolinfo['buyer_mobile']??'';
        $return['buyer_bank'] = $poolinfo['buyer_bank']??'';
        $return['buyer_bankNo'] = $poolinfo['buyer_bankNo']??'';
        $return['seller_title'] = $poolinfo['seller_title']??'';
        $return['seller_addr'] = $poolinfo['seller_addr']??'';
        $return['seller_code'] = $poolinfo['seller_code']??'';
        $return['seller_mobile'] = $poolinfo['seller_mobile']??'';
        $return['seller_bank'] = $poolinfo['seller_bank']??'';
        $return['seller_bankNo'] = $poolinfo['seller_bankNo']??'';
        $return['voider'] = $poolinfo['voider']??'';
        $return['payee'] = $poolinfo['payee']??'';
        $return['drawer'] = $poolinfo['drawer']??'';
        $return['reviewer'] = $poolinfo['reviewer']??'';
        $return['ownerPlace'] = $poolinfo['ownerPlace']??'';
        $orderList =Db::name("invoice_good")->where(["invNo"=>$return['invNo'],"is_del"=>0])->select()->toArray();
        $return['goodList']=$orderList;
        $info =Db::name("invoice_ticket")->where(["invNo"=>$return['invNo'],"is_del"=>0,"type"=>1]) ->field("inv_subtotal,inv_total,check_code,inv_number,inv_code,open_date")->find();
        $return['inv_number']=$info['inv_number']??"";
        $return['inv_code']=$info['inv_code']??"";
        $return['open_date']=date("Y-m-d",strtotime($info['open_date']));
        $return['inv_subtotal']=$info['inv_subtotal']??"";
        $return['inv_total']=$info['inv_total']??"";
        $return['check_code']=$info['check_code']??"";
        if(!in_array($return['status'],[2,3,4,5])){
				$opendate =$info['open_date']??"";;
				if($opendate!=''){
					$open_month =date("Y-m",strtotime($opendate));
					$return['is_out_month']= $open_month==date("Y-m")?0:1;
				}

          }
        return app_show(0,"获取成功",$return);
    }
    /**
     *发票池列表
     */
    public function list(){
        $page=isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']) :1;
        $size=isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']) :15;
        $condition=[["a.is_del","=",0]];
        $start = isset($this->post['start'])&&$this->post['start']!="" ? trim($this->post['start']) :"";
        $end = isset($this->post['end'])&&$this->post['end']!="" ? trim($this->post['end']) :"";
         $roleid = $this->roleid;
        $check = checkRole($roleid,'84');
        if($check){
        	$condition[]=["a.apply_id","=",$this->uid];
        }
        if($start!=""){
            $condition[]=["a.addtime",">=",$start." 00:00:00"];
        }

        if($end!=""){
            $condition[]=["a.addtime","<=",$end." 23:59:59"];
        }
        $status= isset($this->post['status'])&&$this->post['status']!=="" ? intval($this->post['status']):"";
        if($status!==""){
          $condition[]=["a.status","=",$status];
        }
        $inv_type = isset($this->post['inv_type'])&&$this->post['inv_type']!=="" ? trim($this->post['inv_type']):"";
        if($inv_type!==""){
           $condition[]=["a.inv_type","=",$inv_type];
        }
        $inv_out= isset($this->post['inv_out'])&&$this->post['inv_out']!=="" ? trim($this->post['inv_out']):"";
        if($inv_out!==""){
           $condition[]=["a.inv_out","=",$inv_out];
        }
         $platform_type= isset($this->post['platform_type'])&&$this->post['platform_type']!=="" ? intval($this->post['platform_type']):"";
        if($platform_type!==""){
           $condition[]=["a.platform_type","=",$platform_type];
        }
//          $inv_in = isset($this->post['inv_in'])&&$this->post['inv_in']!=="" ? trim($this->post['inv_in']):"";
//        if($inv_in!==""){
//           $condition[]=["a.inv_in","=",$inv_in];
//        }
         $invNo = isset($this->post['invNo'])&&$this->post['invNo']!=="" ? trim($this->post['invNo']):"";
        if($invNo!==""){
           $condition[]=["a.invNo","like","%$invNo%"];
        }
        $relaComNo= isset($this->post['relaComNo'])&&$this->post['relaComNo']!="" ? trim($this->post['relaComNo']) :"";
         if($relaComNo!=""){
            $condition[]=["a.inv_out","=",$relaComNo];
        }
        $inv_number = isset($this->post['inv_number'])&&$this->post['inv_number']!=="" ? trim($this->post['inv_number']):"";
        if($inv_number!==""){
           $condition[]=["c.inv_number","like","%$inv_number%"];
        }
         $inv_code = isset($this->post['inv_code'])&&$this->post['inv_code']!=="" ? trim($this->post['inv_code']):"";
        if($inv_code!==""){
           $condition[]=["c.inv_code","like","%$inv_code%"];
        }
         $inv_company = isset($this->post['inv_company'])&&$this->post['inv_company']!=="" ? trim($this->post['inv_company']):"";
        if($inv_company!==""){
           $condition[]=["a.inv_company","like","%$inv_company%"];
        }
         $buyer_name = isset($this->post['buyer_name'])&&$this->post['buyer_name']!=="" ? trim($this->post['buyer_name']):"";
        if($buyer_name!==""){
           $condition[]=["b.buyer_title","like","%$buyer_name%"];
        }

         $apply_id = isset($this->post['apply_id'])&&$this->post['apply_id']!=="" ? intval($this->post['apply_id']):"";
        if($apply_id!==""){
           $condition[]=["a.apply_id","=",$apply_id];
        }
        $apply_name = isset($this->post['apply_name'])&&$this->post['apply_name']!==""?trim($this->post['apply_name']) :"";
        if($apply_name!==""){
           $condition[]=["a.apply_name","like","%$apply_name%"];
        }
        $count=Db::name("invoice_pool")->alias("a")
        ->rightJoin("invoice_pool_info b","a.invNo=b.invNo")
        ->leftJoin("invoice_ticket c","a.invNo=c.invNo and c.type=0 and c.is_del=0")
        ->where($condition)->count();
        $total =ceil($count/$size);
        $page= $page>$total ? intval($total):$page;
        $list=Db::name("invoice_pool")->alias("a")
        ->rightJoin("invoice_pool_info b","a.invNo=b.invNo")
        ->leftJoin("invoice_ticket c","a.invNo=c.invNo and c.type=0 and c.is_del=0")
        ->where($condition)->field("a.id,
						a.invNo,
						a.platform_type,
						a.open_type,
						a.is_ticket,
						a.tag_id,
						a.apply_id,
						a.apply_name,
						a.status,
						a.inv_value,
						a.inv_type,
						a.buyer_check,
						a.seller_check,
						a.exam_remark,
						a.check_remark,
						a.inv_company,
						a.inv_out,
						b.buyer_title,
						b.seller_title,
						a.addtime,
						c.inv_code,
						c.inv_number,
						c.open_date,
						c.type")
        ->page($page,$size)->order("a.addtime desc")->select()->toArray();
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
    //获取发票详情
    public function info(){
      $invNo = isset($this->post['invNo'])&& $this->post['invNo']!='' ? trim($this->post['invNo']):"";
      if($invNo==''){
          return error_show(1004,"参数 invNo 不能为空");
      }
      $poolinfo =Db::name("invoice_pool")->where([["invNo","=",$invNo],["is_del","=",0]])->findOrEmpty();
      if(empty($poolinfo)){
             return error_show(1004,"为找到开票信息");
      }
        $pool =  Db::name("invoice_pool_info")->where(["invNo"=>$invNo])->find();
        $poolinfo['buyer_title'] = $pool['buyer_title']??'';
        $poolinfo['buyer_code'] = $pool['buyer_code']??'';
        $poolinfo['buyer_addr'] = $pool['buyer_addr']??'';
        $poolinfo['buyer_mobile'] = $pool['buyer_mobile']??'';
        $poolinfo['buyer_bank'] = $pool['buyer_bank']??'';
        $poolinfo['buyer_bankNo'] = $pool['buyer_bankNo']??'';
        $poolinfo['seller_title'] = $pool['seller_title']??'';
        $poolinfo['seller_addr'] = $pool['seller_addr']??'';
        $poolinfo['seller_code'] = $pool['seller_code']??'';
        $poolinfo['seller_mobile'] = $pool['seller_mobile']??'';
        $poolinfo['seller_bank'] = $pool['seller_bank']??'';
        $poolinfo['seller_bankNo'] = $pool['seller_bankNo']??'';
        $poolinfo['voider'] = $pool['voider']??'';
        $poolinfo['payee'] = $pool['payee']??'';
        $poolinfo['drawer'] = $pool['drawer']??'';
        $poolinfo['reviewer'] = $pool['reviewer']??'';
        $poolinfo['ownerPlace'] = $pool['ownerPlace']??'';
        $orderList =Db::name("invoice_good")->where(["invNo"=>$invNo,"is_del"=>0])->column("*","orderCode");

        $poolinfo['goodList']=$orderList;
        $poolinfo['invinfo']=Db::name("invoice_ticket")->withoutField("pdfstream")->where(["invNo"=>$invNo,"type"=>0,"is_del"=>0])
        ->findOrEmpty();
        $orderinfo = Db::name("assoc")->alias("a")->leftJoin("qrd_info c","a.orderCode=c.sequenceNo")
           	->where(["a.viceCode"=>$invNo,"a.is_del"=>0,"a.status"=>[1,2]])
           	->order("a.addtime desc")
           	->field("c.*,a.cancel_fee")
           	->select()->toArray();
         foreach ($orderinfo as &$item){
             $item['ainv_num'] = Db::name("invoice_pool")
                 ->alias("a")
                 ->leftJoin("invoice_good b", "a.invNo=b.invNo and b.is_del=0")
                 ->where(["a.status" => [0, 1, 2, 3], "b.orderCode" => $item['sequenceNo']])
                 ->where('a.invNo', '<>', $invNo)
                 ->sum("b.goodNum");
			$item['winv_num'] = $item['goodNum'] - $item['ainv_num'];
			$item['inv_num'] = $orderList[$item['sequenceNo']]['goodNum'];
        }
        $poolinfo['orderinfo']=$orderinfo;
       return app_show(0,"获取成功",$poolinfo);
    }

	//批量申请红冲发票

    public function TicketEdit(){
		$post=$this->request->only([
			"invNo"=>"", //开票申请编号
			"inv_code"=>"",//发票编码
			"inv_number"=>"",//发票号码
			"inv_subtotal"=>"",//发票税前额度
			"inv_total"=>"",//发票额度
			"open_date"=>"",//开票日期
			"check_code"=>"",//发票校验码
			],"post","trim");
		$valid=Validate::rule([
			"invNo|开票申请编号"=>"require|max:255",
			"inv_code|开票代码"=>"number",
			"inv_number|开票编号"=>"number",
			"inv_subtotal|不含税金额"=>"float",
			"inv_total|价税合计"=>"float",
			"open_date|开票日期"=>"date",
			"check_code|校验码"=>"max:255",
			]);
		if($valid->check($post)==false) return error_show(1004,$valid->getError());
		$ticketinfo =Db::name("invoice_ticket")->where(["invNo"=>$post['invNo'],"is_del"=>0,"type"=>0])->findOrEmpty();
		if(empty($ticketinfo)) return error_show(1004,"未找到开票数据");
		$pool = Db::name("invoice_pool")->where(["invNo"=>$post['invNo'],"is_del"=>0,"status"=>[5,9]])->findOrEmpty();
		if(empty($pool)) return error_show(1004,"开票申请数据不可修改");
		if($pool['open_type']==1)return error_show(1004,"金税开票数据不可修改");
				if($post['inv_number']==='') return error_show(1004,"参数 inv_number不能为空");
               if($post['open_date']==='') return error_show(1004,"参数 open_date 不能为空");
               if(in_array($pool['inv_type'],['normal','roll',"toll",'electronic'])){
               	    if($post['check_code']==='') return error_show(1004,"参数 check_code不能为空");
               }
               //全电子发票
	           if(in_array($pool['inv_type'],['fully_digitalized_special_electronic','fully_digitalized_normal_electronic'])){
	           	    //全电发票传含税金额
	              if($post['inv_total']=='') return error_show(1004,"参数 inv_total 不能为空");
	           }else{
	           	//全电发票无invCode
	           	 if($post['inv_code']==='') return error_show(1004,"参数 inv_code不能为空");
	           	 if($post['inv_subtotal']==='') return error_show(1004,"参数 inv_subtotal 不能为空");
	           }
		Db::startTrans();
		try{
			$Ticket=[
				"inv_code"=>$post['inv_code'],//发票编码
				"inv_number"=>$post['inv_number'],//发票号码
				"inv_subtotal"=>$post['inv_subtotal'],//发票税前额度
				"inv_total"=>$post['inv_total'],//发票额度
				"open_date"=>$post['open_date'],//开票日期
				"check_code"=>$post['check_code'],//发票校验码
				"status"=>0,//带校验
				"updatetime"=>date("Y-m-d H:i:s")//发票校验码
				];
			$ticket =Db::name("invoice_ticket")->where($ticketinfo)->update($Ticket);
			if($ticket==false) throw new \Exception("开票信息更新失败");
			$polup =Db::name("invoice_pool")->where($pool)->update(["status"=>3,"check_remark"=>"","updatetime"=>date("Y-m-d H:i:s")]);
			if($polup==false) throw new \Exception("开票申请信息更新失败");
			Db::commit();
			return app_show(0,"开票信息更新成功");
		}catch (Exception $e){
			Db::rollback();
			return error_show(1005,$e->getMessage());
		}

    }
    //红票申请开票

    public function returnList(){
         $page=isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']) :1;
        $size=isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']) :15;
        $condition=[["b.is_del","=",0]];
         $roleid = $this->roleid;
        $check = checkRole($roleid,'89');
        if($check){
        	$condition[]=["a.apply_id","=",$this->uid];
        }
        $start = isset($this->post['start'])&&$this->post['start']!="" ? trim($this->post['start']) :"";
        $end = isset($this->post['end'])&&$this->post['end']!="" ? trim($this->post['end']) :"";
        $companyNo = isset($this->post['companyNo'])&&$this->post['companyNo']!="" ? trim($this->post['companyNo']) :"";
        if($companyNo!=""){
            $condition[]=["b.inv_out","=",$companyNo];
        }
        $relaComNo= isset($post['relaComNo'])&&$post['relaComNo']!="" ? trim($post['relaComNo']) :"";
         if($relaComNo!=""){
            $condition[]=["b.inv_out","=",$relaComNo];
        }
        if($start!=""){
            $condition[]=["a.addtime",">=",$start." 00:00:00"];
        }
        if($end!=""){
            $condition[]=["a.addtime","<=",$end." 23:59:59"];
        }
         $inv_type = isset($this->post['inv_type'])&&$this->post['inv_type']!=="" ? trim($this->post['inv_type']):"";
        if($inv_type!==""){
           $condition[]=["b.inv_type","=",$inv_type];
        }
         $apply_id = isset($this->post['apply_id'])&&$this->post['apply_id']!=="" ? intval($this->post['apply_id']):"";
        if($apply_id!==""){
           $condition[]=["a.apply_id","=",$apply_id];
        }
        $apply_name = isset($this->post['apply_name'])&&$this->post['apply_name']!==""?trim($this->post['apply_name']) :"";
        if($apply_name!==""){
           $condition[]=["a.apply_name","like","%$apply_name%"];
        }
          $status= isset($this->post['status'])&&$this->post['status']!=="" ? intval($this->post['status']):"";
        if($status!==""){
          $condition[]=["a.status","=",$status];
        }
         $invNo = isset($this->post['invNo'])&&$this->post['invNo']!=="" ? trim($this->post['invNo']):"";
        if($invNo!==""){
           $condition[]=["a.invNo","like","%$invNo%"];
        }
         $returnCode = isset($this->post['returnCode'])&&$this->post['returnCode']!=="" ? trim($this->post['returnCode']):"";
        if($returnCode!==""){
           $condition[]=["a.returnCode","like","%$returnCode%"];
        }
         $count=Db::name("invoice_return")->alias("a")
         ->leftJoin("invoice_pool b","a.invNo=b.invNo")
         ->leftJoin("invoice_pool_info c","a.invNo=c.invNo")
         ->where($condition)->count();
        $total =ceil($count/$size);
        $page= $page>$total ? intval($total):$page;
        $list=Db::name("invoice_return")->alias("a")
         ->leftJoin("invoice_pool b","a.invNo=b.invNo")
         ->leftJoin("invoice_pool_info c","a.invNo=c.invNo")
        ->where($condition)->page($page,$size)->field("a.*,c.buyer_title,c.buyer_code,c.buyer_addr,c.buyer_mobile,c.buyer_bank,c.buyer_bankNo,c.seller_title,c.seller_code,c.seller_addr,c.seller_mobile,c.seller_bank,c.seller_bankNo,c.voider,c.payee,c.drawer,c.reviewer,c.ownerPlace,b.inv_value,b.inv_out,b.inv_type,b.open_type,is_ticket,b.email,b.winv_fee,b.ainv_fee,b.post_fee,b.post_company,b.post_code")->order("id desc")->select()->toArray();
        foreach ($list as &$value){
          $company =Db::name("company_info")->where(["companyNo"=>$value['inv_out']])->find();
          $value['companyName'] = $company['company_name']??"";
          if(!in_array($value['status'],[2,3,4,5])){
				$opendate =Db::name("invoice_ticket")->where(["invNo"=>$value['invNo'],"is_del"=>0,"type"=>0])->value("open_date","");
				if($opendate!=''){
					$open_month =date("Y-m",strtotime($opendate));
					$value['is_out_month']= $open_month==date("Y-m")?0:1;
				}

          }
        }
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
		//红冲申请
    public function applyRed(){
    	$invNo = isset($this->post['invNo'])&&$this->post['invNo']!=''?trim($this->post['invNo']):"";
    	if($invNo=='')return error_show(1004,"参数 invNo 不能为空");
    	$invfo =Db::name("invoice_pool")->where(["invNo"=>$invNo,"is_del"=>0])->find();
		if($invfo==false) return error_show(1004,"发票数据未找到");
		if(!in_array($invfo['status'],[1,2,3,4,5,8]))return error_show(1004,"发票数据状态无法申请");
		$ticket =Db::name("invoice_ticket")->where(["invNo"=>$invNo])->findOrEmpty();
		if(empty($ticket)) return error_show(1004,"未找到开票信息");
		$company =Db::name("company_info")->where(["companyNo"=>'GS2207150956046617'])->findOrEmpty();
		if(empty($company)) return error_show(1004,"业务企业信息未找到");
		$invoice=Config::get("invoice");
		$Tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
		$redticketList=[];
		$redticketArry=[
			"SQBSCQQPCH"=>randomkeys(26).date("YmdHis"),
			"NSRSBH"=>$company['company_license'],
			"FPLXDM"=>$this->kingInvoice[$invfo['inv_type']],
		];
		$goodinfo =Db::name("invoice_good")
            		->where(["invNo"=>$invNo,"is_del"=>0])
            		->field("0 as FPHXZ, 
									catNo  as SPBM,
									id as ZXBM,
									is_discount as YHZCBS,
									if(inv_tag=0,'',inv_tag) as  LSLBS,
									addTax	as ZZSTSGL,
									goodName as XMMC,
									'' as DW,
									'' as SPSL,
									'' as DJ,
									(-totalPrice) as JE,
									0 HSBZ,
									tax as SL,
									-taxPrice as SE")->select()->toArray();
					if(empty($goodinfo)){
						Db::rollback();
	                    return error_show(1004,"开票商品信息未找到");
					}
		if(count($goodinfo)>8){
			$len =array_unique(array_column($goodinfo,'SL'));
	    $qdmx=["FPHXZ"=>6,
		    "SPBM"=>'',
		    "XMMC"=>"详见对应正数发票及清单",
		    "YHZCBS"=>0,
		    "LSLBS"=>'',
		    "ZZSTSGL"=>'',
		    "DW"=>'',
		    "SPSL"=>'',
		    "DJ"=>'',
		    "JE"=>sprintf("%01.2f", (array_sum(array_column($goodinfo,'JE')))),
		    "HSBZ"=>'0',
		    "SL"=>count($len)>1?'':$len[0],
		    "SE"=>sprintf("%01.2f",array_sum(array_column($goodinfo,'SE'))),
	        ];
		}else
			{
				$qdmx=$goodinfo;
			}

		$info=[
			"SQBSCQQLSH"=>randomkeys(26).date("YmdHis"),
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",//0: 正常;1:成品油发票,涉及销售数量 变更(销货退回、开票有误等原因);2: 成品油发票,仅涉及销售金额变更(销 售折让);3:机动车发票,仅涉及销售数
//量变更(销货退回、开票有误等原因);4: 机动车发票,仅涉及销售金额变更(销 售折让)
		];
		$invRed=makeNo("IRE");
		$data=[
			'invNo'=>$invNo,
			"invRed"=>$invRed,
			"inv_out"=>$invfo['inv_out']??"",
			"apply_id"=>$this->uid,
			"apply_name"=>$this->uname,
			"status"=>0,
			"remark"=>'',
			"addtime"=>date("Y-m-d H:i:s"),
			"updatetime"=>date("Y-m-d H:i:s"),
			"SQBSCQQLSH"=>$info['SQBSCQQLSH'],
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",
			 "DDMXXX"=>json_encode($qdmx,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>$redticketArry['SQBSCQQPCH'],
			 "FPLXDM"=>$this->kingInvoice[$invfo['inv_type']],
		];
	    $redticketList[]=["HZSQDTXX"=>$info,"DDMXXX"=>$qdmx];
		$result=$Tax->AllocateRedInvoiceApplication($redticketArry,$redticketList);
		$data['status']=5;
		$data['remark']='红冲申请提交失败';
		if(isset($result['ZTDM']) && $result['ZTDM']=='060000'){
			$resultChild=$result['HZSQDSCJG'][0];
			if($resultChild['ZTDM']=='060000'){
				$data['status']=2;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='红冲申请审核通过';
			}
			if($resultChild['ZTDM']=='060001'){
				$data['status']=1;
				$data['XXBBH']=$resultChild['XXBBH'];
				$data['remark']='红冲申请审核中';
			}
		}
		if($data['status']==5){
			return error_show(1004,"红冲发票申请新建失败");
		}
		$up =Db::name("invoice_red")->insert($data);
		return $up ? app_show(0,"红冲发票申请新建成功",["invRed"=>$invRed]):error_show(1004,"红冲发票申请新建失败");
    }

	//批量申请红冲发票
    public function batchApplyRed(){
        $invArr = isset($this->post['invArr'])&&!empty($this->post['invArr'])?$this->post['invArr']:[];
    	if(empty($invArr))return error_show(1004,"参数 invArr 不能为空");
		$invfo =Db::name("invoice_pool")->where(["invNo"=>$invArr,"is_del"=>0])->select()->toArray();
		if(empty($invfo)) return error_show(1004,"发票数据未找到");
		$insertAll=[];
		$companyCode = array_unique(array_column($invfo,"inv_out"));
		$inv_type = array_unique(array_column($invfo,"inv_type"));
		if(count($companyCode)>1){
			return error_show(1004,"业务企业公司不统一");
		}
		if(count($inv_type)>1){
			return error_show(1004,"发票类型不统一");
		}
		$company =Db::name("company_info")->where(["companyNo"=>$companyCode])->findOrEmpty();
		if(empty($company)) {
			return error_show(1004,"业务企业信息未找到");
		}
		$ticketArr=Db::name("invoice_ticket")->where(["invNo"=>$invArr,"is_del"=>0])->column("*","invNo");
		if(empty($ticketArr)){
		 return error_show(1004,"未找到开票信息");
		}
		$invoice=Config::get("invoice");
		$Tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
		Db::startTrans();
		try{
			$redticketArry=[
					"SQBSCQQPCH"=>randomkeys(26).date("YmdHis"),
					"NSRSBH"=>$company['company_license'],
					"FPLXDM"=>$this->kingInvoice[$inv_type[0]],
				];
			$redticketList=[];
			foreach ($invfo as $value){
					if(!in_array($value['status'],[1,2,3,4,5,8])){
						Db::rollback();
						return error_show(1004,"发票数据状态无法申请");
					}
					$ticket =$ticketArr[$value['invNo']] ??[];
					if(empty($ticket)){
						Db::rollback();
						return error_show(1004,"未找到开票信息");
					}
					$goodinfo =Db::name("invoice_good")
            		->where(["invNo"=>$value['invNo'],"is_del"=>0])
            		->field("  6 as FPHXZ, 
									catNo  as SPBM,
									id as ZXBM,
									is_discount as YHZCBS,
									if(inv_tag=0,'',inv_tag) as  LSLBS,
									addTax	as ZZSTSGL,
									goodName as XMMC,
									'' as DW,
									'' as SPSL,
									'' as DJ,
									(-totalPrice) as JE,
									0 HSBZ,
									tax as SL,
									-taxPrice as SE")
									->select()->toArray();
					if(empty($goodinfo)){
						Db::rollback();
	                    return error_show(1004,"开票商品信息未找到");
					}
					$len =array_unique(array_column($goodinfo,'SL'));
			$qdmx=["FPHXZ"=>6,
					"SPBM"=>'',
					"XMMC"=>"详见对应正数发票及清单",
					"YHZCBS"=>0,
					"LSLBS"=>'',
					"ZZSTSGL"=>'',
					"DW"=>'',
					"SPSL"=>'',
					"DJ"=>'',
					"JE"=>sprintf("%01.2f", (array_sum(array_column($goodinfo,'JE')))),
					"HSBZ"=>'0',
					"SL"=>count($len)>1?'':$len[0],
					"SE"=>sprintf("%01.2f",array_sum(array_column($goodinfo,'SE'))),
					];


			$info=[
			"SQBSCQQLSH"=>randomkeys(26).date("YmdHis"),
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",//0: 正常;1:成品油发票,涉及销售数量 变更(销货退回、开票有误等原因);2: 成品油发票,仅涉及销售金额变更(销 售折让);3:机动车发票,仅涉及销售数
//量变更(销货退回、开票有误等原因);4: 机动车发票,仅涉及销售金额变更(销 售折让)
		];
		$redticketList[]=["HZSQDTXX"=>$info,"DDMXXX"=>$qdmx];
		$data=[
			'invNo'=>$value['invNo'],
			"invRed"=>makeNo("IRE"),
			"inv_out"=>$value['inv_out']??"",
			"apply_id"=>$this->uid,
			"apply_name"=>$this->uname,
			"status"=>5,
			"remark"=>'红冲申请提交失败',
			"addtime"=>date("Y-m-d H:i:s"),
			"updatetime"=>date("Y-m-d H:i:s"),
			"SQBSCQQLSH"=>$info['SQBSCQQLSH'],
			"YYSBZ"=> "0000000000", //营业税标志
			"XXBLX"=> "0",//信息表类型 0 正常;1 逾期(仅销方开具)
			"YFPDM"=>$ticket['inv_code'], //红字专票购方已抵扣可不填
			"YFPHM"=> $ticket['inv_number'],//红字专票购方已抵扣可不填
			"YFPKPRQ"=>$ticket['open_date'], //红字专票购方已抵扣可不填
			"TKSJ"=>date("YmdHis"), //填开时间
			"XHFSBH"=>$ticket['seller_id'],
			"XHFMC"=>$ticket['seller_title'],
			"GMFSBH"=>$ticket['buyer_id'],
			 "GMFMC"=> $ticket['buyer_title'],
			 "HJJE"=> "-".$ticket['inv_subtotal'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",
			 "DDMXXX"=>json_encode($qdmx,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>$redticketArry['SQBSCQQPCH'],
			  "FPLXDM"=>$this->kingInvoice[$value['inv_type']],
		];
		$insertAll[$info['SQBSCQQLSH']]=$data;
		}
		$result=$Tax->AllocateRedInvoiceApplication($redticketArry,$redticketList);
			if(isset($result['ZTDM']) && $result['ZTDM']=='060000'){
				if(isset($result['HZSQDSCJG']) && count($result['HZSQDSCJG'])>0){
					foreach ($result['HZSQDSCJG'] as $value){
						if($value['ZTDM']=='060000'){
							$insertAll[$value['SQBSCQQLSH']]['status']=2;
							$insertAll[$value['SQBSCQQLSH']]['remark']="红冲申请审核通过";
							$insertAll[$value['SQBSCQQLSH']]['XXBBH']=$value['XXBBH'];
							continue;
//							$data['status']=2;
//							$data['remark']='红冲申请审核通过';
						}
						if($value['ZTDM']=='060001'){
							$insertAll[$value['SQBSCQQLSH']]['status']=1;
							$insertAll[$value['SQBSCQQLSH']]['remark']="红冲申请审核中";
							$insertAll[$value['SQBSCQQLSH']]['XXBBH']=$value['XXBBH'];
							continue;
						}
						unset($insertAll[$value['SQBSCQQLSH']]);
					}
				}
			}else{
			Db::rollback();
			return error_show(1004,"红冲发票申请失败");
			}
			$uns= Db::name("invoice_red")->insertAll($insertAll);
			if($uns){
				Db::commit();
				return app_show(0,"红冲发票申请新建成功,成功数量{$uns}个");
			}
			Db::rollback();
			return error_show(1004,"红冲发票申请新建失败");
		}catch (\Exception $e){
			Db::rollback();
			return error_show(1004,$e->getMessage());
		}

    }
    //红票申请开票
    public function redOpen(){
		$invRed= isset($this->post['invRed'])&&$this->post['invRed']!=''? $this->post['invRed']:"";
		if($invRed==''){
			return error_show(1004,"参数 invRed 不能为空");
		}
		$redinfo =Db::name("invoice_red")->where(["invRed"=>$invRed,"is_del"=>0])->findOrEmpty();
		if(empty($redinfo)){
			return error_show(1004,"红冲发票申请不存在");
		}
		$redreason = isset($this->post['redreason'])&&$this->post['redreason']!=''? $this->post['redreason']:"";
		if($redreason==''){
			return error_show(1004,"参数 redreason 不能为空");
		}
		if($redinfo['status']!=2){
				return error_show(1004,"数据状态不可提交申请");
		}
		$invinfo = Db::name("invoice_pool")->where(["invNo"=>$redinfo['invNo'],"is_del"=>0])->findOrEmpty();
		if(empty($invinfo)) return error_show(1004,"红冲发票原票信息未找到");
		$invpoolinfo = Db::name("invoice_ticket")->where(["invNo"=>$redinfo['invNo'],"status"=>1,"is_del"=>0])->findOrEmpty();
		if(empty($invpoolinfo)) return error_show(1004,"红冲发票开票信息未找到");
		Db::startTrans();
		try{
		$data=[
							"invNo"=>$invRed,
							"KPLX"=>"1",
							"XHFSBH"=>$invpoolinfo['seller_id'],
							"XHFMC"=>$invpoolinfo['seller_title'],
							"XHFDZ"=>$invpoolinfo['seller_addr'],
							"XHFDH"=>$invpoolinfo['seller_mobile'],
							"XHFYH"=>$invpoolinfo['seller_bank'],
							"XHFZH"=>$invpoolinfo['seller_bankNo'],
							"GMFBM"=>"",
							"GMFSBH"=>$invpoolinfo['buyer_id'],
							"GMFMC"=>$invpoolinfo['buyer_title'],
							"GMFDZ"=>$invpoolinfo['buyer_addr'],
							"GMFDH"=>$invpoolinfo['buyer_mobile'],
							"GMFYH"=>$invpoolinfo['buyer_bank'],
							"GMFZH"=>$invpoolinfo['buyer_bankNo'],
							"GMFLX"=>$invinfo['company_type'],
							"GMFSJH"=>"",
							"GMFDZYX"=>$invinfo['email'],
							"KPR"=>$invpoolinfo['issuer'],
							"SKR"=>$invpoolinfo['reciver'],
							"FHR"=>$invpoolinfo['reviewer'],
							"QDBZ"=>"0",
							"YFPDM"=>$redinfo['YFPDM'],
							"YFPHM"=>$redinfo['YFPHM'],
							"YFPLX"=>$invpoolinfo['inv_type'] == '004' || $invpoolinfo['inv_type'] =='028'||$redreason=='' ?'':$invpoolinfo['inv_type'],
							"YFPKPRQ"=>$invpoolinfo['inv_type'] == '004' || $invpoolinfo['inv_type'] == '028'||$redreason=='' ? '':date("Y-m-d",strtotime($redinfo['YFPKPRQ'])),
							"CHYY"=>$invpoolinfo['inv_type'] == '004' || $invpoolinfo['inv_type'] == '028' ? '':$redreason,
							"TSCHBZ"=>"0",
							"JSHJ"=>"-".$invpoolinfo['inv_total'],
							"HJJE"=>"-".$invpoolinfo['inv_subtotal'],
							"HJSE"=>"-".$invpoolinfo['tax_fee'],
							"BZ"=>  $invpoolinfo['inv_type'] == '004' || $invpoolinfo['inv_type'] =='028'?"开具红字增值税专用发票信息表编号{$redinfo['XXBBH']}":"对应正数发票代码:{$redinfo['YFPDM']} 号码:{$redinfo['YFPHM']}",
							"DDMXXX"=>$redinfo['DDMXXX'],
							"FPLXDM"=>$redinfo['FPLXDM'],
							"DDQQPCH"=>"",
							"DDQQLSH"=>randomkeys(26).date("YmdHis"),
							"status"=>"0",
							"result"=>"",
							"addtime"=>date("Y-m-d H:i:s"),
							"updatetime"=>date("Y-m-d H:i:s")
						];
		$invoice=Db::name("invoice_interface")->insert($data);
		if($invoice==false){
			Db::rollback();
            return error_show(1003,"红冲开票信息生成失败");
		}
		$upred=Db::name("invoice_red")->where(["invRed"=>$invRed])->update(["status"=>3,"red_reason"=>$redreason,"updatetime"=>date("Y-m-d H:i:s")]);
		if($upred==false){
			Db::rollback();
            return error_show(1003,"红冲发票信息更新失败");
		}
		Db::commit();
		return app_show(0,"红冲发票信息开票提交成功");
		}catch (\Exception $e){
			Db::rollback();
            return error_show(1003,$e->getMessage());
		}
    }
	//红冲票申请列表
    public function redList(){
    	$page=isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']) :1;
        $size=isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']) :15;
        $condition=[["is_del","=",0],["FPLXDM","in",["004",'028']]];
          $roleid = $this->roleid;
        $check = checkRole($roleid,'110');
        if($check){
        	$condition[]=["apply_id","=",$this->uid];
        }
        $invRed=isset($this->post["invRed"])&&$this->post["invRed"]!=''?trim($this->post["invRed"]):"";
        if($invRed!=''){
        	$condition[]=["invRed","like","%$invRed%"];
        }
         $apply_id=isset($this->post["apply_id"])&&$this->post["apply_id"]!=''?intval($this->post["apply_id"]):"";
        if($apply_id!=''){
        	$condition[]=["apply_id","=",$apply_id];
        }
         $invNo=isset($this->post["invNo"])&&$this->post["invNo"]!=''?trim($this->post["invNo"]):"";
        if($invNo!=''){
        	$condition[]=["invNo","like","%$invNo%"];
        }

          $companyNo=isset($this->post["companyNo"])&&$this->post["companyNo"]!=''?trim($this->post["companyNo"]):"";
        if($companyNo!=''){
        	$condition[]=["inv_out","=",$companyNo];
        }
         $relaComNo= isset($post['relaComNo'])&&$post['relaComNo']!="" ? trim($post['relaComNo']) :"";
         if($relaComNo!=""){
            $condition[]=["inv_out","=",$relaComNo];
        }
         $apply_name=isset($this->post["apply_name"])&&$this->post["apply_name"]!=''?trim($this->post["apply_name"]):"";
        if($apply_name!=''){
        	$condition[]=["apply_name","like","%$apply_name%"];
        }
        $start = isset($this->post["start"])&&$this->post["start"]!=''?trim($this->post["start"]):"";
        $end = isset($this->post["end"])&&$this->post["end"]!=''?trim($this->post["end"]):"";
        if($start!=''){
        	$condition[]=["addtime",">=",$start];
        }
        if($end!=''){
        	$condition[]=["addtime","<=",$end];
        }
        $total_low=isset($this->post["total_low"])&&$this->post["total_low"]!=''?floatval($this->post["total_low"]):"";
        $total_up=isset($this->post["total_up"])&&$this->post["total_up"]!=''?floatval($this->post["total_up"]):"";
         if($total_low!=''){
        	$condition[]=["ABS(HJJE)",">=",$total_low];
        }
        if($total_up!=''){
        	$condition[]=["ABS(HJJE)","<=",$total_up];
        }

        $count= Db::name("invoice_red")->where($condition)->count();
        $total =ceil($count/$size);
        $page=$total>=$page?$page :intval($total);
        $list =Db::name("invoice_red")->where($condition)->json(["DDMXXX"])->page($page,$size)->order("addtime desc")->select()
        ->toArray();
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
	/**
	* @return \think\response\Json|void
	 */
    public function ticketInfo(){
       	$num =isset($this->post['number'])&&$this->post['number']!=''?trim($this->post['number']):"";
		if($num==''){
			return error_show(1004,'参数 number 不能为空');
		}
		$condition=[["status","in",[0,1,2]]];
		$condition[]=["inv_number","=",$num];
		$invNo = isset($this->post['invNo'])&&$this->post['invNo']!=''?trim($this->post['invNo']):"";
		if($invNo!=='')$condition[]=["invNo","=",$invNo];
		$info =Db::name("invoice_ticket")->json(['item'])->withoutField("pdfstream")->where($condition)->findOrEmpty();
		if(!empty($info)&& isset($info['item'])){
			array_walk($info['item'],function (&$value){
					if(stripos($value["SL"],"%")==false)$value['SL'] =  ($value['SL']*100)."%";
			});
		}
		$info['invtype_name'] = $this->typename[$info['inv_type']]??"";
		return empty($info)?error_show(1005,"未找到数据"):app_show(0,"获取成功",$info);
    }


	//退票列表
    public function returnRedList(){
         $page=isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']) :1;
        $size=isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']) :15;
        $condition=[];
        $start = isset($this->post['start'])&&$this->post['start']!="" ? trim($this->post['start']) :"";
        $end = isset($this->post['end'])&&$this->post['end']!="" ? trim($this->post['end']) :"";
        if($start!=""){
            $condition[]=["a.addtime",">=",$start." 00:00:00"];
        }
        if($end!=""){
            $condition[]=["a.addtime","<=",$end." 23:59:59"];
        }
         $inv_type = isset($this->post['inv_type'])&&$this->post['inv_type']!=="" ? trim($this->post['inv_type']):"";
        if($inv_type!==""){
           $condition[]=["c.inv_type","=",$inv_type];
        }
         $companyNo = isset($this->post['companyNo'])&&$this->post['companyNo']!=="" ? trim($this->post['companyNo']):"";
        if($companyNo!==""){
           $condition[]=["c.inv_out","=",$companyNo];
        }
         $relaComNo= isset($post['relaComNo'])&&$post['relaComNo']!="" ? trim($post['relaComNo']) :"";
         if($relaComNo!=""){
            $condition[]=["c.inv_out","=",$relaComNo];
        }
         $apply_id = isset($this->post['apply_id'])&&$this->post['apply_id']!=="" ? intval($this->post['apply_id']):"";
        if($apply_id!==""){
           $condition[]=["a.apply_id","=",$apply_id];
        }
        $apply_name = isset($this->post['apply_name'])&&$this->post['apply_name']!==""?trim($this->post['apply_name']) :"";
        if($apply_name!==""){
           $condition[]=["a.apply_name","like","%$apply_name%"];
        }
          $status= isset($this->post['status'])&&$this->post['status']!=="" ? intval($this->post['status']):"";
        if($status!==""){
          $condition[]=["a.status","=",$status];
        }
         $invNo = isset($this->post['invNo'])&&$this->post['invNo']!=="" ? trim($this->post['invNo']):"";
        if($invNo!==""){
           $condition[]=["a.invNo","like","%$invNo%"];
        }
         $returnCode = isset($this->post['returnCode'])&&$this->post['returnCode']!=="" ? trim($this->post['returnCode']):"";
        if($returnCode!==""){
           $condition[]=["a.returnCode","like","%$returnCode%"];
        }
         $count=Db::name("invoice_return")->alias("a")
         ->leftJoin("invoice_ticket b","a.invNo=b.invNo and b.type=1")
         ->leftJoin("invoice_pool c","a.invNo=c.invNo")
         ->where($condition)->count();
        $total =ceil($count/$size);
        $page= $page>$total ? intval($total):$page;
        $list=Db::name("invoice_return")->alias("a")
         ->leftJoin("invoice_ticket b","a.invNo=b.invNo and b.type=1")
          ->leftJoin("invoice_pool c","a.invNo=c.invNo")
          ->field("b.*,a.*")->withoutField("pdfstream")->json(["item"])->page($page,$size)->where($condition)->select()
        ->toArray();
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }

	/**
	* @return \think\response\Json|void
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	*/
    public function tikcetList(){
    	$post=$this->request->only(["invNo"=>"","companyNo"=>"","relaComNo"=>"","page"=>1,"size"=>15],"post","trim");
    	$where=[];
    	 $roleid = $this->roleid;
        $check = checkRole($roleid,'88');
        if($check){
        	$where[]=["b.apply_id","=",$this->uid];
        }
    	if($post["invNo"]!="") $where[]=["a.invNo","=",$post['invNo']];
    	if($post["companyNo"]!="") $where[]=["b.inv_out","=",$post['companyNo']];
    	if($post["relaComNo"]!="") $where[]=["b.inv_out","=",$post['relaComNo']];

    	 $count=Db::name("invoice_ticket")->where($where)->count();
    	 $total =ceil($count/$post['size']);
    	 $page= $post['page']>$total ? intval($total):intval($post['page']);
    	 $list = Db::name("invoice_ticket")
    	 ->alias("a")
    	 ->leftJoin("invoice_pool b","a.invNo=b.invNo")
    	 ->where($where)
    	 ->field("a.*")
    	 ->json(["a.item"])
    	 ->page($page,intval($post['size']))
    	 ->order("a.id desc")
    	 ->select()->toArray();
    	  foreach ($list as &$value){
    	 	    $value['invtype_name'] = $this->typename[$value['inv_type']]??"";
    	 }
    	 return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
	/** @param array invNo  发票编号集合
	* @return \think\response\Json|void
	*/
    public function downorder(){
    	$post=$this->request->only(["invNo"=>[]],"post","trim");
    	 $condition=[["open_type","in",[0,2,3]],["is_del","=",0],["status","=",1]];
        if(!empty($post['invNo'])){
            $condition[]=['invNo',"in",$post['invNo']];
        }
      $invice = Db::name("invoice_pool")->where($condition)->select()->toArray();
        if (empty($invice)){
            return error_show(1003,"未找到数据");
        }
      $data=[];
      foreach ($invice as $value){
          $temp=[];
         $orderNo = Db::name("assoc")->where([["status","=",1],["is_del","=",0],['viceCode',"=",$value['invNo']]])
         ->find();
         if(!$orderNo){
             continue;
         }

         $good = Db::name("qrd_info")->where([['sequenceNo',"=",$orderNo['orderCode']],["status","=",1]])
         ->findOrEmpty();
        if(empty($good)){
           continue;
        }
        if(isset($value['inv_out'])&& $value['inv_out']!=''){
            $invout = Db::name("company_info")->where([['companyNo',"=",$value['inv_out']]])->find();
        }
        $invinfo = Db::name("invoice_pool_info")->where("invNo","=",$value['invNo'])->findOrEmpty();

//       foreach ($good as $val){
//         $qrd = Db::name("qrd_list")->where("sequenceNo","=",$val['goodNo'])->find();
         $temp['invNo'] = $value['invNo'];
         $temp['qrdNo'] = $orderNo['orderCode'];
         $temp['depart'] = $good['department'];
         $temp['apply_name'] =$value['apply_name'];
         $temp['code'] ="";
         $temp['invoice_title'] =$invinfo['buyer_title']??"";
         $temp['invoice_code'] =$invinfo['buyer_code']." ";
         $temp['invoice_addr'] =$invinfo['buyer_addr']??"";
         $temp['invoice_mobile'] =$invinfo['buyer_mobile']??"";
         $temp['invoice_bank'] =$invinfo['buyer_bank']??"";
         $temp['invoice_bankNo'] =$invinfo['buyer_bankNo']." ";
         $temp['company'] =$good['customerName'];
         $temp['goodname'] =$good['goodName'];
         $temp['tax'] =$good['tax'];
         $temp['inv_name'] =$good['goodName'];
         $temp['diff_weight'] =$good['diff_weight'];
         $temp['diff_price'] =$good['diff_fee'];
           $temp['unit'] =$good['goodUnit'];
           $temp['num'] =$good['goodNum'] - $good['thNum'];
           $temp['price'] =$good['goodPrice'];
           $temp['total_fee'] =$good['totalPrice'];
           $temp['inv_type']=$this->invoiceType[$value['inv_type']]?? "-";
            $temp['remark'] =$value['remark'];
           $temp['kp_companyName'] = $invinfo['seller_title']??"";
           $temp['kp_company_address'] = $invinfo['seller_addr']??"";
           $temp['kp_company_license'] = $invinfo['seller_code']." ";
           $temp['kp_bank_name'] = $invinfo['seller_bank']??"";
           $temp['kp_bankNo'] = $invinfo['seller_bankNo']."";
           $temp['kp_contector'] = $invout['contector']??"";
           $temp['kp_mobile'] = $invinfo['seller_mobile']??"";
         $data[]=$temp;
       }
//      }
      if (empty($data)){
          return error_show(1003,"未找到数据");
      }
      $header=[
          "申请编号",
          "公司订单号",
          "申请部门(所属平台)",
          "申请人",
          "代码",
          "发票开具全称",
          "发票开具企业纳税识别号",
          "发票开具企业地址",
          "发票开具企业地址联系方式",
          "发票开具企业收款银行",
          "发票开具企业收款账户",
          "分公司",
          "采购商品名",
          "税率",
          "发票商品名",
          "工差重量",
          "工差金额",
          "单位",
          "数量",
          "单价",
          "总价",
          "开票种类",
          "备注说明",
          '开票企业名称',
          '开票企业地址',
          '开票企业纳税号',
          '开票企业银行名称',
          '开票企业银行账户',
          '开票企业法人',
          '开票企业联系方式'
      ];
       $li = excelExport("待开票",$header,$data);
    }

    public function  importInv(){
		$param =$this->request->only(["data"=>[]],"post");
		if(empty($param['data']))return error_show(1004,"参数 data 不能为空");
		$total=[];
		$list=[];
		 foreach ($param['data'] as $key=>$value){

            if($value['invNo']==""){
                return error_show(1005,"第".($key+1)."行缺少发票申请编号数据");
            }
            if($value["inv_type"]===""){
                return error_show(1005,"第".($key+1)."行缺少发票类型数据");
            }
            if(!in_array($value['inv_type'],$this->invName))  return error_show(1005,"第".($key+1)."行发票类型数据有误");
            if($value["inv_code"]=="" && !in_array($value['inv_type'],[ "fully_digitalized_special_electronic", "fully_digitalized_normal_electronic"])){
                return error_show(1005,"第".($key+1)."行缺少发票代码数据");
            }
            if($value["inv_number"]==""){
                return error_show(1005,"第".($key+1)."行缺少发票号码数据");
            }
            if($value["inv_total"]==""&& in_array($value['inv_type'],["fully_digitalized_special_electronic", "fully_digitalized_normal_electronic"])){
                return error_show(1005,"第".($key+1)."行缺少发票金额数据");
            }
             if($value["inv_subtotal"]==""){
                return error_show(1005,"第".($key+1)."行缺少发票税后金额数据");
            }
            if($value["open_date"]==""){
                return error_show(1005,"第".($key+1)."行缺少发票开票日期数据");
            }
            //电子票校验码必传
            if($value["check_code"]=="" && in_array($value['inv_type'],['normal','roll',"toll",'electronic'])){
                return error_show(1005,"第".($key+1)."行缺少发票校验码数据");
            }
//            if($value['inv_type']==="000"){
//            	if($value['seller_id']=="") return error_show(1005,"第".($key+1)."行缺少销售方纳税识别号数据");
//            	if($value['seller_title']=="") return error_show(1005,"第".($key+1)."行缺少销售方名称数据");
//            	if($value['seller_addr']=="") return error_show(1005,"第".($key+1)."行缺少销售方地址数据");
//            	if($value['seller_mobile']=="") return error_show(1005,"第".($key+1)."行缺少销售方联系方式数据");
//            	if($value['seller_bank']=="") return error_show(1005,"第".($key+1)."行缺少销售方银行数据");
//            	if($value['seller_bankNo']=="") return error_show(1005,"第".($key+1)."行缺少销售方银行账户数据");
//            	if($value['buyer_id']=="") return error_show(1005,"第".($key+1)."行缺少购买方纳税识别号数据");
//            	if($value['buyer_title']=="") return error_show(1005,"第".($key+1)."行缺少购买方名称数据");
//            	if($value['buyer_addr']=="") return error_show(1005,"第".($key+1)."行缺少购买方地址数据");
//            	if($value['buyer_mobile']=="") return error_show(1005,"第".($key+1)."行缺少购买方联系方式数据");
//            	if($value['buyer_bank']=="") return error_show(1005,"第".($key+1)."行缺少购买方银行数据");
//            	if($value['buyer_bankNo']=="") return error_show(1005,"第".($key+1)."行缺少购买方银行账户数据");
//            	if($value['tax_fee']=="") return error_show(1005,"第".($key+1)."行缺少发票税额数据");
//            }
			!isset($total[$value['invNo']]) ? $total[$value['invNo']]['total']=0:"";

            $temp=[];
            $temp['invNo'] = $value["invNo"];
            $temp['type'] = 0;
            $temp['inv_type'] =$value['inv_type'];
            $temp['inv_code'] = $value['inv_code'];
            $temp['inv_number'] = $value['inv_number'];
            $temp['inv_subtotal'] = $value['inv_subtotal'];
            $temp['inv_total'] = $value['inv_total'];
            $temp['check_code'] = $value['check_code']??"";
            $temp['seller_id'] = $value['seller_id']??"";
            $temp['seller_title'] = $value['seller_title']??"";
            $temp['seller_addr'] = $value['seller_addr']??"";
            $temp['seller_mobile'] = $value['seller_mobile']??"";
            $temp['seller_bank'] = $value['seller_bank']??"";
            $temp['seller_bankNo'] = $value['seller_bankNo']??"";
            $temp['buyer_id'] = $value['buyer_id']??"";
            $temp['buyer_title'] = $value['buyer_title']??"";
            $temp['buyer_addr'] = $value['buyer_addr']??"";
            $temp['buyer_mobile'] = $value['buyer_mobile']??"";
            $temp['buyer_bank'] = $value['buyer_bank']??"";
            $temp['buyer_bankNo'] = $value['buyer_bankNo']??"";
            $temp['tax_fee'] = $value['tax_fee']??"";
            $temp['item'] = '';
            $temp['pdfstream'] = '';
            $temp['open_date'] =  date("Y-m-d H:i:s",strtotime($value['open_date']));
            $temp['status'] = 0;
            $temp['is_del'] = 0;
            $temp['addtime'] = date("Y-m-d H:i:s");
            $temp['updatetime'] = date("Y-m-d H:i:s");
            $total[$value["invNo"]]=$temp;
        }

		 Db::startTrans();
		 try{
		 	$keyarr =array_keys($total);
		 	$inpool = Db::name("invoice_pool")->where([["invNo","in",$keyarr],["open_type","in",[0,2,3]],["is_del","=",0],["status","=",2]])->column("winv_fee,invNo,inv_value,inv_type","invNo");

		 	foreach ($total as $key=>$val){
				if(!isset($inpool[$key])) throw new Exception("{$key}发票数据不存在或状态有误");
				if(in_array($val['inv_type'],["fully_digitalized_special_electronic", "fully_digitalized_normal_electronic"]) && $inpool[$key]['winv_fee']!=$val['total']){
					throw new Exception("{$key}全电发票面金额小于未开票金额");
				}
				if($inpool[$key]['inv_type']!= $val['inv_type']) throw new Exception("{$key}发票类型有误");
				$update=[
					"status"=>in_array($val['inv_type'],["fully_digitalized_special_electronic", "fully_digitalized_normal_electronic"])?4:3,
					"open_type"=>$inpool[$key]['open_type']??3,
					"updatetime"=>date("Y-m-d H:i:s")
				];
				 $up =Db::name("invoice_pool")->where([["invNo","=",$key],["is_del","=",0]])->save($update);
                if(!$up){
                    Db::rollback();
                    return error_show(1005,"发票状态更新失败");
                }

               if($update['status']==4){
            	$qrdArr=Db::name("assoc")->where(["viceCode"=>$key,"is_del"=>0])->column("id,orderCode,cancel_fee");
                 if(!empty($qrdArr)){
                      foreach ($qrdArr as $value){
                          $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                          if($qrdinfo==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息未找到");
                          }
                          if($qrdinfo['inv_fee']<$value['cancel_fee']){
                               Db::rollback();
                              return error_show(1003,"确认单信息开票金额不足");
                          }
                          $update =[
                              "ainv_fee"=>$qrdinfo['ainv_fee']+$value['cancel_fee'],
                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
                              "invtime"=>date("Y-m-d H:i:s"),
                              "inv_status"=>$qrdinfo['winv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 3 : 2,
                              "updatetime"=>date("Y-m-d H:i:s"),
                          ];
                          $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                          if($qrdup==false){
                              Db::rollback();
                              return error_show(1003,"确认单信息更新失败");
                          }
                          $assoc=["status"=>2,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
                          $assocup =Db::name("assoc")->where($value)->update($assoc);
                          if($assocup==false){
                              Db::rollback();
                              return error_show(1003,"确认单关联信息更新失败");
                          }
                      }
                 }
                }
                $val['inv_type'] = $this->kingInvoice[$val['inv_type']];
               $list[]=$val;
		 	}

		 	     $inticket =Db::name("invoice_ticket")->insertAll($list);
			     if(!$inticket){
	                Db::rollback();
	                return error_show(1005,"发票数据录入失败");
	            }
                Db::commit();
                return app_show(0,"发票数据录入成功");

		 }catch (\Exception $e){
		 	Db::rollback();
		 	return error_show(1008,$e->getMessage());
		 }

    }
}