<?php


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

class OrderInv extends BaseController{
    public function __construct(App $app) {
        parent::__construct($app);
    }
    /**
     * 新建销售单开票申请
     */
   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,"购买方发票信息未找到");
           }


        $companyNo = isset($this->post['companyNo'])&&$this->post['companyNo']!=='' ? trim($this->post['companyNo']):"";
       if($companyNo==''){
           return error_show(1004,"参数 companyNo 不能为空");
       }
        $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 不能为空");
//       }
//       $customer = Db::name("customer_info")->where(["companyNo"=>$khNo])->find();
//       if($customer==false){
//           return error_show(1004,"客户信息未找到");
//       }
       $invtype = isset($this->post['invtype'])&&$this->post['invtype']!=='' ? intval($this->post['invtype']):"";
        if($invtype==''){
           return error_show(1004,"参数 invtype 不能为空");
       }
        $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'));
        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']}待开票金额不足");
                    }
                    $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")
					->where(["a.status"=>[1,2],"a.is_del"=>0,"a.type"=>1])->sum("b.goodNum");
                    if($qrd['goodNum']-$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'],
                        "catName"=>$good_info['inv_cat_name'],
                        "catNo"=>$good_info['inv_cat_code'],
                        "goodPrice"=>round($value['inv_fee']/$value['num'],8),
                        "unitName"=>$qrd['goodUnit'],
                        "goodNum"=>$value['num'],
                        "specInfo"=>'',
                        "totalPrice"=>$value['inv_fee'],
                        "tax"=>$good_info['inv_tax'],
                        "is_discount"=>$good_info['is_discount'],
                        "addTax"=>$good_info['addTax'],
                        "inv_tag"=>$good_info['inv_tag'],
                        "taxPrice"=>round($value['inv_fee']*$good_info['inv_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"=> $company['company_name'],
            "apply_id"=>$this->uid,
            "apply_name"=>$this->uname,
            "inv_type"=>$invtype,//发票类型  专用 普通 电子专用 电子普通
            "open_type"=>0, //开票类型 金税开票 金税线下 纯线下
            "is_ticket"=>$company['out_ticket'], //是否支持金税开票
            "company_type"=> $buyinfo['company_type'], //类型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());
        }
   }
    // 0 待财务开票/待金税开票   1待财务审核 2待填写物流 3开票完成  4开票失败/开票驳回   5财务驳回 6退票 7金税开票中
   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']):"";

//        $invArr=isset($this->post['invArr'])&&!empty($this->post['invArr'])?$this->post['invArr']:[];
        $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']):"";
        $total_fee =isset($this->post['total_fee'])&&$this->post['total_fee']!=''?floor($this->post['total_fee']):"";
        $subtotal_fee =isset($this->post['subtotal_fee'])&&$this->post['subtotal_fee']!=''?floor($this->post['subtotal_fee']):"";

        if($status==1){
           if($open_type==='')return error_show(1004,"参数 open_type 不能为空");
           if($open_type!=1){
               if($invCode==='') return error_show(1004,"参数 invCode 不能为空");
               if($invNum==='') return error_show(1004,"参数 invNum 不能为空");
               if($open_date==='') return error_show(1004,"参数 open_date 不能为空");
               if($total_fee==='') return error_show(1004,"参数 tatal_fee 不能为空");
               if($subtotal_fee==='') return error_show(1004,"参数 subtotal_fee 不能为空");
               if($total_fee!=$invinfo['inv_value'])return error_show(1004,"发票金额不足");
           }else{
           	$status=7;
           }
        }
        $update=[
            "status"=>$status,
            "exam_remark"=>$remark,
            "updatetime" => date("Y-m-d H:i:s")
            ];
        $status==1 ? $update['open_type']=$open_type :"";
        Db::startTrans();
        try{

          $invup =Db::name("invoice_pool")->where($invinfo)->update($update);
        if($invup){
            if($status==1&& $open_type!=1){

            		 $invpool=[
                        "invNo"=>$invinfo['invNo'],
                        "inv_type"=>$open_type,
                        "inv_code"=>$invCode,
                        "inv_number"=>$invNum,
                        "inv_total"=>$total_fee,
                        "inv_subtotal"=>$subtotal_fee,
                        "open_date"=>$open_date,
                        "item"=>'',
                        "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){
	                    Db::rollback();
	                   return error_show(1004,"发票信息添加失败");
	                }
            	}
            if($status==7 && $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,
									unitName as DW,
									goodNum as SPSL,
									goodPrice as DJ,
									totalPrice as JE,
									1 HSBZ,
									tax as SL,
									taxPrice as SE")
									->select()->toJson();
					if(empty($goodinfo)){
						Db::rollback();
	                    return error_show(1004,"开票商品信息未找到");
					}
						$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"=>"",
							"DDMXXX"=>$goodinfo,
							"FPLXDM"=>invoiceType($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,"开票信息生成失败");
					}
					Cache::push("invoiceList",$data["DDQQLSH"]);
            	}


            if($status==4 ||$status==5 ){
               $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 ?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['sequenceNo']])->find();
                           if($report)$report->rmField("invNo",$invinfo['invNo']);
                      }
                 }
            }
            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,"发票申请信息未找到");
        }
        $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']!="" ? floor($this->post['post_fee']):"0";
        Db::startTrans();
        try{
            $data=[
                "post_company"=>$post_company,
                "post_code"=>$post_code,
                "post_fee"=>$post_fee,
                "status"=>3,
                "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,"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());
        }
    }
    /**
    * 发票废弃使用
    */
    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,5]))return  error_show(1004,"发票状态无法废弃");
		$company =Db::name("company_info")->where(["companyNo"=>$invinfo['inv_out']])->find();
		if($company==false)return  error_show(1004,"开票业务公司未找到");
		$invoice =Db::name("invoice_ticket")->where(["invNo"=>$invNo])->find();
		if($invoice==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'],invoiceType($invinfo['inv_type']),$invoice['inv_code'],$invoice['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){
			 	if($invinfo['status']!=5){
			    $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']!=3){
         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,"未找到开票的销售单信息");
     }
     $returnCode = makeNo("RIN");
     $data=[
         "returnCode"=>$returnCode,
         "invNo"=>$invNo,
         "return_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")
         ];
        $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);
             }
             return app_show(0,"退票申请新建成功",["returnCode"=>$returnCode]);
         }else{
             return error_show(1005,"退票申请新建失败");
         }
    }
    // 0 待审核 1 待退票 2 退票成功 3 驳回4 退票失败
    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 不能为空");
        }
        $return_type = isset($this->post['return_type'])&&$this->post['return_type']!="" ? intval($this->post['return_type']):"";
        if ($return_type==""){
              return error_show(1005,"参数 return_type 不能为空");
        }
        $remark =isset($this->post['remark'])&&$this->post['remark']!="" ? trim($this->post['remark']):"";
        if($remark==""){
             return error_show(1005,"参数 remark 不能为空");
        }
        $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();
        if($invinfo==false){
            return error_show(1004,"发票申请数据未找到");
        }
        if($invinfo['status']!=3){
         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,"未找到开票的销售单信息");
         }
         Db::startTrans();
         try{
             $update=["status"=>$status,"return_type"=>$return_type,"remark"=>$remark,"updatetime"=>date("Y-m-d H:i:s")];
             $up =Db::name("invoice_return")->where($return)->update($update);
            if($up){
                if($status==2){
                      $qrdArr=Db::name("assoc")->where(["viceCode"=>$return['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($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']==0 ? 1 : 2,
                                  "status"=>$qrdinfo['ainv_fee']==0 &&$qrdinfo['inv_fee']==0 && $qrdinfo['pay_status'] ?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,"确认单关联信息更新失败");
                              }
                          }
                     }
                }
                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());
         }

    }
    //红冲票
    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['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']==0 ? 1 : 2,
                              "status"=>$qrdinfo['ainv_fee']==0 &&$qrdinfo['inv_fee']==0 && $qrdinfo['pay_status'] ?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']??"";
        $poolinfo =  Db::name("invoice_pool_info")->where(["invNo"=>$return['invNo']])->find();
        $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;
        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']) :"";
        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']!=="" ? intval($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];
        }
//          $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%"];
        }
         $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")->leftJoin("invoice_pool_info b","a.invNo=b.invNo")->where
        ($condition)->count();
        $total =ceil($count/$size);
        $page= $page>$total ? intval($total):$page;
        $list=Db::name("invoice_pool")->alias("a")->leftJoin("invoice_pool_info b","a.invNo=b.invNo")->where($condition)
        ->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])->select()->toArray();
        $poolinfop['goodList']=$orderList;
       return app_show(0,"获取成功",$poolinfo);
    }
    //退票列表
    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]];
        $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']!=="" ? intval($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']??"";
        }
        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]))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"=>$invfo['inv_out']])->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"=>invoiceType($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,
									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,"开票商品信息未找到");
					}
		$info=[
			"SQBSCQQLSH"=>randomkeys(29).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_total'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"", //申请说明
			 "XXBTSBS"=>"0",//0: 正常;1:成品油发票,涉及销售数量 变更(销货退回、开票有误等原因);2: 成品油发票,仅涉及销售金额变更(销 售折让);3:机动车发票,仅涉及销售数
//量变更(销货退回、开票有误等原因);4: 机动车发票,仅涉及销售金额变更(销 售折让)
		];
					$invRed=makeNo("IRE");
		$data=[
			'invNo'=>$invNo,
			"invRed"=>$invRed,
			"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_total'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"", //申请说明
			 "XXBTSBS"=>"0",
			 "DDMXX"=>json_encode($goodinfo,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>$redticketArry['SQBSCQQPCH'],
			  "FPLXDM"=>invoiceType($invfo['inv_type']),
		];
		$redticketList[]=["HZSQDTXX"=>$info,"DDMXXX"=>$goodinfo];
		$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['remark']='红冲申请审核通过';
			}
			if($resultChild['ZTDM']=='060001'){
				$data['status']=1;
				$data['remark']='红冲申请审核中';
			}
		}
		$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"=>invoiceType($inv_type[0]),
				];
			$redticketList=[];
			foreach ($invfo as $value){
					if(!in_array($value['status'],[1,2,3,4,5])){
						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("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,
									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,"开票商品信息未找到");
					}

			$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_total'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",//0: 正常;1:成品油发票,涉及销售数量 变更(销货退回、开票有误等原因);2: 成品油发票,仅涉及销售金额变更(销 售折让);3:机动车发票,仅涉及销售数
//量变更(销货退回、开票有误等原因);4: 机动车发票,仅涉及销售金额变更(销 售折让)
		];
		$data=[
			'invNo'=>$value['invNo'],
			"invRed"=>makeNo("IRE"),
			"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_total'],//合计金额(不含 税)
			 "HJSE"=>"-".$ticket['tax_fee'],//合计税额
			 "SQSM"=>"1100000000", //申请说明
			 "XXBTSBS"=>"0",
			 "DDMXXX"=>json_encode($goodinfo,JSON_UNESCAPED_UNICODE),
			 "SQBSCQQPCH"=>$redticketArry['SQBSCQQPCH'],
			  "FPLXDM"=>invoiceType($value['inv_type']),
		];
		$redticketList[]=["HZSQDTXX"=>$info,"DDMXXX"=>$goodinfo];
		$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'];
//							$data['status']=2;
//							$data['remark']='红冲申请审核通过';
						}
						if($value['ZTDM']=='060001'){
							$insertAll[$value['SQBSCQQLSH']]['status']=1;
							$insertAll[$value['SQBSCQQLSH']]['remark']="红冲申请审核中";
							$insertAll[$value['SQBSCQQLSH']]['XXBBH']=$value['XXBBH'];
						}
					}
				}
			}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"=>"",
							"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]];
        $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%"];
        }
         $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"]!=''?floor($this->post["total_low"]):"";
        $total_up=isset($this->post["total_up"])&&$this->post["total_up"]!=''?floor($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]);
    }

}