Browse Source

fix:发票回显修改

duxin 5 months ago
parent
commit
12928e9147
1 changed files with 1799 additions and 1799 deletions
  1. 1799 1799
      src/jfw/modules/subscribepay/src/service/invoice.go

+ 1799 - 1799
src/jfw/modules/subscribepay/src/service/invoice.go

@@ -1,66 +1,66 @@
 package service
 
 import (
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/go-xweb/log"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"app.yhyue.com/moapp/jybase/mail"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
-	"bytes"
-	"database/sql"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"github.com/google/uuid"
-	"io/ioutil"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"net/http"
-	"os"
-	"strconv"
-	"strings"
-	"sync"
-	"time"
+    . "app.yhyue.com/moapp/jybase/api"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jybase/go-xweb/log"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jybase/mail"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
+    "bytes"
+    "database/sql"
+    "encoding/json"
+    "errors"
+    "fmt"
+    "github.com/google/uuid"
+    "io/ioutil"
+    "jy/src/jfw/modules/subscribepay/src/config"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "net/http"
+    "os"
+    "strconv"
+    "strings"
+    "sync"
+    "time"
 )
 
 type Invoice struct {
-	*xweb.Action
-	addinvoice        xweb.Mapper `xweb:"/invoice/add"`            //开发票
-	showinvoice       xweb.Mapper `xweb:"/invoice/show"`           //查看发票
-	newInvoiceShow    xweb.Mapper `xweb:"/invoice/newShow"`        //查看发票
-	showinvoiceList   xweb.Mapper `xweb:"/invoice/showList"`       //新查看发票 p537
-	callbackinvoice   xweb.Mapper `xweb:"/invoice/callback"`       //开发票回调
-	replaceinvoice    xweb.Mapper `xweb:"/invoice/replace"`        //换发票
-	newReplaceinvoice xweb.Mapper `xweb:"/invoice/newReplace"`     //新换发票
-	refundinvoice     xweb.Mapper `xweb:"/invoice/refund"`         //退票
-	invoiceinfo       xweb.Mapper `xweb:"/invoice/info"`           //订单详情数据
-	available         xweb.Mapper `xweb:"/invoice/available"`      //是否可用开发票
-	invoiceswitch     xweb.Mapper `xweb:"/invoice/switch"`         //发票开关
-	invoiceQuery      xweb.Mapper `xweb:"/invoice/query"`          //发票信息查询
-	invoiceSubmit     xweb.Mapper `xweb:"/invoice/submit"`         //发票信息提交
-	getCompanyCode    xweb.Mapper `xweb:"/invoice/getCompanyCode"` //开票联想税号
+    *xweb.Action
+    addinvoice        xweb.Mapper `xweb:"/invoice/add"`            //开发票
+    showinvoice       xweb.Mapper `xweb:"/invoice/show"`           //查看发票
+    newInvoiceShow    xweb.Mapper `xweb:"/invoice/newShow"`        //查看发票
+    showinvoiceList   xweb.Mapper `xweb:"/invoice/showList"`       //新查看发票 p537
+    callbackinvoice   xweb.Mapper `xweb:"/invoice/callback"`       //开发票回调
+    replaceinvoice    xweb.Mapper `xweb:"/invoice/replace"`        //换发票
+    newReplaceinvoice xweb.Mapper `xweb:"/invoice/newReplace"`     //新换发票
+    refundinvoice     xweb.Mapper `xweb:"/invoice/refund"`         //退票
+    invoiceinfo       xweb.Mapper `xweb:"/invoice/info"`           //订单详情数据
+    available         xweb.Mapper `xweb:"/invoice/available"`      //是否可用开发票
+    invoiceswitch     xweb.Mapper `xweb:"/invoice/switch"`         //发票开关
+    invoiceQuery      xweb.Mapper `xweb:"/invoice/query"`          //发票信息查询
+    invoiceSubmit     xweb.Mapper `xweb:"/invoice/submit"`         //发票信息提交
+    getCompanyCode    xweb.Mapper `xweb:"/invoice/getCompanyCode"` //开票联想税号
 }
 
 var dbname = "invoice"
 
 type ReturnJson map[string]interface{}
 type InvoiceInfo struct {
-	code int                    `json:"code"`
-	msg  string                 `json:"msg"`
-	data map[string]interface{} `json:"data"`
+    code int                    `json:"code"`
+    msg  string                 `json:"msg"`
+    data map[string]interface{} `json:"data"`
 }
 
 // 红票信息
 type RedMsg struct {
-	InvoiceCode      string `json:"invoice_code"`
-	InvoiceNumber    string `json:"invoice_number"`
-	Url              string `json:"url"`
-	InvoiceSerialnum string `json:"invoice_serialnum"`
-	InvoiceStatus    string `json:"invoice_status"`
-	BillingTime      int64  `json:"billing_time"`
+    InvoiceCode      string `json:"invoice_code"`
+    InvoiceNumber    string `json:"invoice_number"`
+    Url              string `json:"url"`
+    InvoiceSerialnum string `json:"invoice_serialnum"`
+    InvoiceStatus    string `json:"invoice_status"`
+    BillingTime      int64  `json:"billing_time"`
 }
 
 var emailHtml_gs = `<p class="item">
@@ -103,1878 +103,1878 @@ var email_format = ""
 var email_format_new = ""
 
 func init() {
-	for i := 0; i < 10; i++ {
-		locks[i] = sync.Mutex{}
-	}
-	r, err := os.Open("./mailtemplate.html")
-	if err != nil {
-		log.Println("err", err)
-	}
-	defer r.Close()
-	bs, _ := ioutil.ReadAll(r)
-	email_format = string(bs)
-	r, err = os.Open("./mailtemplateNew.html")
-	if err != nil {
-		log.Println("err", err)
-	}
-	defer r.Close()
-	bs, _ = ioutil.ReadAll(r)
-	email_format_new = string(bs)
+    for i := 0; i < 10; i++ {
+        locks[i] = sync.Mutex{}
+    }
+    r, err := os.Open("./mailtemplate.html")
+    if err != nil {
+        log.Println("err", err)
+    }
+    defer r.Close()
+    bs, _ := ioutil.ReadAll(r)
+    email_format = string(bs)
+    r, err = os.Open("./mailtemplateNew.html")
+    if err != nil {
+        log.Println("err", err)
+    }
+    defer r.Close()
+    bs, _ = ioutil.ReadAll(r)
+    email_format_new = string(bs)
 }
 
 func (this *Invoice) Invoiceswitch() {
-	if config.InvoiceConfig.Invoice_switch {
-		this.ServeJson(map[string]interface{}{
-			"code": "1000",
-		})
-	} else {
-		//更新数据 用于回显
-		userId := qutil.ObjToString(this.GetSession("userId"))
-		order_code := this.GetString("order_code")
-		applyBill_company := this.GetString("company")
-		//获取数据
-		applyBill_type := this.GetString("invoice_type") //个人 单位
-		my_email := this.GetString("email")
-		phone_num := this.GetString("phone_num")
-		code := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
-		data := make(map[string]interface{})
-		dataexport_data := make(map[string]interface{})
-		if userId != "" && my_email != "" && phone_num != "" && order_code != "" {
-			if applyBill_type == "个人" {
-				data["taxpayer_identnum"] = ""
-				data["company_name"] = ""
-				dataexport_data["applyBill_type"] = 0
-				dataexport_data["applyBill_taxnum"] = ""
-				dataexport_data["applybill_company"] = ""
-			} else {
-				data["taxpayer_identnum"] = code
-				data["company_name"] = applyBill_company
-				dataexport_data["applyBill_taxnum"] = code
-				dataexport_data["applybill_company"] = applyBill_company
-				dataexport_data["applyBill_type"] = 1
-			}
-			dataexport_data["user_mail"] = my_email
-			dataexport_data["user_phone"] = phone_num
-			data["order_code"] = order_code
-			data["mail"] = my_email
-			data["phone"] = phone_num
-			data["invoice_type"] = applyBill_type
-			data["create_time"] = time.Now().Unix()
-			data["user_id"] = userId
-			status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-			if len(*status) <= 0 {
-				//更新 "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum"
-				util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data)
-			} else {
-				req := map[string]interface{}{
-					"order_code":      order_code,
-					"user_id":         userId,
-					"invoice_changed": 0,
-				}
-				if len(*status) > 1 {
-					req["id"] = (*status)[1]["id"]
-				} else {
-					req["id"] = (*status)[0]["id"]
-				}
-				util.Mysql.Update(dbname, req, data)
-			}
-		}
-		this.ServeJson(map[string]interface{}{
-			"code":   "1001",
-			"messge": "因第三方发票系统升级,开发票功能暂停使用。如有疑问,请咨询客服400-108-6670",
-		})
-	}
+    if config.InvoiceConfig.Invoice_switch {
+        this.ServeJson(map[string]interface{}{
+            "code": "1000",
+        })
+    } else {
+        //更新数据 用于回显
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        order_code := this.GetString("order_code")
+        applyBill_company := this.GetString("company")
+        //获取数据
+        applyBill_type := this.GetString("invoice_type") //个人 单位
+        my_email := this.GetString("email")
+        phone_num := this.GetString("phone_num")
+        code := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
+        data := make(map[string]interface{})
+        dataexport_data := make(map[string]interface{})
+        if userId != "" && my_email != "" && phone_num != "" && order_code != "" {
+            if applyBill_type == "个人" {
+                data["taxpayer_identnum"] = ""
+                data["company_name"] = ""
+                dataexport_data["applyBill_type"] = 0
+                dataexport_data["applyBill_taxnum"] = ""
+                dataexport_data["applybill_company"] = ""
+            } else {
+                data["taxpayer_identnum"] = code
+                data["company_name"] = applyBill_company
+                dataexport_data["applyBill_taxnum"] = code
+                dataexport_data["applybill_company"] = applyBill_company
+                dataexport_data["applyBill_type"] = 1
+            }
+            dataexport_data["user_mail"] = my_email
+            dataexport_data["user_phone"] = phone_num
+            data["order_code"] = order_code
+            data["mail"] = my_email
+            data["phone"] = phone_num
+            data["invoice_type"] = applyBill_type
+            data["create_time"] = time.Now().Unix()
+            data["user_id"] = userId
+            status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+            if len(*status) <= 0 {
+                //更新 "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum"
+                util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data)
+            } else {
+                req := map[string]interface{}{
+                    "order_code":      order_code,
+                    "user_id":         userId,
+                    "invoice_changed": 0,
+                }
+                if len(*status) > 1 {
+                    req["id"] = (*status)[1]["id"]
+                } else {
+                    req["id"] = (*status)[0]["id"]
+                }
+                util.Mysql.Update(dbname, req, data)
+            }
+        }
+        this.ServeJson(map[string]interface{}{
+            "code":   "1001",
+            "messge": "因第三方发票系统升级,开发票功能暂停使用。如有疑问,请咨询客服400-108-6670",
+        })
+    }
 }
 
 // Addinvoice 用户端-线上开票只能选电子普票
 func (this *Invoice) Addinvoice() error {
-	defer qutil.Catch()
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	var applyBill_status int
-	var order_code, applyBill_company, applyBill_type, price, product_name string
-	order_code = this.GetString("order_code")
-	applyBill_company = this.GetString("company")
-	//获取数据
-	applyBill_type = this.GetString("invoice_type") //个人 单位
-	my_email := this.GetString("email")
-	phone_num := this.GetString("phone_num")
-	code := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
-	isSys, _ := this.GetBool("isSys")
-	jsonData := ReturnJson{}
-	invoice_status := -1   //发票表开票失败
-	updata_status := false //更新表状态
-	if userId != "" && my_email != "" && phone_num != "" && order_code != "" {
-		last := order_code[len([]rune(order_code))-1:]
-		pos := qutil.IntAllDef(last, 0)
-		locks[pos].Lock()
-		defer locks[pos].Unlock()
-		u := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId, "applyBill_status": map[string]interface{}{"ne": 2}}, "order_money,product_type,pay_way,pay_money,is_backstage_order,billingMode,signing_subject,return_status,applybill_status", "")
-		if u != nil {
-			//后端代用户下单支持开票 order_channel = xdqd04
-			if qutil.IntAll((*u)["billingMode"]) == 1 && (qutil.IntAll((*u)["is_backstage_order"]) != 1 || (qutil.IntAll((*u)["is_backstage_order"]) == 1 && qutil.ObjToString((*u)["signing_subject"]) == "h01" && qutil.IntAll((*u)["return_status"]) == 1 && qutil.IntAll((*u)["applybill_status"]) == 0)) {
-				var prices float64
-				//公对公转账 账单金额可以修改 开发票应取实付金额 pay_money
-				//微信支付宝支付 pay_money为订单金额减去微信or支付包红包
-				prices = qutil.Float64All((*u)["pay_money"]) / float64(100)
-				price = strconv.FormatFloat(prices, 'f', -1, 64)
-				product_name = (*u)["product_type"].(string)
-				applyBill_status = 1
-				data := make(map[string]interface{})
-				dataexport_data := make(map[string]interface{})
-				dataexport_data["applyBill_status"] = applyBill_status
-				if applyBill_type == "个人" {
-					dataexport_data["applyBill_type"] = 0
-					data["taxpayer_identnum"] = ""
-					data["company_name"] = ""
-					dataexport_data["applyBill_taxnum"] = ""
-					dataexport_data["applybill_company"] = ""
-				} else {
-					data["taxpayer_identnum"] = code
-					data["company_name"] = applyBill_company
-					dataexport_data["applyBill_taxnum"] = code
-					dataexport_data["applybill_company"] = applyBill_company
-					dataexport_data["applyBill_type"] = 1
-				}
-				dataexport_data["user_mail"] = my_email
-				data["product_type"] = product_name
-				data["order_code"] = order_code
-				data["mail"] = my_email
-				data["phone"] = phone_num
-				data["invoice_type"] = applyBill_type
-				data["invoice_changed"] = 0
-				data["create_time"] = time.Now().Unix()
-				data["user_id"] = userId
-				data["invoice_status"] = 0
-				data["invoice_money"] = price
-				var orders = []map[string]interface{}{}
-				var items = []map[string]interface{}{}
-				item := map[string]interface{}{
-					"name":        product_name,
-					"code":        config.InvoiceConfig.Code,
-					"yhzcbs":      config.InvoiceConfig.Tax_policy,
-					"lineType":    config.InvoiceConfig.Invoice_nature,
-					"taxRate":     config.InvoiceConfig.Tax_rate,
-					"taxPrice":    price,
-					"totalAmount": price,
-					"quantity":    "1",
-				}
-				items = append(items, item)
-				order := map[string]interface{}{
-					"billNo": order_code,
-					"items":  items,
-				}
-				orders = append(orders, order)
-				client := &http.Client{}
-				body := map[string]interface{}{
-					"Swno":      order_code,
-					"custType":  "03",
-					"orders":    orders,
-					"custTaxNo": code,
-					"phone":     phone_num,
-					"billDate":  NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
-				}
-
-				if applyBill_type == "单位" {
-					body["custName"] = applyBill_company
-				} else {
-					body["custName"] = applyBill_type
-				}
-				//发送请求之前插入数据,防止请求时间过长
-				if !isSys {
-					status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-					if len(*status) > 0 {
-						return nil
-					}
-					if i := util.Mysql.Insert(dbname, data); i > 0 {
-						invoice_status = 0
-					}
-					if !util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data) {
-						invoice_status = -1
-					}
-				} else {
-					if ok := util.Mysql.Update(dbname, map[string]interface{}{
-						"order_code":      order_code,
-						"user_id":         userId,
-						"invoice_changed": 0,
-					}, data); ok {
-						invoice_status = 0
-					}
-				}
-				if config.InvoiceConfig.Third_party_switch {
-					b, _ := json.Marshal(body)
-					buffer := bytes.NewBuffer(b)
-					request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
-					response, err := client.Do(request)
-					if err == nil {
-						res, err := ioutil.ReadAll(response.Body)
-						if err != nil {
-							invoice_status = -1
-						} else {
-							resMap := qutil.ObjToMap(string(res))
-							if *resMap != nil {
-								if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
-									invoice_status = 1
-									jsonData["invoice_status"] = invoice_status
-								} else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
-									// log.Println("开票中")
-									invoice_status = 0
-									jsonData["invoice_status"] = invoice_status
-								} else { //开票失败
-									// log.Println("开票失败")
-									invoice_status = -1
-									jsonData["invoice_status"] = invoice_status
-								}
-							}
-							defer response.Body.Close()
-							resData := (*resMap)["data"].(map[string]interface{})
-							update_status := util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code}, map[string]interface{}{
-								"invoice_serialnum": resData["swno"],
-								"invoice_code":      resData["fpdm"],
-								"invoice_number":    resData["fphm"],
-								"url":               resData["path"],
-								"invoice_status":    invoice_status,
-							})
-							if !update_status {
-								log.Println("order_ocde:", order_code+"update fail")
-							}
-						}
-					}
-				}
-			}
-		} else {
-			if invoice_status != 1 {
-				log.Println("invoice err:", "updata_status:", updata_status, "order_code:", order_code, "invoice_status:", invoice_status, userId)
-			}
-		}
-	}
-	jsonData["invoice_status"] = invoice_status
-	this.ServeJson(jsonData)
-	return nil
+    defer qutil.Catch()
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    var applyBill_status int
+    var order_code, applyBill_company, applyBill_type, price, product_name string
+    order_code = this.GetString("order_code")
+    applyBill_company = this.GetString("company")
+    //获取数据
+    applyBill_type = this.GetString("invoice_type") //个人 单位
+    my_email := this.GetString("email")
+    phone_num := this.GetString("phone_num")
+    code := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
+    isSys, _ := this.GetBool("isSys")
+    jsonData := ReturnJson{}
+    invoice_status := -1   //发票表开票失败
+    updata_status := false //更新表状态
+    if userId != "" && my_email != "" && phone_num != "" && order_code != "" {
+        last := order_code[len([]rune(order_code))-1:]
+        pos := qutil.IntAllDef(last, 0)
+        locks[pos].Lock()
+        defer locks[pos].Unlock()
+        u := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId, "applyBill_status": map[string]interface{}{"ne": 2}}, "order_money,product_type,pay_way,pay_money,is_backstage_order,billingMode,signing_subject,return_status,applybill_status", "")
+        if u != nil {
+            //后端代用户下单支持开票 order_channel = xdqd04
+            if qutil.IntAll((*u)["billingMode"]) == 1 && (qutil.IntAll((*u)["is_backstage_order"]) != 1 || (qutil.IntAll((*u)["is_backstage_order"]) == 1 && qutil.ObjToString((*u)["signing_subject"]) == "h01" && qutil.IntAll((*u)["return_status"]) == 1 && qutil.IntAll((*u)["applybill_status"]) == 0)) {
+                var prices float64
+                //公对公转账 账单金额可以修改 开发票应取实付金额 pay_money
+                //微信支付宝支付 pay_money为订单金额减去微信or支付包红包
+                prices = qutil.Float64All((*u)["pay_money"]) / float64(100)
+                price = strconv.FormatFloat(prices, 'f', -1, 64)
+                product_name = (*u)["product_type"].(string)
+                applyBill_status = 1
+                data := make(map[string]interface{})
+                dataexport_data := make(map[string]interface{})
+                dataexport_data["applyBill_status"] = applyBill_status
+                if applyBill_type == "个人" {
+                    dataexport_data["applyBill_type"] = 0
+                    data["taxpayer_identnum"] = ""
+                    data["company_name"] = ""
+                    dataexport_data["applyBill_taxnum"] = ""
+                    dataexport_data["applybill_company"] = ""
+                } else {
+                    data["taxpayer_identnum"] = code
+                    data["company_name"] = applyBill_company
+                    dataexport_data["applyBill_taxnum"] = code
+                    dataexport_data["applybill_company"] = applyBill_company
+                    dataexport_data["applyBill_type"] = 1
+                }
+                dataexport_data["user_mail"] = my_email
+                data["product_type"] = product_name
+                data["order_code"] = order_code
+                data["mail"] = my_email
+                data["phone"] = phone_num
+                data["invoice_type"] = applyBill_type
+                data["invoice_changed"] = 0
+                data["create_time"] = time.Now().Unix()
+                data["user_id"] = userId
+                data["invoice_status"] = 0
+                data["invoice_money"] = price
+                var orders = []map[string]interface{}{}
+                var items = []map[string]interface{}{}
+                item := map[string]interface{}{
+                    "name":        product_name,
+                    "code":        config.InvoiceConfig.Code,
+                    "yhzcbs":      config.InvoiceConfig.Tax_policy,
+                    "lineType":    config.InvoiceConfig.Invoice_nature,
+                    "taxRate":     config.InvoiceConfig.Tax_rate,
+                    "taxPrice":    price,
+                    "totalAmount": price,
+                    "quantity":    "1",
+                }
+                items = append(items, item)
+                order := map[string]interface{}{
+                    "billNo": order_code,
+                    "items":  items,
+                }
+                orders = append(orders, order)
+                client := &http.Client{}
+                body := map[string]interface{}{
+                    "Swno":      order_code,
+                    "custType":  "03",
+                    "orders":    orders,
+                    "custTaxNo": code,
+                    "phone":     phone_num,
+                    "billDate":  NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
+                }
+
+                if applyBill_type == "单位" {
+                    body["custName"] = applyBill_company
+                } else {
+                    body["custName"] = applyBill_type
+                }
+                //发送请求之前插入数据,防止请求时间过长
+                if !isSys {
+                    status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+                    if len(*status) > 0 {
+                        return nil
+                    }
+                    if i := util.Mysql.Insert(dbname, data); i > 0 {
+                        invoice_status = 0
+                    }
+                    if !util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data) {
+                        invoice_status = -1
+                    }
+                } else {
+                    if ok := util.Mysql.Update(dbname, map[string]interface{}{
+                        "order_code":      order_code,
+                        "user_id":         userId,
+                        "invoice_changed": 0,
+                    }, data); ok {
+                        invoice_status = 0
+                    }
+                }
+                if config.InvoiceConfig.Third_party_switch {
+                    b, _ := json.Marshal(body)
+                    buffer := bytes.NewBuffer(b)
+                    request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
+                    response, err := client.Do(request)
+                    if err == nil {
+                        res, err := ioutil.ReadAll(response.Body)
+                        if err != nil {
+                            invoice_status = -1
+                        } else {
+                            resMap := qutil.ObjToMap(string(res))
+                            if *resMap != nil {
+                                if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
+                                    invoice_status = 1
+                                    jsonData["invoice_status"] = invoice_status
+                                } else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
+                                    // log.Println("开票中")
+                                    invoice_status = 0
+                                    jsonData["invoice_status"] = invoice_status
+                                } else { //开票失败
+                                    // log.Println("开票失败")
+                                    invoice_status = -1
+                                    jsonData["invoice_status"] = invoice_status
+                                }
+                            }
+                            defer response.Body.Close()
+                            resData := (*resMap)["data"].(map[string]interface{})
+                            update_status := util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code}, map[string]interface{}{
+                                "invoice_serialnum": resData["swno"],
+                                "invoice_code":      resData["fpdm"],
+                                "invoice_number":    resData["fphm"],
+                                "url":               resData["path"],
+                                "invoice_status":    invoice_status,
+                            })
+                            if !update_status {
+                                log.Println("order_ocde:", order_code+"update fail")
+                            }
+                        }
+                    }
+                }
+            }
+        } else {
+            if invoice_status != 1 {
+                log.Println("invoice err:", "updata_status:", updata_status, "order_code:", order_code, "invoice_status:", invoice_status, userId)
+            }
+        }
+    }
+    jsonData["invoice_status"] = invoice_status
+    this.ServeJson(jsonData)
+    return nil
 }
 
 // 查看发票
 func (this *Invoice) Showinvoice() {
-	order_code := this.GetString("order_code")
-	data := make(map[string]interface{})
-	data["order_code"] = order_code
-	status := util.Mysql.Find(dbname, data, "", "create_time", 0, 0)
-	//红冲发票开关
-	redSwitchInfo := map[string]interface{}{
-		"ris": config.InvoiceConfig.Red_invoice_switch,
-		"rim": config.InvoiceConfig.Red_invoice_msg,
-	}
-	if status != nil && len(*status) != 0 {
-		count := len(*status)
-		data := (*status)[count-1]
-		if data != nil {
-			delete(data, "user_id")
-			if url := qutil.InterfaceToStr(data["url"]); url != "" {
-				//ios 移动端
-				if util.IsMobileIOS(this.Request.UserAgent()) {
-					//国家税务局-增值税电子发票公共服务平台
-					if strings.Contains(url, "tysl.beijing.chinatax") {
-						data["url"] = strings.ReplaceAll(url, "/preview.html?code=", "/web-reader/reader?file=")
-					}
-				}
-				this.ServeJson(map[string]interface{}{
-					"status":        "success",
-					"changed":       qutil.If(count > 1, true, false).(bool),
-					"data":          data,
-					"redSwitchInfo": redSwitchInfo,
-				})
-			} else {
-				this.ServeJson(map[string]interface{}{
-					"status":        "processing",
-					"changed":       qutil.If(count > 1, true, false).(bool),
-					"data":          data,
-					"redSwitchInfo": redSwitchInfo,
-				})
-			}
-		} else {
-			this.ServeJson(map[string]interface{}{
-				"status":        "fail",
-				"changed":       false,
-				"data":          "",
-				"redSwitchInfo": redSwitchInfo,
-			})
-		}
-		//if len(*status) > 1 {
-		//	if (*status)[1]["url"] != nil && (*status)[1]["url"] != "" {
-		//		this.ServeJson(map[string]interface{}{
-		//			"status":        "success",
-		//			"changed":       true,
-		//			"data":          (*status)[1],
-		//			"redSwitchInfo": redSwitchInfo,
-		//		})
-		//	} else {
-		//		this.ServeJson(map[string]interface{}{
-		//			"status":        "processing",
-		//			"changed":       true,
-		//			"data":          (*status)[1],
-		//			"redSwitchInfo": redSwitchInfo,
-		//		})
-		//	}
-		//} else {
-		//	if (*status)[0]["url"] != nil && (*status)[0]["url"] != "" {
-		//		this.ServeJson(map[string]interface{}{
-		//			"status":        "success",
-		//			"changed":       false,
-		//			"data":          (*status)[0],
-		//			"redSwitchInfo": redSwitchInfo,
-		//		})
-		//	} else {
-		//		this.ServeJson(map[string]interface{}{
-		//			"status":        "processing",
-		//			"changed":       false,
-		//			"data":          (*status)[0],
-		//			"redSwitchInfo": redSwitchInfo,
-		//		})
-		//	}
-		//}
-	} else {
-		datas := util.Mysql.FindOne("dataexport_order", data, "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum", "")
-		this.ServeJson(map[string]interface{}{
-			"status":        "fail",
-			"data":          "",
-			"datas":         datas,
-			"redSwitchInfo": redSwitchInfo,
-		})
-	}
+    order_code := this.GetString("order_code")
+    data := make(map[string]interface{})
+    data["order_code"] = order_code
+    status := util.Mysql.Find(dbname, data, "", "create_time", 0, 0)
+    //红冲发票开关
+    redSwitchInfo := map[string]interface{}{
+        "ris": config.InvoiceConfig.Red_invoice_switch,
+        "rim": config.InvoiceConfig.Red_invoice_msg,
+    }
+    if status != nil && len(*status) != 0 {
+        count := len(*status)
+        data := (*status)[count-1]
+        if data != nil {
+            delete(data, "user_id")
+            if url := qutil.InterfaceToStr(data["url"]); url != "" {
+                //ios 移动端
+                if util.IsMobileIOS(this.Request.UserAgent()) {
+                    //国家税务局-增值税电子发票公共服务平台
+                    if strings.Contains(url, "tysl.beijing.chinatax") {
+                        data["url"] = strings.ReplaceAll(url, "/preview.html?code=", "/web-reader/reader?file=")
+                    }
+                }
+                this.ServeJson(map[string]interface{}{
+                    "status":        "success",
+                    "changed":       qutil.If(count > 1, true, false).(bool),
+                    "data":          data,
+                    "redSwitchInfo": redSwitchInfo,
+                })
+            } else {
+                this.ServeJson(map[string]interface{}{
+                    "status":        "processing",
+                    "changed":       qutil.If(count > 1, true, false).(bool),
+                    "data":          data,
+                    "redSwitchInfo": redSwitchInfo,
+                })
+            }
+        } else {
+            this.ServeJson(map[string]interface{}{
+                "status":        "fail",
+                "changed":       false,
+                "data":          "",
+                "redSwitchInfo": redSwitchInfo,
+            })
+        }
+        //if len(*status) > 1 {
+        //	if (*status)[1]["url"] != nil && (*status)[1]["url"] != "" {
+        //		this.ServeJson(map[string]interface{}{
+        //			"status":        "success",
+        //			"changed":       true,
+        //			"data":          (*status)[1],
+        //			"redSwitchInfo": redSwitchInfo,
+        //		})
+        //	} else {
+        //		this.ServeJson(map[string]interface{}{
+        //			"status":        "processing",
+        //			"changed":       true,
+        //			"data":          (*status)[1],
+        //			"redSwitchInfo": redSwitchInfo,
+        //		})
+        //	}
+        //} else {
+        //	if (*status)[0]["url"] != nil && (*status)[0]["url"] != "" {
+        //		this.ServeJson(map[string]interface{}{
+        //			"status":        "success",
+        //			"changed":       false,
+        //			"data":          (*status)[0],
+        //			"redSwitchInfo": redSwitchInfo,
+        //		})
+        //	} else {
+        //		this.ServeJson(map[string]interface{}{
+        //			"status":        "processing",
+        //			"changed":       false,
+        //			"data":          (*status)[0],
+        //			"redSwitchInfo": redSwitchInfo,
+        //		})
+        //	}
+        //}
+    } else {
+        datas := util.Mysql.FindOne("dataexport_order", data, "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum", "")
+        this.ServeJson(map[string]interface{}{
+            "status":        "fail",
+            "data":          "",
+            "datas":         datas,
+            "redSwitchInfo": redSwitchInfo,
+        })
+    }
 
 }
 
 // 查看发票
 func (this *Invoice) ShowinvoiceList() {
-	order_code := this.GetString("order_code")
-	//红冲发票开关
-	redSwitchInfo := map[string]interface{}{
-		"ris": config.InvoiceConfig.Red_invoice_switch,
-		"rim": config.InvoiceConfig.Red_invoice_msg,
-	}
-	invoices := ShowList(order_code)
-	if invoices != nil && len(invoices) > 0 {
-		//isIos := util.IsMobileIOS(this.Request.UserAgent())
-		var invoiceData []map[string]interface{}
-		for _, data := range invoices {
-			//是否换过票
-			isChanged := qutil.IntAll(data["isChanged"]) > 1
-			if isChanged && qutil.IntAll(data["invoice_changed"]) == 0 { //换过票的 只展示换票后的数据
-				continue
-			}
-			delete(data, "user_id")
-			data["id"] = encrypt.SE.Encode2Hex(qutil.InterfaceToStr(data["id"]))
-			timeLimit := qutil.Int64All(data["create_time"]) <= config.InvoiceConfig.Order_createtime                                //24年之前的发票不让换票
-			isJyInvoice := !(qutil.InterfaceToStr(data["invoice_number"]) != "" && qutil.InterfaceToStr(data["invoice_code"]) == "") //非数电票
-			isJyEntity := data["invoicing_entity"] != nil && qutil.InterfaceToStr(data["invoicing_entity"]) != config.InvoiceConfig.SigningSubject
-			data["changed"] = qutil.If(isJyInvoice || isChanged || isJyEntity || timeLimit, true, false)
-			//if url := qutil.InterfaceToStr(data["url"]); url != "" {
-			//ios 移动端
-			//if !isIos {
-			data["url"] = qutil.If(data["source_url"] != nil && qutil.ObjToString(data["source_url"]) != "", data["source_url"], data["url"])
-			//国家税务局-增值税电子发票公共服务平台
-			//if strings.Contains(url, "tysl.beijing.chinatax") {
-			//	data["url"] = strings.ReplaceAll(url, "/preview.html?code=", "/web-reader/reader?file=")
-			//}
-			//}
-			//}
-			isReopen := timeLimit
-			//var isReopen bool
-			if qutil.IntAll(data["invoice_status"]) == -1 && !isReopen {
-				isReopen = util.Mysql.Count("invoice_fail_record", map[string]interface{}{
-					"only_Identifying": data["only_Identifying"],
-					"order_code":       order_code,
-				})+1 >= config.InvoiceConfig.SubmitNum
-			}
-			data["only_Identifying"] = encrypt.SE.EncodeString(qutil.InterfaceToStr(data["only_Identifying"]))
-			data["isReopen"] = isReopen
-			invoiceData = append(invoiceData, data)
-		}
-		this.ServeJson(map[string]interface{}{
-			"status":        "success",
-			"invoiceData":   invoiceData,
-			"redSwitchInfo": redSwitchInfo,
-		})
-	} else {
-		data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": order_code,
-		}, "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum", "")
-		if data != nil {
-			(*data)["status"] = "fail"
-		}
-
-		this.ServeJson(map[string]interface{}{
-			"status":        "fail",
-			"orderData":     data,
-			"redSwitchInfo": redSwitchInfo,
-		})
-	}
+    order_code := this.GetString("order_code")
+    //红冲发票开关
+    redSwitchInfo := map[string]interface{}{
+        "ris": config.InvoiceConfig.Red_invoice_switch,
+        "rim": config.InvoiceConfig.Red_invoice_msg,
+    }
+    invoices := ShowList(order_code)
+    if invoices != nil && len(invoices) > 0 {
+        //isIos := util.IsMobileIOS(this.Request.UserAgent())
+        var invoiceData []map[string]interface{}
+        for _, data := range invoices {
+            //是否换过票
+            isChanged := qutil.IntAll(data["isChanged"]) > 1
+            if isChanged && qutil.IntAll(data["invoice_changed"]) == 0 { //换过票的 只展示换票后的数据
+                continue
+            }
+            delete(data, "user_id")
+            data["id"] = encrypt.SE.Encode2Hex(qutil.InterfaceToStr(data["id"]))
+            timeLimit := qutil.Int64All(data["create_time"]) <= config.InvoiceConfig.Order_createtime                                //24年之前的发票不让换票
+            isJyInvoice := !(qutil.InterfaceToStr(data["invoice_number"]) != "" && qutil.InterfaceToStr(data["invoice_code"]) == "") //非数电票
+            isJyEntity := data["invoicing_entity"] != nil && qutil.InterfaceToStr(data["invoicing_entity"]) != config.InvoiceConfig.SigningSubject
+            data["changed"] = qutil.If(isJyInvoice || isChanged || isJyEntity || timeLimit, true, false)
+            //if url := qutil.InterfaceToStr(data["url"]); url != "" {
+            //ios 移动端
+            //if !isIos {
+            data["url"] = qutil.If(data["source_url"] != nil && qutil.ObjToString(data["source_url"]) != "", data["source_url"], data["url"])
+            //国家税务局-增值税电子发票公共服务平台
+            //if strings.Contains(url, "tysl.beijing.chinatax") {
+            //	data["url"] = strings.ReplaceAll(url, "/preview.html?code=", "/web-reader/reader?file=")
+            //}
+            //}
+            //}
+            isReopen := timeLimit
+            //var isReopen bool
+            if qutil.IntAll(data["invoice_status"]) == -1 && !isReopen {
+                isReopen = util.Mysql.Count("invoice_fail_record", map[string]interface{}{
+                    "only_Identifying": data["only_Identifying"],
+                    "order_code":       order_code,
+                })+1 >= config.InvoiceConfig.SubmitNum
+            }
+            data["only_Identifying"] = encrypt.SE.EncodeString(qutil.InterfaceToStr(data["only_Identifying"]))
+            data["isReopen"] = isReopen
+            invoiceData = append(invoiceData, data)
+        }
+        this.ServeJson(map[string]interface{}{
+            "status":        "success",
+            "invoiceData":   invoiceData,
+            "redSwitchInfo": redSwitchInfo,
+        })
+    } else {
+        data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+            "order_code": order_code,
+        }, "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum", "")
+        if data != nil {
+            (*data)["status"] = "fail"
+        }
+
+        this.ServeJson(map[string]interface{}{
+            "status":        "fail",
+            "orderData":     data,
+            "redSwitchInfo": redSwitchInfo,
+        })
+    }
 }
 
 func ShowList(order_code string) []map[string]interface{} {
-	data := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT *,(
+    data := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT *,(
   SELECT count(1) as count FROM invoice b WHERE b.order_code = a.order_code and  b.only_Identifying is not null and b.only_Identifying = a.only_Identifying
 ) as isChanged FROM invoice a WHERE order_code = '%s' and invoice_status != -2 and invoice_variety is not null and invoice_variety is not null and invoice_variety not  LIKE '%s' ORDER BY create_time DESC`, order_code, "%纸质%"))
-	if data == nil {
-		return nil
-	}
-	return *data
+    if data == nil {
+        return nil
+    }
+    return *data
 }
 
 func (this *Invoice) NewInvoiceShow() {
-	stype := this.GetString("stype")
-	code := this.GetString("code")
-	data := make(map[string]interface{})
-	var sData map[string]interface{}
-	switch stype {
-	case "1": //订单回显金额
-		payMoney, phone := ResidueMoney(code)
-		data["pay_money"] = payMoney
-		sData = ShowData(phone)
-	case "2": //发票信息回显
-		invoice := util.Mysql.FindOne("invoice", map[string]interface{}{"id": encrypt.SE.Decode4Hex(code)}, "id,only_Identifying,order_code,invoice_order_code,invoice_money,remark,invoice_type,invoice_content,invoice_variety,company_name,phone,mail,taxpayer_identnum,invoice_money,invoice_order_money,company_address,bank_name,recipient,delivery_address,bank_account,company_phone", "")
-		if invoice != nil {
-			(*invoice)["id"] = code
-			if (*invoice)["invoice_order_code"] != nil {
-				(*invoice)["order_code"] = (*invoice)["invoice_order_code"]
-			}
-			(*invoice)["only_Identifying"] = encrypt.SE.EncodeString(qutil.InterfaceToStr((*invoice)["only_Identifying"]))
-		}
-		data["invoice"] = invoice
-	}
-	data["showData"] = sData
-	this.ServeJson(map[string]interface{}{
-		"data": data,
-	})
+    stype := this.GetString("stype")
+    code := this.GetString("code")
+    data := make(map[string]interface{})
+    var sData map[string]interface{}
+    switch stype {
+    case "1": //订单回显金额
+        payMoney, phone := ResidueMoney(code)
+        data["pay_money"] = payMoney
+        sData = ShowData(phone)
+    case "2": //发票信息回显
+        invoice := util.Mysql.FindOne("invoice", map[string]interface{}{"id": encrypt.SE.Decode4Hex(code)}, "id,only_Identifying,order_code,invoice_order_code,invoice_money,remark,invoice_type,invoice_content,invoice_variety,company_name,phone,mail,taxpayer_identnum,invoice_money,invoice_order_money,company_address,bank_name,recipient,delivery_address,bank_account,company_phone", "")
+        if invoice != nil {
+            (*invoice)["id"] = code
+            if (*invoice)["invoice_order_code"] != nil {
+                (*invoice)["order_code"] = (*invoice)["invoice_order_code"]
+            }
+            (*invoice)["only_Identifying"] = encrypt.SE.EncodeString(qutil.InterfaceToStr((*invoice)["only_Identifying"]))
+        }
+        data["invoice"] = invoice
+    }
+    data["showData"] = sData
+    this.ServeJson(map[string]interface{}{
+        "data": data,
+    })
 }
 
 // 开发票回调
 func (this *Invoice) Callbackinvoice() {
-	isRed, _ := this.GetBool("isRed")
-	resType := this.GetString("resType") //红票回调-->"changed":换票 "refund":退票
-	order_code := this.GetString("order_code")
-	applyBill_status := this.GetString("code")
-	fpdm := this.GetString("fpdm")
-	fphm := this.GetString("fphm")
-	path := this.GetString("path")
-	swno := this.GetString("swno")
-	changed := this.GetString("changed")
-	isSys, _ := this.GetBool("isSys") //是否发票系统故障
-	if isSys {
-		q := map[string]interface{}{}
-		q["order_code"] = order_code
-		q["invoice_changed"], _ = strconv.Atoi(changed)
-		sysMap := map[string]interface{}{"invoice_status": -1}
-		ok := util.Mysql.Update(dbname, q, sysMap)
-		if ok {
-			this.ServeJson(map[string]interface{}{
-				"msg":    "发票系统故障回调成功",
-				"status": "success",
-			})
-		}
-		return
-	}
-	if !isRed {
-		if order_code != "" {
-			if changed == "1" {
-				m := make(map[string]interface{})
-				query := make(map[string]interface{})
-				query["order_code"] = order_code
-				query["invoice_changed"] = 1
-				m["invoice_code"] = fpdm
-				m["invoice_number"] = fphm
-				m["url"] = "http://" + path
-				m["invoice_serialnum"] = swno
-				m["invoice_status"] = applyBill_status
-				m["billing_time"] = time.Now().Unix()
-				updata_status := util.Mysql.Update(dbname, query, m)
-				if updata_status {
-					user_info := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "user_nickname,user_mail", "")
-					res := util.Mysql.FindOne(dbname, query, "invoice_type,mail,taxpayer_identnum,company_name,phone,url", "")
-					if (*res)["invoice_type"] == "个人" {
-						go func() {
-							var user_mail string
-							if (*res)["mail"] == nil {
-								user_mail = (*user_info)["user_mail"].(string)
-							} else {
-								user_mail = (*res)["mail"].(string)
-							}
-							var url string
-							if (*res)["url"] == nil {
-								url = "http://" + path
-							} else {
-								url = (*res)["url"].(string)
-							}
-							emailHtml := emailHtml_gr
-							emailHtmls := fmt.Sprintf(emailHtml, (*res)["phone"], user_mail)
-							html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
-							InvoiceSendMail(user_mail, html, "电子发票")
-						}()
-					} else {
-						var company_mail string
-						if (*res)["mail"] == nil {
-							company_mail = (*user_info)["user_mail"].(string)
-						} else {
-							company_mail = (*res)["mail"].(string)
-						}
-						var url string
-						if (*res)["url"] == nil {
-							url = "http://" + path
-						} else {
-							url = (*res)["url"].(string)
-						}
-						emailHtml := emailHtml_gs
-						emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], company_mail)
-						if strings.Contains(order_code, "xx") {
-							//自助开票
-							orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
-							if len(*orderCodeArr) > 0 {
-								order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
-								for _, v := range strings.Split(order_code, ",") {
-									//订单信息保存
-									updateData := map[string]interface{}{}
-									if InvoiceStatusHandle(v) {
-										updateData["applybill_status"] = 2
-									} else {
-										updateData["applybill_status"] = 3
-									}
-									util.Mysql.Update("dataexport_order", map[string]interface{}{
-										"order_code": v,
-									}, updateData)
-								}
-							}
-						}
-						html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
-						InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
-
-					}
-					this.ServeJson(map[string]interface{}{
-						"msg":    "状态修改成功",
-						"status": "success",
-					})
-				}
-			} else {
-				t := make(map[string]interface{})
-
-				if strings.Contains(order_code, "xx") {
-					//自助开票
-					t["only_Identifying"] = order_code
-				} else {
-					//系统开票
-					t["order_code"] = order_code
-				}
-				t["invoice_changed"] = 0
-				user_info := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "user_nickname,user_mail", "")
-				res := util.Mysql.FindOne(dbname, t, "invoice_type,mail,taxpayer_identnum,company_name,phone,url", "")
-				if res != nil {
-					m := make(map[string]interface{})
-					query := make(map[string]interface{})
-					if strings.Contains(order_code, "xx") {
-						//自助开票
-						query["only_Identifying"] = order_code
-					} else {
-						//系统开票
-						query["order_code"] = order_code
-					}
-					query["invoice_changed"] = 0
-					m["invoice_code"] = fpdm
-					m["invoice_number"] = fphm
-					m["url"] = "http://" + path
-					m["invoice_serialnum"] = swno
-					m["invoice_status"] = applyBill_status
-					m["billing_time"] = time.Now().Unix()
-					updata_status := util.Mysql.Update(dbname, query, m)
-					if updata_status {
-						if (*res)["invoice_type"] == "个人" {
-							go func() {
-								var user_mail string
-								if (*res)["mail"] == nil {
-									user_mail = (*user_info)["user_mail"].(string)
-								} else {
-									user_mail = (*res)["mail"].(string)
-								}
-								var url string
-								if (*res)["url"] == nil {
-									url = "http://" + path
-								} else {
-									url = (*res)["url"].(string)
-								}
-								emailHtml := emailHtml_gr
-								emailHtmls := fmt.Sprintf(emailHtml, (*res)["phone"], user_mail)
-								if strings.Contains(order_code, "xx") {
-									//自助开票
-									orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
-									if len(*orderCodeArr) > 0 {
-										order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
-										for _, v := range strings.Split(order_code, ",") {
-											//订单信息保存
-											updateData := map[string]interface{}{}
-											if InvoiceStatusHandle(v) {
-												updateData["applybill_status"] = 2
-											} else {
-												updateData["applybill_status"] = 3
-											}
-											util.Mysql.Update("dataexport_order", map[string]interface{}{
-												"order_code": v,
-											}, updateData)
-										}
-									}
-
-								}
-								html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
-								InvoiceSendMail(user_mail, html, "电子发票")
-
-							}()
-
-						} else {
-							var company_mail string
-							if (*res)["mail"] == nil {
-								company_mail = (*user_info)["user_mail"].(string)
-							} else {
-								company_mail = (*res)["mail"].(string)
-							}
-							var url string
-							if (*res)["url"] == nil {
-								url = "http://" + path
-							} else {
-								url = (*res)["url"].(string)
-							}
-							emailHtml := emailHtml_gs
-							emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], company_mail)
-							if strings.Contains(order_code, "xx") {
-								//自助开票
-								orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
-								if len(*orderCodeArr) > 0 {
-									order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
-									for _, v := range strings.Split(order_code, ",") {
-										//订单信息保存
-										updateData := map[string]interface{}{}
-										if InvoiceStatusHandle(v) {
-											updateData["applybill_status"] = 2
-										} else {
-											updateData["applybill_status"] = 3
-										}
-										util.Mysql.Update("dataexport_order", map[string]interface{}{
-											"order_code": v,
-										}, updateData)
-									}
-								}
-
-							}
-							html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
-							InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
-
-						}
-						this.ServeJson(map[string]interface{}{
-							"msg":    "状态修改成功",
-							"status": "success",
-						})
-					}
-
-				} else {
-					this.ServeJson(map[string]interface{}{
-						"msg":    "订单不存在",
-						"status": "fail",
-					})
-				}
-			}
-
-		} else {
-			this.ServeJson(map[string]interface{}{
-				"msg":    "参数缺失",
-				"status": "fail",
-			})
-		}
-	} else {
-		redMap := map[string]interface{}{}
-		query := map[string]interface{}{}
-		if order_code != "" {
-			query["order_code"] = order_code
-			red := RedMsg{
-				fpdm,
-				fphm,
-				"http://" + path,
-				swno,
-				applyBill_status,
-				time.Now().Unix(),
-			}
-			redStr, _ := json.Marshal(red)
-			redMap["red"] = redStr
-			redMap["invoice_status"] = -2
-		}
-		if resType == "changed" {
-			query["invoice_changed"] = 0
-			ok := util.Mysql.Update(dbname, query, redMap)
-			if ok {
-				this.ServeJson(map[string]interface{}{
-					"msg":    "用户换票冲红保存成功",
-					"status": "success",
-				})
-			}
-		} else if resType == "refund" {
-			data := util.Mysql.Find(dbname, query, "", "create_time", 0, 0)
-			if len(*data) == 2 {
-				query["invoice_changed"] = 1
-			} else {
-				query["invoice_changed"] = 0
-			}
-			ok := util.Mysql.Update(dbname, query, redMap)
-			if ok {
-				this.ServeJson(map[string]interface{}{
-					"msg":    "用户退款冲红保存成功",
-					"status": "success",
-				})
-			}
-		}
-	}
+    isRed, _ := this.GetBool("isRed")
+    resType := this.GetString("resType") //红票回调-->"changed":换票 "refund":退票
+    order_code := this.GetString("order_code")
+    applyBill_status := this.GetString("code")
+    fpdm := this.GetString("fpdm")
+    fphm := this.GetString("fphm")
+    path := this.GetString("path")
+    swno := this.GetString("swno")
+    changed := this.GetString("changed")
+    isSys, _ := this.GetBool("isSys") //是否发票系统故障
+    if isSys {
+        q := map[string]interface{}{}
+        q["order_code"] = order_code
+        q["invoice_changed"], _ = strconv.Atoi(changed)
+        sysMap := map[string]interface{}{"invoice_status": -1}
+        ok := util.Mysql.Update(dbname, q, sysMap)
+        if ok {
+            this.ServeJson(map[string]interface{}{
+                "msg":    "发票系统故障回调成功",
+                "status": "success",
+            })
+        }
+        return
+    }
+    if !isRed {
+        if order_code != "" {
+            if changed == "1" {
+                m := make(map[string]interface{})
+                query := make(map[string]interface{})
+                query["order_code"] = order_code
+                query["invoice_changed"] = 1
+                m["invoice_code"] = fpdm
+                m["invoice_number"] = fphm
+                m["url"] = "http://" + path
+                m["invoice_serialnum"] = swno
+                m["invoice_status"] = applyBill_status
+                m["billing_time"] = time.Now().Unix()
+                updata_status := util.Mysql.Update(dbname, query, m)
+                if updata_status {
+                    user_info := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "user_nickname,user_mail", "")
+                    res := util.Mysql.FindOne(dbname, query, "invoice_type,mail,taxpayer_identnum,company_name,phone,url", "")
+                    if (*res)["invoice_type"] == "个人" {
+                        go func() {
+                            var user_mail string
+                            if (*res)["mail"] == nil {
+                                user_mail = (*user_info)["user_mail"].(string)
+                            } else {
+                                user_mail = (*res)["mail"].(string)
+                            }
+                            var url string
+                            if (*res)["url"] == nil {
+                                url = "http://" + path
+                            } else {
+                                url = (*res)["url"].(string)
+                            }
+                            emailHtml := emailHtml_gr
+                            emailHtmls := fmt.Sprintf(emailHtml, (*res)["phone"], user_mail)
+                            html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
+                            InvoiceSendMail(user_mail, html, "电子发票")
+                        }()
+                    } else {
+                        var company_mail string
+                        if (*res)["mail"] == nil {
+                            company_mail = (*user_info)["user_mail"].(string)
+                        } else {
+                            company_mail = (*res)["mail"].(string)
+                        }
+                        var url string
+                        if (*res)["url"] == nil {
+                            url = "http://" + path
+                        } else {
+                            url = (*res)["url"].(string)
+                        }
+                        emailHtml := emailHtml_gs
+                        emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], company_mail)
+                        if strings.Contains(order_code, "xx") {
+                            //自助开票
+                            orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
+                            if len(*orderCodeArr) > 0 {
+                                order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
+                                for _, v := range strings.Split(order_code, ",") {
+                                    //订单信息保存
+                                    updateData := map[string]interface{}{}
+                                    if InvoiceStatusHandle(v) {
+                                        updateData["applybill_status"] = 2
+                                    } else {
+                                        updateData["applybill_status"] = 3
+                                    }
+                                    util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                        "order_code": v,
+                                    }, updateData)
+                                }
+                            }
+                        }
+                        html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
+                        InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
+
+                    }
+                    this.ServeJson(map[string]interface{}{
+                        "msg":    "状态修改成功",
+                        "status": "success",
+                    })
+                }
+            } else {
+                t := make(map[string]interface{})
+
+                if strings.Contains(order_code, "xx") {
+                    //自助开票
+                    t["only_Identifying"] = order_code
+                } else {
+                    //系统开票
+                    t["order_code"] = order_code
+                }
+                t["invoice_changed"] = 0
+                user_info := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "user_nickname,user_mail", "")
+                res := util.Mysql.FindOne(dbname, t, "invoice_type,mail,taxpayer_identnum,company_name,phone,url", "")
+                if res != nil {
+                    m := make(map[string]interface{})
+                    query := make(map[string]interface{})
+                    if strings.Contains(order_code, "xx") {
+                        //自助开票
+                        query["only_Identifying"] = order_code
+                    } else {
+                        //系统开票
+                        query["order_code"] = order_code
+                    }
+                    query["invoice_changed"] = 0
+                    m["invoice_code"] = fpdm
+                    m["invoice_number"] = fphm
+                    m["url"] = "http://" + path
+                    m["invoice_serialnum"] = swno
+                    m["invoice_status"] = applyBill_status
+                    m["billing_time"] = time.Now().Unix()
+                    updata_status := util.Mysql.Update(dbname, query, m)
+                    if updata_status {
+                        if (*res)["invoice_type"] == "个人" {
+                            go func() {
+                                var user_mail string
+                                if (*res)["mail"] == nil {
+                                    user_mail = (*user_info)["user_mail"].(string)
+                                } else {
+                                    user_mail = (*res)["mail"].(string)
+                                }
+                                var url string
+                                if (*res)["url"] == nil {
+                                    url = "http://" + path
+                                } else {
+                                    url = (*res)["url"].(string)
+                                }
+                                emailHtml := emailHtml_gr
+                                emailHtmls := fmt.Sprintf(emailHtml, (*res)["phone"], user_mail)
+                                if strings.Contains(order_code, "xx") {
+                                    //自助开票
+                                    orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
+                                    if len(*orderCodeArr) > 0 {
+                                        order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
+                                        for _, v := range strings.Split(order_code, ",") {
+                                            //订单信息保存
+                                            updateData := map[string]interface{}{}
+                                            if InvoiceStatusHandle(v) {
+                                                updateData["applybill_status"] = 2
+                                            } else {
+                                                updateData["applybill_status"] = 3
+                                            }
+                                            util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                                "order_code": v,
+                                            }, updateData)
+                                        }
+                                    }
+
+                                }
+                                html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
+                                InvoiceSendMail(user_mail, html, "电子发票")
+
+                            }()
+
+                        } else {
+                            var company_mail string
+                            if (*res)["mail"] == nil {
+                                company_mail = (*user_info)["user_mail"].(string)
+                            } else {
+                                company_mail = (*res)["mail"].(string)
+                            }
+                            var url string
+                            if (*res)["url"] == nil {
+                                url = "http://" + path
+                            } else {
+                                url = (*res)["url"].(string)
+                            }
+                            emailHtml := emailHtml_gs
+                            emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], company_mail)
+                            if strings.Contains(order_code, "xx") {
+                                //自助开票
+                                orderCodeArr := util.Mysql.SelectBySql("select   GROUP_CONCAT(order_code) as  order_code  from   invoice  where  only_Identifying=?", order_code)
+                                if len(*orderCodeArr) > 0 {
+                                    order_code = qutil.ObjToString((*orderCodeArr)[0]["order_code"])
+                                    for _, v := range strings.Split(order_code, ",") {
+                                        //订单信息保存
+                                        updateData := map[string]interface{}{}
+                                        if InvoiceStatusHandle(v) {
+                                            updateData["applybill_status"] = 2
+                                        } else {
+                                            updateData["applybill_status"] = 3
+                                        }
+                                        util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                            "order_code": v,
+                                        }, updateData)
+                                    }
+                                }
+
+                            }
+                            html := fmt.Sprintf(email_format, order_code, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">下载发票</a>", url), "电子普通发票", emailHtmls)
+                            InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
+
+                        }
+                        this.ServeJson(map[string]interface{}{
+                            "msg":    "状态修改成功",
+                            "status": "success",
+                        })
+                    }
+
+                } else {
+                    this.ServeJson(map[string]interface{}{
+                        "msg":    "订单不存在",
+                        "status": "fail",
+                    })
+                }
+            }
+
+        } else {
+            this.ServeJson(map[string]interface{}{
+                "msg":    "参数缺失",
+                "status": "fail",
+            })
+        }
+    } else {
+        redMap := map[string]interface{}{}
+        query := map[string]interface{}{}
+        if order_code != "" {
+            query["order_code"] = order_code
+            red := RedMsg{
+                fpdm,
+                fphm,
+                "http://" + path,
+                swno,
+                applyBill_status,
+                time.Now().Unix(),
+            }
+            redStr, _ := json.Marshal(red)
+            redMap["red"] = redStr
+            redMap["invoice_status"] = -2
+        }
+        if resType == "changed" {
+            query["invoice_changed"] = 0
+            ok := util.Mysql.Update(dbname, query, redMap)
+            if ok {
+                this.ServeJson(map[string]interface{}{
+                    "msg":    "用户换票冲红保存成功",
+                    "status": "success",
+                })
+            }
+        } else if resType == "refund" {
+            data := util.Mysql.Find(dbname, query, "", "create_time", 0, 0)
+            if len(*data) == 2 {
+                query["invoice_changed"] = 1
+            } else {
+                query["invoice_changed"] = 0
+            }
+            ok := util.Mysql.Update(dbname, query, redMap)
+            if ok {
+                this.ServeJson(map[string]interface{}{
+                    "msg":    "用户退款冲红保存成功",
+                    "status": "success",
+                })
+            }
+        }
+    }
 }
 
 // 换票
 func (this *Invoice) Replaceinvoice() {
-	//红冲开关
-	if !config.InvoiceConfig.Red_invoice_switch {
-		this.ServeJson(map[string]interface{}{
-			"invoice_status": -1,
-			"invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
-		})
-		return
-	}
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	order_code := this.GetString("order_code")
-	isSys, _ := this.GetBool("isSys")
-	res := util.Mysql.FindOne(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId, "invoice_changed": 0}, "", "") //仅线上开发票可换票
-	if res != nil {
-		order_res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId, "applyBill_status": map[string]interface{}{"ne": 2}}, "order_money,product_type,user_nickname,user_mail", "")
-		invoice_type := this.GetString("invoice_type")
-		phone := this.GetString("phone_num")
-		e_mail := this.GetString("email")
-		company_name := this.GetString("company")
-		id_num := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
-		if invoice_type == "个人" {
-			if phone == (*res)["phone"] && e_mail == (*res)["mail"] && (*res)["invoice_type"] == "个人" {
-				emailHtml := emailHtml_gr
-				emailHtmls := fmt.Sprintf(emailHtml, phone, e_mail)
-				html := fmt.Sprintf(email_format, order_code, (*res)["url"], emailHtmls)
-				m := make(map[string]interface{})
-				m["order_code"] = order_code
-				m["invoice_changed"] = 1
-				m["invoice_code"] = (*res)["invoice_code"]
-				m["invoice_number"] = (*res)["invoice_number"]
-				m["url"] = (*res)["url"]
-				m["invoice_serialnum"] = (*res)["invoice_serialnum"]
-				m["invoice_status"] = 1
-				m["billing_time"] = time.Now().Unix()
-				m["mail"] = (*res)["mail"]
-				m["phone"] = (*res)["phone"]
-				m["invoice_type"] = (*res)["invoice_type"]
-				m["company_name"] = (*res)["company_name"]
-				m["taxpayer_identnum"] = (*res)["taxpayer_identnum"]
-				m["create_time"] = time.Now().Unix()
-				m["product_type"] = (*res)["product_type"]
-				m["user_id"] = userId
-				if !isSys {
-					status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-					if len(*status) > 1 {
-						return
-					}
-					order_id := util.Mysql.Insert(dbname, m)
-					if order_id != -1 {
-						this.ServeJson(map[string]interface{}{
-							"invoice_status": 1,
-						})
-					}
-				} else {
-					query := map[string]interface{}{}
-					query["user_id"] = userId
-					query["order_code"] = order_code
-					query["invoice_changed"] = 1
-					ok := util.Mysql.Update(dbname, query, m)
-					if ok {
-						this.ServeJson(map[string]interface{}{
-							"invoice_status": 1,
-						})
-					}
-				}
-				InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
-				return
-			}
-		} else {
-			if phone == (*res)["phone"] && e_mail == (*res)["mail"] && id_num == (*res)["taxpayer_identnum"] && company_name == (*res)["company_name"] && (*res)["invoice_type"] == "单位" {
-				emailHtml := emailHtml_gs
-				emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], e_mail)
-				html := fmt.Sprintf(email_format, order_code, (*res)["url"], emailHtmls)
-				m := make(map[string]interface{})
-				m["order_code"] = order_code
-				m["invoice_changed"] = 1
-				m["invoice_code"] = (*res)["invoice_code"]
-				m["invoice_number"] = (*res)["invoice_number"]
-				m["url"] = (*res)["url"]
-				m["invoice_serialnum"] = (*res)["invoice_serialnum"]
-				m["invoice_status"] = 1
-				m["billing_time"] = time.Now().Unix()
-				m["mail"] = (*res)["mail"]
-				m["phone"] = (*res)["phone"]
-				m["invoice_type"] = (*res)["invoice_type"]
-				m["company_name"] = (*res)["company_name"]
-				m["taxpayer_identnum"] = (*res)["taxpayer_identnum"]
-				m["create_time"] = time.Now().Unix()
-				m["product_type"] = (*res)["product_type"]
-				m["user_id"] = userId
-				if !isSys {
-					status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-					if len(*status) > 1 {
-						return
-					}
-					order_id := util.Mysql.Insert(dbname, m)
-					if order_id != -1 {
-						this.ServeJson(map[string]interface{}{
-							"invoice_status": 1,
-						})
-					}
-				} else {
-					query := map[string]interface{}{}
-					query["user_id"] = userId
-					query["order_code"] = order_code
-					query["invoice_changed"] = 1
-					ok := util.Mysql.Update(dbname, query, m)
-					if ok {
-						this.ServeJson(map[string]interface{}{
-							"invoice_status": 1,
-						})
-					}
-				}
-				InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
-				return
-			}
-		}
-		invoice_status := 0
-		dataexport_data := make(map[string]interface{})
-		if invoice_type == "个人" {
-			dataexport_data["applyBill_type"] = 0
-			dataexport_data["applyBill_taxnum"] = ""
-			dataexport_data["applybill_company"] = ""
-		} else {
-			dataexport_data["applyBill_type"] = 1
-			dataexport_data["applyBill_taxnum"] = id_num
-			dataexport_data["applybill_company"] = company_name
-		}
-		dataexport_data["user_mail"] = e_mail
-		util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data)
-		data := make(map[string]interface{})
-		data["order_code"] = order_code
-		data["mail"] = e_mail
-		data["phone"] = phone
-		data["invoice_type"] = invoice_type
-		data["company_name"] = company_name
-		data["taxpayer_identnum"] = id_num
-		data["invoice_changed"] = 1
-		data["create_time"] = time.Now().Unix()
-		data["user_id"] = userId
-		data["invoice_status"] = invoice_status
-		data["product_type"] = (*res)["product_type"]
-		if !isSys {
-			status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-			if len(*status) == 0 {
-				if id := util.Mysql.Insert(dbname, data); id > 0 {
-					invoice_status = 1
-				}
-			} else {
-				invoice_status = 1
-			}
-		} else {
-			if ok := util.Mysql.Update(dbname, map[string]interface{}{
-				"order_code":      order_code,
-				"user_id":         userId,
-				"invoice_changed": 1,
-			}, data); ok {
-				invoice_status = 1
-			}
-		}
-		if !config.InvoiceConfig.Third_party_switch {
-			this.ServeJson(map[string]interface{}{
-				"invoice_status": invoice_status,
-			})
-			return
-		}
-		var orders = []map[string]interface{}{}
-		var items = []map[string]interface{}{}
-		prices := qutil.Float64All((*order_res)["order_money"]) / float64(100)
-		price := strconv.FormatFloat(prices, 'f', -1, 64)
-		item := map[string]interface{}{
-			"name":        (*order_res)["product_type"],
-			"code":        config.InvoiceConfig.Code,
-			"yhzcbs":      config.InvoiceConfig.Tax_policy,
-			"lineType":    config.InvoiceConfig.Invoice_nature,
-			"taxRate":     config.InvoiceConfig.Tax_rate,
-			"taxPrice":    price,
-			"totalAmount": price,
-			"quantity":    "1",
-			"phone":       phone,
-			"billDate":    NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
-		}
-		items = append(items, item)
-		order := map[string]interface{}{
-			"billNo": order_code,
-			"items":  items,
-		}
-		orders = append(orders, order)
-		client := &http.Client{}
-		body := map[string]interface{}{
-			"Swno":      order_code,
-			"custType":  "03",
-			"orders":    orders,
-			"custTaxNo": id_num,
-			"yfphm":     (*res)["invoice_number"],
-			"yfpdm":     (*res)["invoice_code"],
-			"changed":   "1",
-			"phone":     phone,
-			"redcode":   (*res)["invoice_serialnum"],
-		}
-		if invoice_type == "单位" {
-			body["custName"] = company_name
-		} else {
-			body["custName"] = invoice_type
-		}
-		b, _ := json.Marshal(body)
-		buffer := bytes.NewBuffer(b)
-		request, err := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Replace", buffer)
-		if err == nil {
-			var invoice_status = 0
-			invoice_res := &InvoiceInfo{}
-			response, err1 := client.Do(request)
-			if err1 != nil {
-				invoice_status = -1
-			} else {
-				res, err := ioutil.ReadAll(response.Body)
-				defer response.Body.Close()
-				if err != nil {
-					invoice_status = -1
-				} else {
-					resMap := qutil.ObjToMap(string(res))
-					if *resMap != nil {
-						if qutil.IntAll((*resMap)["code"]) == 1 {
-							invoice_status = -1
-						}
-					}
-					err := json.Unmarshal(res, invoice_res)
-					if err != nil {
-						log.Println("序列化出错", err)
-					} else {
-						if invoice_res.data["path"] != nil {
-							invoice_status = 1
-						}
-						if invoice_res == nil {
-							invoice_status = -1
-						}
-					}
-				}
-			}
-			updata_status := true
-			if invoice_status == -1 {
-				if !delReplaceInvoice(map[string]interface{}{"order_code": order_code, "invoice_changed": 1}) {
-					log.Printf("delete replace invoice err: %s", order_code)
-				}
-			} else {
-				updata_status = util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code, "invoice_changed": 1}, map[string]interface{}{
-					"invoice_serialnum": invoice_res.data["swno"],
-					"invoice_code":      invoice_res.data["fpdm"],
-					"invoice_number":    invoice_res.data["fphm"],
-					"url":               invoice_res.data["path"],
-					"invoice_status":    invoice_status,
-				})
-			}
-			if updata_status {
-				this.ServeJson(map[string]interface{}{
-					"invoice_status": invoice_status,
-				})
-			} else {
-				this.ServeJson(map[string]interface{}{
-					"invoice_status": 0,
-				})
-			}
-		} else {
-			go func() {
-				//删除该错误发票信息
-				// util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code, "invoice_changed": 1}, map[string]interface{}{
-				// 	"invoice_status": -1,
-				// })
-				if !delReplaceInvoice(map[string]interface{}{"order_code": order_code, "invoice_changed": 1}) {
-					log.Printf("delete go func replace invoice err: %s", order_code)
-				}
-			}()
-
-			this.ServeJson(map[string]interface{}{
-				"invoice_status": -1,
-			})
-		}
-	}
+    //红冲开关
+    if !config.InvoiceConfig.Red_invoice_switch {
+        this.ServeJson(map[string]interface{}{
+            "invoice_status": -1,
+            "invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
+        })
+        return
+    }
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    order_code := this.GetString("order_code")
+    isSys, _ := this.GetBool("isSys")
+    res := util.Mysql.FindOne(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId, "invoice_changed": 0}, "", "") //仅线上开发票可换票
+    if res != nil {
+        order_res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId, "applyBill_status": map[string]interface{}{"ne": 2}}, "order_money,product_type,user_nickname,user_mail", "")
+        invoice_type := this.GetString("invoice_type")
+        phone := this.GetString("phone_num")
+        e_mail := this.GetString("email")
+        company_name := this.GetString("company")
+        id_num := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
+        if invoice_type == "个人" {
+            if phone == (*res)["phone"] && e_mail == (*res)["mail"] && (*res)["invoice_type"] == "个人" {
+                emailHtml := emailHtml_gr
+                emailHtmls := fmt.Sprintf(emailHtml, phone, e_mail)
+                html := fmt.Sprintf(email_format, order_code, (*res)["url"], emailHtmls)
+                m := make(map[string]interface{})
+                m["order_code"] = order_code
+                m["invoice_changed"] = 1
+                m["invoice_code"] = (*res)["invoice_code"]
+                m["invoice_number"] = (*res)["invoice_number"]
+                m["url"] = (*res)["url"]
+                m["invoice_serialnum"] = (*res)["invoice_serialnum"]
+                m["invoice_status"] = 1
+                m["billing_time"] = time.Now().Unix()
+                m["mail"] = (*res)["mail"]
+                m["phone"] = (*res)["phone"]
+                m["invoice_type"] = (*res)["invoice_type"]
+                m["company_name"] = (*res)["company_name"]
+                m["taxpayer_identnum"] = (*res)["taxpayer_identnum"]
+                m["create_time"] = time.Now().Unix()
+                m["product_type"] = (*res)["product_type"]
+                m["user_id"] = userId
+                if !isSys {
+                    status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+                    if len(*status) > 1 {
+                        return
+                    }
+                    order_id := util.Mysql.Insert(dbname, m)
+                    if order_id != -1 {
+                        this.ServeJson(map[string]interface{}{
+                            "invoice_status": 1,
+                        })
+                    }
+                } else {
+                    query := map[string]interface{}{}
+                    query["user_id"] = userId
+                    query["order_code"] = order_code
+                    query["invoice_changed"] = 1
+                    ok := util.Mysql.Update(dbname, query, m)
+                    if ok {
+                        this.ServeJson(map[string]interface{}{
+                            "invoice_status": 1,
+                        })
+                    }
+                }
+                InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
+                return
+            }
+        } else {
+            if phone == (*res)["phone"] && e_mail == (*res)["mail"] && id_num == (*res)["taxpayer_identnum"] && company_name == (*res)["company_name"] && (*res)["invoice_type"] == "单位" {
+                emailHtml := emailHtml_gs
+                emailHtmls := fmt.Sprintf(emailHtml, (*res)["company_name"], (*res)["taxpayer_identnum"], (*res)["phone"], e_mail)
+                html := fmt.Sprintf(email_format, order_code, (*res)["url"], emailHtmls)
+                m := make(map[string]interface{})
+                m["order_code"] = order_code
+                m["invoice_changed"] = 1
+                m["invoice_code"] = (*res)["invoice_code"]
+                m["invoice_number"] = (*res)["invoice_number"]
+                m["url"] = (*res)["url"]
+                m["invoice_serialnum"] = (*res)["invoice_serialnum"]
+                m["invoice_status"] = 1
+                m["billing_time"] = time.Now().Unix()
+                m["mail"] = (*res)["mail"]
+                m["phone"] = (*res)["phone"]
+                m["invoice_type"] = (*res)["invoice_type"]
+                m["company_name"] = (*res)["company_name"]
+                m["taxpayer_identnum"] = (*res)["taxpayer_identnum"]
+                m["create_time"] = time.Now().Unix()
+                m["product_type"] = (*res)["product_type"]
+                m["user_id"] = userId
+                if !isSys {
+                    status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+                    if len(*status) > 1 {
+                        return
+                    }
+                    order_id := util.Mysql.Insert(dbname, m)
+                    if order_id != -1 {
+                        this.ServeJson(map[string]interface{}{
+                            "invoice_status": 1,
+                        })
+                    }
+                } else {
+                    query := map[string]interface{}{}
+                    query["user_id"] = userId
+                    query["order_code"] = order_code
+                    query["invoice_changed"] = 1
+                    ok := util.Mysql.Update(dbname, query, m)
+                    if ok {
+                        this.ServeJson(map[string]interface{}{
+                            "invoice_status": 1,
+                        })
+                    }
+                }
+                InvoiceSendMail((*res)["mail"].(string), html, "电子发票")
+                return
+            }
+        }
+        invoice_status := 0
+        dataexport_data := make(map[string]interface{})
+        if invoice_type == "个人" {
+            dataexport_data["applyBill_type"] = 0
+            dataexport_data["applyBill_taxnum"] = ""
+            dataexport_data["applybill_company"] = ""
+        } else {
+            dataexport_data["applyBill_type"] = 1
+            dataexport_data["applyBill_taxnum"] = id_num
+            dataexport_data["applybill_company"] = company_name
+        }
+        dataexport_data["user_mail"] = e_mail
+        util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data)
+        data := make(map[string]interface{})
+        data["order_code"] = order_code
+        data["mail"] = e_mail
+        data["phone"] = phone
+        data["invoice_type"] = invoice_type
+        data["company_name"] = company_name
+        data["taxpayer_identnum"] = id_num
+        data["invoice_changed"] = 1
+        data["create_time"] = time.Now().Unix()
+        data["user_id"] = userId
+        data["invoice_status"] = invoice_status
+        data["product_type"] = (*res)["product_type"]
+        if !isSys {
+            status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+            if len(*status) == 0 {
+                if id := util.Mysql.Insert(dbname, data); id > 0 {
+                    invoice_status = 1
+                }
+            } else {
+                invoice_status = 1
+            }
+        } else {
+            if ok := util.Mysql.Update(dbname, map[string]interface{}{
+                "order_code":      order_code,
+                "user_id":         userId,
+                "invoice_changed": 1,
+            }, data); ok {
+                invoice_status = 1
+            }
+        }
+        if !config.InvoiceConfig.Third_party_switch {
+            this.ServeJson(map[string]interface{}{
+                "invoice_status": invoice_status,
+            })
+            return
+        }
+        var orders = []map[string]interface{}{}
+        var items = []map[string]interface{}{}
+        prices := qutil.Float64All((*order_res)["order_money"]) / float64(100)
+        price := strconv.FormatFloat(prices, 'f', -1, 64)
+        item := map[string]interface{}{
+            "name":        (*order_res)["product_type"],
+            "code":        config.InvoiceConfig.Code,
+            "yhzcbs":      config.InvoiceConfig.Tax_policy,
+            "lineType":    config.InvoiceConfig.Invoice_nature,
+            "taxRate":     config.InvoiceConfig.Tax_rate,
+            "taxPrice":    price,
+            "totalAmount": price,
+            "quantity":    "1",
+            "phone":       phone,
+            "billDate":    NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
+        }
+        items = append(items, item)
+        order := map[string]interface{}{
+            "billNo": order_code,
+            "items":  items,
+        }
+        orders = append(orders, order)
+        client := &http.Client{}
+        body := map[string]interface{}{
+            "Swno":      order_code,
+            "custType":  "03",
+            "orders":    orders,
+            "custTaxNo": id_num,
+            "yfphm":     (*res)["invoice_number"],
+            "yfpdm":     (*res)["invoice_code"],
+            "changed":   "1",
+            "phone":     phone,
+            "redcode":   (*res)["invoice_serialnum"],
+        }
+        if invoice_type == "单位" {
+            body["custName"] = company_name
+        } else {
+            body["custName"] = invoice_type
+        }
+        b, _ := json.Marshal(body)
+        buffer := bytes.NewBuffer(b)
+        request, err := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Replace", buffer)
+        if err == nil {
+            var invoice_status = 0
+            invoice_res := &InvoiceInfo{}
+            response, err1 := client.Do(request)
+            if err1 != nil {
+                invoice_status = -1
+            } else {
+                res, err := ioutil.ReadAll(response.Body)
+                defer response.Body.Close()
+                if err != nil {
+                    invoice_status = -1
+                } else {
+                    resMap := qutil.ObjToMap(string(res))
+                    if *resMap != nil {
+                        if qutil.IntAll((*resMap)["code"]) == 1 {
+                            invoice_status = -1
+                        }
+                    }
+                    err := json.Unmarshal(res, invoice_res)
+                    if err != nil {
+                        log.Println("序列化出错", err)
+                    } else {
+                        if invoice_res.data["path"] != nil {
+                            invoice_status = 1
+                        }
+                        if invoice_res == nil {
+                            invoice_status = -1
+                        }
+                    }
+                }
+            }
+            updata_status := true
+            if invoice_status == -1 {
+                if !delReplaceInvoice(map[string]interface{}{"order_code": order_code, "invoice_changed": 1}) {
+                    log.Printf("delete replace invoice err: %s", order_code)
+                }
+            } else {
+                updata_status = util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code, "invoice_changed": 1}, map[string]interface{}{
+                    "invoice_serialnum": invoice_res.data["swno"],
+                    "invoice_code":      invoice_res.data["fpdm"],
+                    "invoice_number":    invoice_res.data["fphm"],
+                    "url":               invoice_res.data["path"],
+                    "invoice_status":    invoice_status,
+                })
+            }
+            if updata_status {
+                this.ServeJson(map[string]interface{}{
+                    "invoice_status": invoice_status,
+                })
+            } else {
+                this.ServeJson(map[string]interface{}{
+                    "invoice_status": 0,
+                })
+            }
+        } else {
+            go func() {
+                //删除该错误发票信息
+                // util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code, "invoice_changed": 1}, map[string]interface{}{
+                // 	"invoice_status": -1,
+                // })
+                if !delReplaceInvoice(map[string]interface{}{"order_code": order_code, "invoice_changed": 1}) {
+                    log.Printf("delete go func replace invoice err: %s", order_code)
+                }
+            }()
+
+            this.ServeJson(map[string]interface{}{
+                "invoice_status": -1,
+            })
+        }
+    }
 
 }
 
 // 新换票
 func (this *Invoice) NewReplaceinvoice() {
-	//红冲开关
-	if !config.InvoiceConfig.Red_invoice_switch {
-		this.ServeJson(map[string]interface{}{
-			"invoice_status": -1,
-			"invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
-		})
-		return
-	}
-	invoice_type := this.GetString("invoice_type")
-	phone := this.GetString("phone")
-	e_mail := this.GetString("mail")
-	company_name := this.GetString("company_name")
-	id_num := strings.ToUpper(this.GetString("taxpayer_identnum")) //纳税人识别号
-	invoiceContent := this.GetString("invoiceContent")
-	remark := this.GetString("remark")
-	invoiceVariety := this.GetString("invoice_variety")
-	invoice_status := 0
-	//userId := qutil.ObjToString(this.GetSession("userId"))  支持扫描换票
-	//order_code := this.GetString("order_code")
-	sid := encrypt.SE.Decode4Hex(this.GetString("sid"))
-	oRes := util.Mysql.FindOne(dbname, map[string]interface{}{"id": sid, "invoice_changed": 0, "invoice_status": 1}, "", "") //仅线上开发票可换票
-	if oRes != nil && len(*oRes) > 0 &&
-		((*oRes)["invoicing_entity"] == nil || qutil.InterfaceToStr((*oRes)["invoicing_entity"]) == config.InvoiceConfig.SigningSubject) {
-		var (
-			qSql    string
-			errCode []string
-			//saveData []map[string]interface{}
-			resArr []map[string]interface{}
-		)
-		pCode := qutil.InterfaceToStr((*oRes)["order_code"])
-		//多订单联合开票
-		if invoice_order_code := qutil.InterfaceToStr((*oRes)["invoice_order_code"]); len(strings.Split(invoice_order_code, ",")) > 1 {
-			pCode = invoice_order_code
-			qSql = fmt.Sprintf(`SELECT * FROM invoice WHERE invoice_order_code = '%s' and invoice_changed = 0 and invoice_status = 1`, qutil.InterfaceToStr((*oRes)["invoice_order_code"]))
-			res1 := util.Mysql.SelectBySql(qSql)
-			if res1 != nil && len(*res1) > 0 {
-				resArr = *res1
-			}
-		} else {
-			resArr = append(resArr, *oRes)
-		}
-		var isMail bool
-		tm := time.Now()
-		for _, res := range resArr {
-			if res["only_Identifying"] == nil { //无唯一id 允许换票一次 生成唯一id
-				newUuid := uuid.New()
-				res["only_Identifying"] = newUuid
-				util.Mysql.Update(dbname, map[string]interface{}{"id": res["id"]}, map[string]interface{}{"only_Identifying": newUuid, "invoice_status": -2})
-			} else if util.Mysql.Count(dbname, map[string]interface{}{
-				"order_code":       res["order_code"],
-				"user_id":          res["user_id"],
-				"only_Identifying": res["only_Identifying"],
-			}) > 1 {
-				continue
-			}
-
-			res["company_phone"] = this.GetString("company_phone")
-			res["operable_time"] = FormatDate(&tm, Date_Full_Layout)
-			res["bank_account"] = this.GetString("bank_account")
-			res["company_address"] = this.GetString("company_address")
-			res["bank_name"] = this.GetString("bank_name")
-			res["recipient"] = this.GetString("recipient")
-			res["delivery_address"] = this.GetString("delivery_address")
-			data := res
-			delete(data, "id")
-			switch IsEdit(res, phone, e_mail, id_num, company_name, invoice_type, invoiceContent, remark, invoiceVariety) {
-			case true:
-				this.ServeJson(map[string]interface{}{
-					"invoice_status": -1,
-					"invoice_msg":    "开票信息未修改,不允许提交",
-				})
-				return
-				data["phone"] = phone
-				data["mail"] = e_mail
-				data["invoice_content"] = invoiceContent
-				data["company_name"] = company_name
-				data["invoice_type"] = invoice_type
-				data["taxpayer_identnum"] = id_num
-				data["remark"] = remark
-				data["invoice_variety"] = invoiceVariety
-				//var html string
-				//if invoice_type == "个人" {
-				//	emailHtml := emailHtml_gr
-				//	emailHtmls := fmt.Sprintf(emailHtml, phone, e_mail)
-				//	html = fmt.Sprintf(email_format, data["order_code"], data["url"], emailHtmls)
-				//} else {
-				//	emailHtml := emailHtml_gs
-				//	emailHtmls := fmt.Sprintf(emailHtml, company_name, id_num, phone, e_mail)
-				//	html = fmt.Sprintf(email_format, data["order_code"], data["url"], emailHtmls)
-				//}
-				data["invoice_changed"] = 1
-				data["invoice_status"] = 1
-				data["billing_time"] = tm.Unix()
-				data["create_time"] = tm.Unix()
-				order_id := util.Mysql.Insert(dbname, data)
-				if order_id == -1 {
-					errCode = append(errCode, fmt.Sprintf("%s_%s", data["order_code"], data["invoice_order_code"]))
-				}
-				if !isMail { //成功发邮件
-					isMail = true
-					sendMail(invoice_type, pCode, company_name, id_num, e_mail, phone, qutil.InterfaceToStr(data["source_url"]), invoiceContent)
-					//InvoiceSendMail(data["mail"].(string), html, "电子发票")
-				}
-			case false:
-				if !config.InvoiceConfig.Third_party_switch {
-					this.ServeJson(map[string]interface{}{
-						"error_code": -2,
-						"error_msg":  "暂不支持换票",
-					})
-					return
-				}
-				data["phone"] = phone
-				data["mail"] = e_mail
-				data["invoice_content"] = invoiceContent
-				data["company_name"] = company_name
-				data["invoice_type"] = invoice_type
-				data["taxpayer_identnum"] = id_num
-				data["remark"] = remark
-				data["invoice_variety"] = invoiceVariety
-				dataexport_data := make(map[string]interface{})
-				if invoice_type == "个人" {
-					dataexport_data["applyBill_type"] = 0
-					dataexport_data["applyBill_taxnum"] = ""
-					dataexport_data["applybill_company"] = ""
-				} else {
-					dataexport_data["applyBill_type"] = 1
-					dataexport_data["applyBill_taxnum"] = id_num
-					dataexport_data["applybill_company"] = company_name
-				}
-				dataexport_data["user_mail"] = e_mail
-				util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": res["order_code"]}, dataexport_data)
-				data["mail"] = e_mail
-				data["phone"] = phone
-				data["invoice_type"] = invoice_type
-				data["company_name"] = company_name
-				data["taxpayer_identnum"] = id_num
-				data["invoice_changed"] = 1
-				data["create_time"] = time.Now().Unix()
-				data["invoice_status"] = invoice_status
-				order_id := util.Mysql.Insert(dbname, data)
-				if order_id == -1 {
-					errCode = append(errCode, fmt.Sprintf("%s_%s", data["order_code"], data["invoice_order_code"]))
-				}
-			}
-		}
-		log.Println("换票错误信息:", errCode)
-		this.ServeJson(map[string]interface{}{
-			"error_code": 0,
-			"error_msg":  "",
-		})
-
-	} else {
-		this.ServeJson(map[string]interface{}{
-			"error_code": -1,
-			"error_msg":  "订单状态异常",
-		})
-		return
-	}
+    //红冲开关
+    if !config.InvoiceConfig.Red_invoice_switch {
+        this.ServeJson(map[string]interface{}{
+            "invoice_status": -1,
+            "invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
+        })
+        return
+    }
+    invoice_type := this.GetString("invoice_type")
+    phone := this.GetString("phone")
+    e_mail := this.GetString("mail")
+    company_name := this.GetString("company_name")
+    id_num := strings.ToUpper(this.GetString("taxpayer_identnum")) //纳税人识别号
+    invoiceContent := this.GetString("invoiceContent")
+    remark := this.GetString("remark")
+    invoiceVariety := this.GetString("invoice_variety")
+    invoice_status := 0
+    //userId := qutil.ObjToString(this.GetSession("userId"))  支持扫描换票
+    //order_code := this.GetString("order_code")
+    sid := encrypt.SE.Decode4Hex(this.GetString("sid"))
+    oRes := util.Mysql.FindOne(dbname, map[string]interface{}{"id": sid, "invoice_changed": 0, "invoice_status": 1}, "", "") //仅线上开发票可换票
+    if oRes != nil && len(*oRes) > 0 &&
+        ((*oRes)["invoicing_entity"] == nil || qutil.InterfaceToStr((*oRes)["invoicing_entity"]) == config.InvoiceConfig.SigningSubject) {
+        var (
+            qSql    string
+            errCode []string
+            //saveData []map[string]interface{}
+            resArr []map[string]interface{}
+        )
+        pCode := qutil.InterfaceToStr((*oRes)["order_code"])
+        //多订单联合开票
+        if invoice_order_code := qutil.InterfaceToStr((*oRes)["invoice_order_code"]); len(strings.Split(invoice_order_code, ",")) > 1 {
+            pCode = invoice_order_code
+            qSql = fmt.Sprintf(`SELECT * FROM invoice WHERE invoice_order_code = '%s' and invoice_changed = 0 and invoice_status = 1`, qutil.InterfaceToStr((*oRes)["invoice_order_code"]))
+            res1 := util.Mysql.SelectBySql(qSql)
+            if res1 != nil && len(*res1) > 0 {
+                resArr = *res1
+            }
+        } else {
+            resArr = append(resArr, *oRes)
+        }
+        var isMail bool
+        tm := time.Now()
+        for _, res := range resArr {
+            if res["only_Identifying"] == nil { //无唯一id 允许换票一次 生成唯一id
+                newUuid := uuid.New()
+                res["only_Identifying"] = newUuid
+                util.Mysql.Update(dbname, map[string]interface{}{"id": res["id"]}, map[string]interface{}{"only_Identifying": newUuid, "invoice_status": -2})
+            } else if util.Mysql.Count(dbname, map[string]interface{}{
+                "order_code":       res["order_code"],
+                "user_id":          res["user_id"],
+                "only_Identifying": res["only_Identifying"],
+            }) > 1 {
+                continue
+            }
+
+            res["company_phone"] = this.GetString("company_phone")
+            res["operable_time"] = FormatDate(&tm, Date_Full_Layout)
+            res["bank_account"] = this.GetString("bank_account")
+            res["company_address"] = this.GetString("company_address")
+            res["bank_name"] = this.GetString("bank_name")
+            res["recipient"] = this.GetString("recipient")
+            res["delivery_address"] = this.GetString("delivery_address")
+            data := res
+            delete(data, "id")
+            switch IsEdit(res, phone, e_mail, id_num, company_name, invoice_type, invoiceContent, remark, invoiceVariety) {
+            case true:
+                this.ServeJson(map[string]interface{}{
+                    "invoice_status": -1,
+                    "invoice_msg":    "开票信息未修改,不允许提交",
+                })
+                return
+                data["phone"] = phone
+                data["mail"] = e_mail
+                data["invoice_content"] = invoiceContent
+                data["company_name"] = company_name
+                data["invoice_type"] = invoice_type
+                data["taxpayer_identnum"] = id_num
+                data["remark"] = remark
+                data["invoice_variety"] = invoiceVariety
+                //var html string
+                //if invoice_type == "个人" {
+                //	emailHtml := emailHtml_gr
+                //	emailHtmls := fmt.Sprintf(emailHtml, phone, e_mail)
+                //	html = fmt.Sprintf(email_format, data["order_code"], data["url"], emailHtmls)
+                //} else {
+                //	emailHtml := emailHtml_gs
+                //	emailHtmls := fmt.Sprintf(emailHtml, company_name, id_num, phone, e_mail)
+                //	html = fmt.Sprintf(email_format, data["order_code"], data["url"], emailHtmls)
+                //}
+                data["invoice_changed"] = 1
+                data["invoice_status"] = 1
+                data["billing_time"] = tm.Unix()
+                data["create_time"] = tm.Unix()
+                order_id := util.Mysql.Insert(dbname, data)
+                if order_id == -1 {
+                    errCode = append(errCode, fmt.Sprintf("%s_%s", data["order_code"], data["invoice_order_code"]))
+                }
+                if !isMail { //成功发邮件
+                    isMail = true
+                    sendMail(invoice_type, pCode, company_name, id_num, e_mail, phone, qutil.InterfaceToStr(data["source_url"]), invoiceContent)
+                    //InvoiceSendMail(data["mail"].(string), html, "电子发票")
+                }
+            case false:
+                if !config.InvoiceConfig.Third_party_switch {
+                    this.ServeJson(map[string]interface{}{
+                        "error_code": -2,
+                        "error_msg":  "暂不支持换票",
+                    })
+                    return
+                }
+                data["phone"] = phone
+                data["mail"] = e_mail
+                data["invoice_content"] = invoiceContent
+                data["company_name"] = company_name
+                data["invoice_type"] = invoice_type
+                data["taxpayer_identnum"] = id_num
+                data["remark"] = remark
+                data["invoice_variety"] = invoiceVariety
+                dataexport_data := make(map[string]interface{})
+                if invoice_type == "个人" {
+                    dataexport_data["applyBill_type"] = 0
+                    dataexport_data["applyBill_taxnum"] = ""
+                    dataexport_data["applybill_company"] = ""
+                } else {
+                    dataexport_data["applyBill_type"] = 1
+                    dataexport_data["applyBill_taxnum"] = id_num
+                    dataexport_data["applybill_company"] = company_name
+                }
+                dataexport_data["user_mail"] = e_mail
+                util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": res["order_code"]}, dataexport_data)
+                data["mail"] = e_mail
+                data["phone"] = phone
+                data["invoice_type"] = invoice_type
+                data["company_name"] = company_name
+                data["taxpayer_identnum"] = id_num
+                data["invoice_changed"] = 1
+                data["create_time"] = time.Now().Unix()
+                data["invoice_status"] = invoice_status
+                order_id := util.Mysql.Insert(dbname, data)
+                if order_id == -1 {
+                    errCode = append(errCode, fmt.Sprintf("%s_%s", data["order_code"], data["invoice_order_code"]))
+                }
+            }
+        }
+        log.Println("换票错误信息:", errCode)
+        this.ServeJson(map[string]interface{}{
+            "error_code": 0,
+            "error_msg":  "",
+        })
+
+    } else {
+        this.ServeJson(map[string]interface{}{
+            "error_code": -1,
+            "error_msg":  "订单状态异常",
+        })
+        return
+    }
 
 }
 
 func IsEdit(res map[string]interface{}, phone, e_mail, id_num, company_name, invoice_type, invoiceContent, remark, invoiceVariety string) bool {
-	if invoice_type == "个人" {
-		if phone == res["phone"] && e_mail == res["mail"] && res["invoice_type"] == "个人" &&
-			res["invoice_content"] == invoiceContent && res["remark"] == remark && res["invoice_variety"] == invoiceVariety {
-			return true
-		}
-	} else {
-		if phone == res["phone"] && e_mail == res["mail"] && id_num == res["taxpayer_identnum"] &&
-			company_name == res["company_name"] && res["invoice_type"] == "单位" &&
-			res["invoice_content"] == invoiceContent && res["remark"] == remark && res["invoice_variety"] == invoiceVariety {
-			return true
-		}
-	}
-	return false
+    if invoice_type == "个人" {
+        if phone == res["phone"] && e_mail == res["mail"] && res["invoice_type"] == "个人" &&
+            res["invoice_content"] == invoiceContent && res["remark"] == remark && res["invoice_variety"] == invoiceVariety {
+            return true
+        }
+    } else {
+        if phone == res["phone"] && e_mail == res["mail"] && id_num == res["taxpayer_identnum"] &&
+            company_name == res["company_name"] && res["invoice_type"] == "单位" &&
+            res["invoice_content"] == invoiceContent && res["remark"] == remark && res["invoice_variety"] == invoiceVariety {
+            return true
+        }
+    }
+    return false
 }
 
 // 退票
 func (this *Invoice) Refundinvoice() {
-	if !config.InvoiceConfig.Third_party_switch {
-		this.ServeJson(map[string]interface{}{
-			"invoice_status": -1,
-			"invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
-		})
-		return
-	}
-	var refund_flag = -1
-	userid := this.GetSession("userId")
-	invoice_serialnum := this.GetString("invoice_serialnum") //发票流水号
-	if invoice_serialnum != "" {
-		query := make(map[string]interface{})
-		query["invoice_serialnum"] = invoice_serialnum
-		query["user_id"] = userid
-		res := util.Mysql.FindOne(dbname, query, "fpdm,fphm,invoice_serialnum", "")
-		if res != nil {
-			req_ := make(map[string]interface{})
-			req_["fpdm"] = (*res)["fpdm"]
-			req_["fphm"] = (*res)["fphm"]
-			req_["redcode"] = (*res)["invoice_serialnum"]
-			b, _ := json.Marshal(req_)
-			buffer := bytes.NewBuffer(b)
-			request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/RedSubmit", buffer)
-			client := &http.Client{}
-			response, err := client.Do(request)
-			if err == nil {
-				res, _ := ioutil.ReadAll(response.Body)
-				defer response.Body.Close()
-				result := map[string]interface{}{}
-				err := json.Unmarshal(res, &result)
-				if err != nil {
-					log.Println("json序列化错误")
-				} else {
-					if result["code"].(string) == "0" {
-						refund_flag = 0
-					} else if result["code"].(string) == "1" {
-						refund_flag = 1
-					} else {
-						refund_flag = 2
-					}
-				}
-				go util.Mysql.Update(dbname, query, map[string]interface{}{"refund_flag": refund_flag})
-			}
-
-		}
-	}
+    if !config.InvoiceConfig.Third_party_switch {
+        this.ServeJson(map[string]interface{}{
+            "invoice_status": -1,
+            "invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
+        })
+        return
+    }
+    var refund_flag = -1
+    userid := this.GetSession("userId")
+    invoice_serialnum := this.GetString("invoice_serialnum") //发票流水号
+    if invoice_serialnum != "" {
+        query := make(map[string]interface{})
+        query["invoice_serialnum"] = invoice_serialnum
+        query["user_id"] = userid
+        res := util.Mysql.FindOne(dbname, query, "fpdm,fphm,invoice_serialnum", "")
+        if res != nil {
+            req_ := make(map[string]interface{})
+            req_["fpdm"] = (*res)["fpdm"]
+            req_["fphm"] = (*res)["fphm"]
+            req_["redcode"] = (*res)["invoice_serialnum"]
+            b, _ := json.Marshal(req_)
+            buffer := bytes.NewBuffer(b)
+            request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/RedSubmit", buffer)
+            client := &http.Client{}
+            response, err := client.Do(request)
+            if err == nil {
+                res, _ := ioutil.ReadAll(response.Body)
+                defer response.Body.Close()
+                result := map[string]interface{}{}
+                err := json.Unmarshal(res, &result)
+                if err != nil {
+                    log.Println("json序列化错误")
+                } else {
+                    if result["code"].(string) == "0" {
+                        refund_flag = 0
+                    } else if result["code"].(string) == "1" {
+                        refund_flag = 1
+                    } else {
+                        refund_flag = 2
+                    }
+                }
+                go util.Mysql.Update(dbname, query, map[string]interface{}{"refund_flag": refund_flag})
+            }
+
+        }
+    }
 
 }
 
 func (this *Invoice) Invoiceinfo() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	order_code := this.GetString("order_code")
-	data := make(map[string]interface{})
-	data["order_code"] = order_code
-	data["user_id"] = userId
-	countdowntime := config.Config.OrderCountdown.(string)
-	status := util.Mysql.FindOne("dataexport_order", data, "", "")
-	if *status != nil {
-		(*status)["source"] = LastInvoiceSource(qutil.InterfaceToStr((*status)["order_code"]))
-		//卡卷id加密
-		if (*status)["d_relation_id"] != "" {
-			(*status)["userLotteryId"] = encrypt.SE.Encode2Hex(qutil.ObjToString((*status)["d_relation_id"]))
-		}
-		(*status)["order_money"] = float64((*status)["order_money"].(int64)) / 100
-		if (*status)["discount_price"] != nil && (*status)["discount_price"].(int64) > 0 {
-			(*status)["discount_price"] = float64((*status)["discount_price"].(int64)) / 100
-		}
-		if (*status)["pay_money"] != nil && (*status)["pay_money"].(int64) > 0 {
-			(*status)["pay_money"] = float64((*status)["pay_money"].(int64)) / 100
-		}
-		delete((*status), "d_relation_id")
-		(*status)["countdown"] = countdowntime
-		var isCanInvoic bool
-		create_time, _ := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*status)["create_time"]), time.Local)
-		if create_time.Unix() > config.InvoiceConfig.Order_createtime {
-			//剩余可开票金额
-			isCanInvoic = IsAllowInvoice(*status)
-		}
-		(*status)["is_can_invoice"] = isCanInvoic
-		filter := dataexport.SieveCondition{}
-		if (*status)["filter"] != nil {
-			err := json.Unmarshal([]byte((*status)["filter"].(string)), &filter)
-			if err == nil {
-				// 处理行业其他
-				tmpIndustry := []string{}
-				for i := 0; i < len(filter.Industry); i++ {
-					cIndustry := filter.Industry[i]
-					if strings.Contains(cIndustry, "其它") {
-						continue
-					}
-					tmpIndustry = append(tmpIndustry, cIndustry)
-				}
-				filter.Industry = tmpIndustry
-			}
-			(*status)["filter"] = filter
-		}
-		//是否存在可查看发票
-		(*status)["invoice_show"] = len(ShowList(order_code)) > 0
-		this.ServeJson(map[string]interface{}{
-			"status": "success",
-			"data":   status,
-		})
-	} else {
-		(*status)["countdown"] = countdowntime
-		this.ServeJson(map[string]interface{}{
-			"status": "fail",
-			"data":   "",
-		})
-	}
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    order_code := this.GetString("order_code")
+    data := make(map[string]interface{})
+    data["order_code"] = order_code
+    data["user_id"] = userId
+    countdowntime := config.Config.OrderCountdown.(string)
+    status := util.Mysql.FindOne("dataexport_order", data, "", "")
+    if *status != nil {
+        (*status)["source"] = LastInvoiceSource(qutil.InterfaceToStr((*status)["order_code"]))
+        //卡卷id加密
+        if (*status)["d_relation_id"] != "" {
+            (*status)["userLotteryId"] = encrypt.SE.Encode2Hex(qutil.ObjToString((*status)["d_relation_id"]))
+        }
+        (*status)["order_money"] = float64((*status)["order_money"].(int64)) / 100
+        if (*status)["discount_price"] != nil && (*status)["discount_price"].(int64) > 0 {
+            (*status)["discount_price"] = float64((*status)["discount_price"].(int64)) / 100
+        }
+        if (*status)["pay_money"] != nil && (*status)["pay_money"].(int64) > 0 {
+            (*status)["pay_money"] = float64((*status)["pay_money"].(int64)) / 100
+        }
+        delete((*status), "d_relation_id")
+        (*status)["countdown"] = countdowntime
+        var isCanInvoic bool
+        create_time, _ := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*status)["create_time"]), time.Local)
+        if create_time.Unix() > config.InvoiceConfig.Order_createtime {
+            //剩余可开票金额
+            isCanInvoic = IsAllowInvoice(*status)
+        }
+        (*status)["is_can_invoice"] = isCanInvoic
+        filter := dataexport.SieveCondition{}
+        if (*status)["filter"] != nil {
+            err := json.Unmarshal([]byte((*status)["filter"].(string)), &filter)
+            if err == nil {
+                // 处理行业其他
+                tmpIndustry := []string{}
+                for i := 0; i < len(filter.Industry); i++ {
+                    cIndustry := filter.Industry[i]
+                    if strings.Contains(cIndustry, "其它") {
+                        continue
+                    }
+                    tmpIndustry = append(tmpIndustry, cIndustry)
+                }
+                filter.Industry = tmpIndustry
+            }
+            (*status)["filter"] = filter
+        }
+        //是否存在可查看发票
+        (*status)["invoice_show"] = len(ShowList(order_code)) > 0
+        this.ServeJson(map[string]interface{}{
+            "status": "success",
+            "data":   status,
+        })
+    } else {
+        (*status)["countdown"] = countdowntime
+        this.ServeJson(map[string]interface{}{
+            "status": "fail",
+            "data":   "",
+        })
+    }
 
 }
 
 func InvoiceSendMail(target_mail, html, title string) {
-	for k, v := range config.GmailAuth {
-		if mail.GSendMail("剑鱼标讯", target_mail, "", "", title, html, "", "", v) {
-			log.Println(target_mail, fmt.Sprintf("使用%s发送邮件成功", v.User))
-			break
-		}
-		if k < len(config.GmailAuth)-1 {
-			log.Println(target_mail, fmt.Sprintf("使用%s发送邮件失败!3s后使用其他邮箱尝试", v.User))
-		} else {
-			log.Println(target_mail, fmt.Sprintf("使用%s发送邮件失败!", v.User))
-		}
-		time.Sleep(time.Second * 3)
-	}
+    for k, v := range config.GmailAuth {
+        if mail.GSendMail("剑鱼标讯", target_mail, "", "", title, html, "", "", v) {
+            log.Println(target_mail, fmt.Sprintf("使用%s发送邮件成功", v.User))
+            break
+        }
+        if k < len(config.GmailAuth)-1 {
+            log.Println(target_mail, fmt.Sprintf("使用%s发送邮件失败!3s后使用其他邮箱尝试", v.User))
+        } else {
+            log.Println(target_mail, fmt.Sprintf("使用%s发送邮件失败!", v.User))
+        }
+        time.Sleep(time.Second * 3)
+    }
 }
 
 // 查询订单最后开票状态
 func LastInvoiceSource(orderCode string) int64 {
-	orderData := util.Mysql.SelectBySql("select source  from  invoice   where   order_code  =? ORDER BY  create_time desc ", orderCode)
-	if orderData != nil && len(*orderData) > 0 {
-		return qutil.Int64All((*orderData)[0]["source"])
-	}
-	return 0
+    orderData := util.Mysql.SelectBySql("select source  from  invoice   where   order_code  =? ORDER BY  create_time desc ", orderCode)
+    if orderData != nil && len(*orderData) > 0 {
+        return qutil.Int64All((*orderData)[0]["source"])
+    }
+    return 0
 }
 
 // 是否可开票
 func IsAllowInvoice(res map[string]interface{}) bool {
-	if qutil.IntAll(res["applybill_status"]) > 0 {
-		return false
-	}
-	if qutil.Float64All(res["pay_money"]) == 0 {
-		return false
-	}
-	filter := qutil.ObjToString(res["filter"].(string))
-	filter_map := map[string]interface{}{}
-	_ = json.Unmarshal([]byte(filter), &filter_map)
-	if qutil.IntAll(res["order_status"]) == 1 && qutil.InterfaceToStr(filter_map["badge"]) != "exchange" {
-		//用户下单|| 代用户下单
-		if qutil.IntAll(res["is_backstage_order"]) == 0 || qutil.InterfaceToStr(res["order_channel"]) == "xdqd04" {
-			return len(ShowList(qutil.InterfaceToStr(res["order_code"]))) == 0
-		} else { //qmx下单 已全额回款 发票企业为剑鱼
-			return qutil.IntAll(res["return_status"]) == 1 && qutil.InterfaceToStr(res["signing_subject"]) == "h01" &&
-				len(ShowList(qutil.InterfaceToStr(res["order_code"]))) == 0
-		}
-	}
-	return false
+    if qutil.IntAll(res["applybill_status"]) > 0 {
+        return false
+    }
+    if qutil.Float64All(res["pay_money"]) == 0 {
+        return false
+    }
+    filter := qutil.ObjToString(res["filter"].(string))
+    filter_map := map[string]interface{}{}
+    _ = json.Unmarshal([]byte(filter), &filter_map)
+    if qutil.IntAll(res["order_status"]) == 1 && qutil.InterfaceToStr(filter_map["badge"]) != "exchange" {
+        //用户下单|| 代用户下单
+        if qutil.IntAll(res["is_backstage_order"]) == 0 || qutil.InterfaceToStr(res["order_channel"]) == "xdqd04" {
+            return len(ShowList(qutil.InterfaceToStr(res["order_code"]))) == 0
+        } else { //qmx下单 已全额回款 发票企业为剑鱼
+            return qutil.IntAll(res["return_status"]) == 1 && qutil.InterfaceToStr(res["signing_subject"]) == "h01" &&
+                len(ShowList(qutil.InterfaceToStr(res["order_code"]))) == 0
+        }
+    }
+    return false
 }
 
 func (this *Invoice) Available() {
-	u := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": this.GetString("order_code")}, "pay_time", "")
-	status := 0
-	if u != nil {
-		if pay_time, _ := (*u)["pay_time"].(string); pay_time != "" && config.InvoiceConfig.Switch_paymch.Time != "" {
-			p1, err1 := time.ParseInLocation(Date_Full_Layout, pay_time, time.Local)
-			p2, err2 := time.ParseInLocation(Date_Full_Layout, config.InvoiceConfig.Switch_paymch.Time, time.Local)
-			if err1 == nil && err2 == nil {
-				if config.InvoiceConfig.Switch_paymch.Model == 1 { //大于该时间点,不能开票
-					if p1.Before(p2) {
-						status = 1
-					}
-				} else if config.InvoiceConfig.Switch_paymch.Model == 2 { //小于该时间点,不能开票
-					if p1.After(p2) {
-						status = 1
-					}
-				} else { //无限制,都能开票
-					status = 1
-				}
-			}
-		} else {
-			status = 1
-		}
-	}
-	this.ServeJson(map[string]interface{}{
-		"status": status,
-	})
+    u := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": this.GetString("order_code")}, "pay_time", "")
+    status := 0
+    if u != nil {
+        if pay_time, _ := (*u)["pay_time"].(string); pay_time != "" && config.InvoiceConfig.Switch_paymch.Time != "" {
+            p1, err1 := time.ParseInLocation(Date_Full_Layout, pay_time, time.Local)
+            p2, err2 := time.ParseInLocation(Date_Full_Layout, config.InvoiceConfig.Switch_paymch.Time, time.Local)
+            if err1 == nil && err2 == nil {
+                if config.InvoiceConfig.Switch_paymch.Model == 1 { //大于该时间点,不能开票
+                    if p1.Before(p2) {
+                        status = 1
+                    }
+                } else if config.InvoiceConfig.Switch_paymch.Model == 2 { //小于该时间点,不能开票
+                    if p1.After(p2) {
+                        status = 1
+                    }
+                } else { //无限制,都能开票
+                    status = 1
+                }
+            }
+        } else {
+            status = 1
+        }
+    }
+    this.ServeJson(map[string]interface{}{
+        "status": status,
+    })
 }
 
 // 删除有问题的换开发票并记录
 func delReplaceInvoice(query map[string]interface{}) bool {
-	data := util.Mysql.FindOne(dbname, query, "", "")
-	if data != nil && len(*data) > 0 {
-		log.Printf("invoice replace delete data: %+v", data)
-	}
-	return util.Mysql.Delete(dbname, query)
+    data := util.Mysql.FindOne(dbname, query, "", "")
+    if data != nil && len(*data) > 0 {
+        log.Printf("invoice replace delete data: %+v", data)
+    }
+    return util.Mysql.Delete(dbname, query)
 }
 
 func InvoiceAmount(orderCode string) (invoicedMoney int64) {
-	invoicedInfo := util.Mysql.SelectBySql(fmt.Sprintf("SELECT invoice_order_money,only_Identifying FROM invoice WHERE order_code = '%s' and invoice_status>=0", orderCode))
-	if invoicedInfo != nil && len(*invoicedInfo) > 0 {
-		onlyMap := make(map[string]int64)
-		for _, m := range *invoicedInfo {
-			if m["only_Identifying"] != nil { //过滤换票过程中的数据
-				onlyMap[qutil.InterfaceToStr(m["only_Identifying"])] = qutil.Int64All(m["invoice_order_money"])
-			} else {
-				invoicedMoney += qutil.Int64All(m["invoice_order_money"])
-			}
-		}
-		if len(onlyMap) > 0 {
-			for _, i := range onlyMap {
-				invoicedMoney += i
-			}
-		}
-	}
-	return
+    invoicedInfo := util.Mysql.SelectBySql(fmt.Sprintf("SELECT invoice_order_money,only_Identifying FROM invoice WHERE order_code = '%s' and invoice_status>=0", orderCode))
+    if invoicedInfo != nil && len(*invoicedInfo) > 0 {
+        onlyMap := make(map[string]int64)
+        for _, m := range *invoicedInfo {
+            if m["only_Identifying"] != nil { //过滤换票过程中的数据
+                onlyMap[qutil.InterfaceToStr(m["only_Identifying"])] = qutil.Int64All(m["invoice_order_money"])
+            } else {
+                invoicedMoney += qutil.Int64All(m["invoice_order_money"])
+            }
+        }
+        if len(onlyMap) > 0 {
+            for _, i := range onlyMap {
+                invoicedMoney += i
+            }
+        }
+    }
+    return
 }
 
 // InvoiceSubmit 发票信息提交
 func (this *Invoice) InvoiceSubmit() {
-	if !R.CheckReqParam(this.ResponseWriter, this.Request, "invoice_variety", "invoiceContent", "invoice_type", "phone", "mail") {
-		this.ServeJson(NewResult("", errors.New("缺少参数")))
-		return
-	}
-	if this.GetString("invoice_type") == "单位" && !R.CheckReqParam(this.ResponseWriter, this.Request, "company_name", "taxpayer_identnum") {
-		this.ServeJson(NewResult("", errors.New("缺少参数")))
-		return
-	}
-	if !config.InvoiceConfig.Invoice_type[this.GetString("invoice_variety")] {
-		this.ServeJson(NewResult("", errors.New("发票类型有误")))
-		return
-	}
-	if this.GetString("invoice_type") != "个人" && this.GetString("invoice_type") != "单位" {
-		this.ServeJson(NewResult("", errors.New("发票抬头有误")))
-		return
-	}
-	if len([]rune(this.GetString("company_address"))) > 55 {
-		this.ServeJson(NewResult("", errors.New("单位地址过长")))
-		return
-	}
-	now := time.Now()
-	again, _ := this.GetInteger("again")                                                //是否是失败重新开票 0 首次提交  1 再此提交
-	oldOnlyIdentifying := encrypt.SE.DecodeString(this.GetString("oldOnlyIdentifying")) //最后一次失败的发票信息唯一标识
-	data := map[string]interface{}{
-		"company_name":      this.GetString("company_name"),
-		"phone":             this.GetString("phone"),
-		"mail":              this.GetString("mail"),
-		"invoice_type":      this.GetString("invoice_type"),
-		"invoice_content":   this.GetString("invoiceContent"),
-		"invoice_status":    0,
-		"invoice_changed":   0,
-		"company_phone":     this.GetString("company_phone"),
-		"taxpayer_identnum": this.GetString("taxpayer_identnum"),
-		"create_time":       time.Now().Unix(),
-		"operable_time":     FormatDate(&now, Date_Full_Layout),
-		"invoicing_entity":  "北京剑鱼信息技术有限公司",
-		"remark":            this.GetString("remark"),
-		"invoice_variety":   this.GetString("invoice_variety"),
-		"bank_account":      this.GetString("bank_account"),
-		"company_address":   this.GetString("company_address"),
-		"bank_name":         this.GetString("bank_name"),
-		"recipient":         this.GetString("recipient"),
-		"delivery_address":  this.GetString("delivery_address"),
-	}
-	if again == 1 {
-		err := OpenInvoiceAgain(oldOnlyIdentifying, data)
-		if err != nil {
-			this.ServeJson(NewResult("", err))
-			return
-		}
-		this.ServeJson(NewResult("保存信息成功", nil))
-		return
-	}
-	source, _ := this.GetInteger("source")
-	switch source {
-	case 0: //用户端开票
-		userId := qutil.ObjToString(this.GetSession("userId"))
-		if userId == "" {
-			this.ServeJson(NewResult("", errors.New("userId为空")))
-			return
-		}
-		orderCode := this.GetString("order_code")
-		err := JyOpenInvoice(orderCode, userId, data)
-		if err != nil {
-			this.ServeJson(NewResult("", err))
-			return
-		}
-	case 1: //管理后台扫码开票
-		onlyIdentifying := encrypt.SE.DecodeString(this.GetString("onlyIdentifying"))
-		invoiceMoney := encrypt.SE.DecodeString(this.GetString("invoiceMoney"))
-		operator := encrypt.SE.Decode4HexByCheck(this.GetString("operator"))
-		if onlyIdentifying == "" || invoiceMoney == "" {
-			this.ServeJson(NewResult("", errors.New("传入参数不正确")))
-			return
-		}
-		err := AdminOpenInvoice(onlyIdentifying, invoiceMoney, operator, data)
-		if err != nil {
-			this.ServeJson(NewResult("", err))
-			return
-		}
-	}
-	this.ServeJson(NewResult("保存信息成功", nil))
+    if !R.CheckReqParam(this.ResponseWriter, this.Request, "invoice_variety", "invoiceContent", "invoice_type", "phone", "mail") {
+        this.ServeJson(NewResult("", errors.New("缺少参数")))
+        return
+    }
+    if this.GetString("invoice_type") == "单位" && !R.CheckReqParam(this.ResponseWriter, this.Request, "company_name", "taxpayer_identnum") {
+        this.ServeJson(NewResult("", errors.New("缺少参数")))
+        return
+    }
+    if !config.InvoiceConfig.Invoice_type[this.GetString("invoice_variety")] {
+        this.ServeJson(NewResult("", errors.New("发票类型有误")))
+        return
+    }
+    if this.GetString("invoice_type") != "个人" && this.GetString("invoice_type") != "单位" {
+        this.ServeJson(NewResult("", errors.New("发票抬头有误")))
+        return
+    }
+    if len([]rune(this.GetString("company_address"))) > 55 {
+        this.ServeJson(NewResult("", errors.New("单位地址过长")))
+        return
+    }
+    now := time.Now()
+    again, _ := this.GetInteger("again")                                                //是否是失败重新开票 0 首次提交  1 再此提交
+    oldOnlyIdentifying := encrypt.SE.DecodeString(this.GetString("oldOnlyIdentifying")) //最后一次失败的发票信息唯一标识
+    data := map[string]interface{}{
+        "company_name":      this.GetString("company_name"),
+        "phone":             this.GetString("phone"),
+        "mail":              this.GetString("mail"),
+        "invoice_type":      this.GetString("invoice_type"),
+        "invoice_content":   this.GetString("invoiceContent"),
+        "invoice_status":    0,
+        "invoice_changed":   0,
+        "company_phone":     this.GetString("company_phone"),
+        "taxpayer_identnum": this.GetString("taxpayer_identnum"),
+        "create_time":       time.Now().Unix(),
+        "operable_time":     FormatDate(&now, Date_Full_Layout),
+        "invoicing_entity":  "北京剑鱼信息技术有限公司",
+        "remark":            this.GetString("remark"),
+        "invoice_variety":   this.GetString("invoice_variety"),
+        "bank_account":      this.GetString("bank_account"),
+        "company_address":   this.GetString("company_address"),
+        "bank_name":         this.GetString("bank_name"),
+        "recipient":         this.GetString("recipient"),
+        "delivery_address":  this.GetString("delivery_address"),
+    }
+    if again == 1 {
+        err := OpenInvoiceAgain(oldOnlyIdentifying, data)
+        if err != nil {
+            this.ServeJson(NewResult("", err))
+            return
+        }
+        this.ServeJson(NewResult("保存信息成功", nil))
+        return
+    }
+    source, _ := this.GetInteger("source")
+    switch source {
+    case 0: //用户端开票
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        if userId == "" {
+            this.ServeJson(NewResult("", errors.New("userId为空")))
+            return
+        }
+        orderCode := this.GetString("order_code")
+        err := JyOpenInvoice(orderCode, userId, data)
+        if err != nil {
+            this.ServeJson(NewResult("", err))
+            return
+        }
+    case 1: //管理后台扫码开票
+        onlyIdentifying := encrypt.SE.DecodeString(this.GetString("onlyIdentifying"))
+        invoiceMoney := encrypt.SE.DecodeString(this.GetString("invoiceMoney"))
+        operator := encrypt.SE.Decode4HexByCheck(this.GetString("operator"))
+        if onlyIdentifying == "" || invoiceMoney == "" {
+            this.ServeJson(NewResult("", errors.New("传入参数不正确")))
+            return
+        }
+        err := AdminOpenInvoice(onlyIdentifying, invoiceMoney, operator, data)
+        if err != nil {
+            this.ServeJson(NewResult("", err))
+            return
+        }
+    }
+    this.ServeJson(NewResult("保存信息成功", nil))
 }
 
 func OpenInvoiceAgain(oldOnlyIdentifying string, data map[string]interface{}) error {
-	if oldOnlyIdentifying == "" {
-		return errors.New("缺少关键参数")
-	}
-	if util.Mysql.Count("invoice_fail_record", map[string]interface{}{"only_Identifying": oldOnlyIdentifying}) >= config.InvoiceConfig.SubmitNum {
-		return errors.New("提交次数已达上限")
-	}
-	ok := InvoiceFailRecord(oldOnlyIdentifying)
-	if !ok {
-		return errors.New("插入失败记录出错")
-	}
-	delete(data, "invoice_changed")
-	if !util.Mysql.Update("invoice", map[string]interface{}{"only_Identifying": oldOnlyIdentifying, "invoice_status": -1}, data) {
-		return errors.New("再次开票更新发票信息出错")
-	}
-	return nil
+    if oldOnlyIdentifying == "" {
+        return errors.New("缺少关键参数")
+    }
+    if util.Mysql.Count("invoice_fail_record", map[string]interface{}{"only_Identifying": oldOnlyIdentifying}) >= config.InvoiceConfig.SubmitNum {
+        return errors.New("提交次数已达上限")
+    }
+    ok := InvoiceFailRecord(oldOnlyIdentifying)
+    if !ok {
+        return errors.New("插入失败记录出错")
+    }
+    delete(data, "invoice_changed")
+    if !util.Mysql.Update("invoice", map[string]interface{}{"only_Identifying": oldOnlyIdentifying, "invoice_status": -1}, data) {
+        return errors.New("再次开票更新发票信息出错")
+    }
+    return nil
 }
 
 func JyOpenInvoice(orderCode, userId string, data map[string]interface{}) error {
-	onlyIdentifying := fmt.Sprintf("%s%s%s", "aa", time.Now().Format("150405"), qutil.GetRandom(4))
-	orderInfo := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": orderCode}, "product_type,user_mail,pay_money,create_time,signing_subject,applybill_status", "")
-	if orderInfo == nil {
-		return errors.New("订单不存在")
-	}
-	createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", qutil.ObjToString((*orderInfo)["create_time"]), time.Local)
-	if createTime.Unix() < config.InvoiceConfig.Order_createtime {
-		return errors.New("2024年之前的订单不在开票")
-	}
-	if qutil.ObjToString((*orderInfo)["signing_subject"]) == "h02" {
-		return errors.New("签约主体为拓普")
-	}
-	/*if qutil.IntAll((*orderInfo)["applybill_status"]) != 0 {
-		return errors.New("已提交发票信息")
-	}*/
-	invoicedMoney := InvoiceAmount(orderCode) //已开票金额
-	invoiceMoney := qutil.Int64All((*orderInfo)["pay_money"]) - invoicedMoney
-	if invoiceMoney == 0 {
-		return errors.New("开票金额已用完")
-	}
-	data["order_code"] = orderCode
-	data["invoice_order_code"] = orderCode
-	data["only_Identifying"] = onlyIdentifying
-	data["invoice_money"] = invoiceMoney
-	data["invoice_order_money"] = invoiceMoney
-	data["product_type"] = qutil.ObjToString((*orderInfo)["product_type"])
-	data["user_id"] = userId
-	data["source"] = 0
-	if !util.Mysql.ExecTx("用户端开发票", func(tx *sql.Tx) bool {
-		if util.Mysql.InsertByTx(tx, "invoice", data) <= 0 {
-			log.Println("插入invoice出错", orderCode)
-			return false
-		}
-		if !util.Mysql.UpdateByTx(tx, "dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-		}, map[string]interface{}{
-			"applybill_status": 1,
-		}) {
-			log.Println("更新dataexport_order出错", orderCode)
-			return false
-		}
-		return true
-	}) {
-		return errors.New("用户端开票插入数据出错")
-	}
-	return nil
+    onlyIdentifying := fmt.Sprintf("%s%s%s", "aa", time.Now().Format("150405"), qutil.GetRandom(4))
+    orderInfo := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": orderCode}, "product_type,user_mail,pay_money,create_time,signing_subject,applybill_status", "")
+    if orderInfo == nil {
+        return errors.New("订单不存在")
+    }
+    createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", qutil.ObjToString((*orderInfo)["create_time"]), time.Local)
+    if createTime.Unix() < config.InvoiceConfig.Order_createtime {
+        return errors.New("2024年之前的订单不在开票")
+    }
+    if qutil.ObjToString((*orderInfo)["signing_subject"]) == "h02" {
+        return errors.New("签约主体为拓普")
+    }
+    /*if qutil.IntAll((*orderInfo)["applybill_status"]) != 0 {
+    	return errors.New("已提交发票信息")
+    }*/
+    invoicedMoney := InvoiceAmount(orderCode) //已开票金额
+    invoiceMoney := qutil.Int64All((*orderInfo)["pay_money"]) - invoicedMoney
+    if invoiceMoney == 0 {
+        return errors.New("开票金额已用完")
+    }
+    data["order_code"] = orderCode
+    data["invoice_order_code"] = orderCode
+    data["only_Identifying"] = onlyIdentifying
+    data["invoice_money"] = invoiceMoney
+    data["invoice_order_money"] = invoiceMoney
+    data["product_type"] = qutil.ObjToString((*orderInfo)["product_type"])
+    data["user_id"] = userId
+    data["source"] = 0
+    if !util.Mysql.ExecTx("用户端开发票", func(tx *sql.Tx) bool {
+        if util.Mysql.InsertByTx(tx, "invoice", data) <= 0 {
+            log.Println("插入invoice出错", orderCode)
+            return false
+        }
+        if !util.Mysql.UpdateByTx(tx, "dataexport_order", map[string]interface{}{
+            "order_code": orderCode,
+        }, map[string]interface{}{
+            "applybill_status": 1,
+        }) {
+            log.Println("更新dataexport_order出错", orderCode)
+            return false
+        }
+        return true
+    }) {
+        return errors.New("用户端开票插入数据出错")
+    }
+    return nil
 }
 
 func AdminOpenInvoice(onlyIdentifying, invoiceMoney, operator string, data map[string]interface{}) error {
-	//二维码
-	path := "/front/invoiceScan/qr"
-	urlStr := fmt.Sprintf("onlyIdentifying=%s&invoiceMoney=%s&operator=%s", encrypt.SE.EncodeString(onlyIdentifying), encrypt.SE.EncodeString(invoiceMoney), encrypt.SE.Encode2HexByCheck(operator))
-	fullUrl := path + "?" + urlStr
-	oldData := util.Mysql.FindOne("invoice", map[string]interface{}{
-		"only_Identifying": onlyIdentifying,
-	}, "id", "")
-	if oldData != nil {
-		return errors.New("该订单发票信息已经提交过申请")
-	}
-	orderArr := []string{}
-	mailOrderArr := []string{}
-	orderMap := map[string]interface{}{}
-	Allmoney := int64(0)
-	for _, v := range strings.Split(invoiceMoney, ",") {
-		invoiceMoneyArr := strings.Split(v, ":")
-		orderArr = append(orderArr, invoiceMoneyArr[0])
-		Allmoney += qutil.Int64All(invoiceMoneyArr[1])
-		orderMap[invoiceMoneyArr[0]] = invoiceMoneyArr[1]
-		prices := qutil.Float64All(invoiceMoneyArr[1]) / float64(100)
-		price := strconv.FormatFloat(prices, 'f', -1, 64)
-		mailOrderArr = append(mailOrderArr, fmt.Sprintf("%s(%s元)", invoiceMoneyArr[0], price))
-
-	}
-	//提交时订单金额再做一次校验
-	for orderCode, money := range orderMap {
-		payMoney, _ := ResidueMoney(orderCode)
-		if payMoney < qutil.Int64All(money) {
-			return errors.New("该订单发票信息已经提交过申请")
-		}
-	}
-	if !util.Mysql.ExecTx("发票信息保存", func(tx *sql.Tx) bool {
-		for orderCode, money := range orderMap {
-			orderInfo := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": orderCode}, "product_type,user_mail,user_id,create_time", "")
-			productType := ""
-			if orderInfo != nil {
-				productType = qutil.InterfaceToStr((*orderInfo)["product_type"])
-			}
-			createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", qutil.ObjToString((*orderInfo)["create_time"]), time.Local)
-			if createTime.Unix() < config.InvoiceConfig.Order_createtime {
-				log.Println("2024年之前的订单不在开票", orderCode)
-				return false
-			}
-			data["order_code"] = orderCode
-			data["invoice_order_code"] = strings.Join(orderArr, ",")
-			data["only_Identifying"] = onlyIdentifying
-			data["invoice_money"] = Allmoney
-			data["invoice_order_money"] = money
-			data["product_type"] = productType
-			data["user_id"] = qutil.ObjToString((*orderInfo)["user_id"])
-			data["operator"] = operator
-			data["source"] = 1
-			data["code_url"] = fullUrl
-			if util.Mysql.Insert("invoice", data) <= 0 {
-				log.Println("扫码开票插入invoice表出错", orderCode)
-				return false
-			}
-			//订单发票状态改成已申请
-			if !util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"order_code": orderCode,
-			}, map[string]interface{}{
-				"applybill_status": 1,
-			}) {
-				log.Println("扫码开票更新dataexport_order表出错", orderCode)
-				return false
-			}
-		}
-		return true
-	}) {
-		return errors.New("发票信息保存失败")
-	}
-	return nil
+    //二维码
+    path := "/front/invoiceScan/qr"
+    urlStr := fmt.Sprintf("onlyIdentifying=%s&invoiceMoney=%s&operator=%s", encrypt.SE.EncodeString(onlyIdentifying), encrypt.SE.EncodeString(invoiceMoney), encrypt.SE.Encode2HexByCheck(operator))
+    fullUrl := path + "?" + urlStr
+    oldData := util.Mysql.FindOne("invoice", map[string]interface{}{
+        "only_Identifying": onlyIdentifying,
+    }, "id", "")
+    if oldData != nil {
+        return errors.New("该订单发票信息已经提交过申请")
+    }
+    orderArr := []string{}
+    mailOrderArr := []string{}
+    orderMap := map[string]interface{}{}
+    Allmoney := int64(0)
+    for _, v := range strings.Split(invoiceMoney, ",") {
+        invoiceMoneyArr := strings.Split(v, ":")
+        orderArr = append(orderArr, invoiceMoneyArr[0])
+        Allmoney += qutil.Int64All(invoiceMoneyArr[1])
+        orderMap[invoiceMoneyArr[0]] = invoiceMoneyArr[1]
+        prices := qutil.Float64All(invoiceMoneyArr[1]) / float64(100)
+        price := strconv.FormatFloat(prices, 'f', -1, 64)
+        mailOrderArr = append(mailOrderArr, fmt.Sprintf("%s(%s元)", invoiceMoneyArr[0], price))
+
+    }
+    //提交时订单金额再做一次校验
+    for orderCode, money := range orderMap {
+        payMoney, _ := ResidueMoney(orderCode)
+        if payMoney < qutil.Int64All(money) {
+            return errors.New("该订单发票信息已经提交过申请")
+        }
+    }
+    if !util.Mysql.ExecTx("发票信息保存", func(tx *sql.Tx) bool {
+        for orderCode, money := range orderMap {
+            orderInfo := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": orderCode}, "product_type,user_mail,user_id,create_time", "")
+            productType := ""
+            if orderInfo != nil {
+                productType = qutil.InterfaceToStr((*orderInfo)["product_type"])
+            }
+            createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", qutil.ObjToString((*orderInfo)["create_time"]), time.Local)
+            if createTime.Unix() < config.InvoiceConfig.Order_createtime {
+                log.Println("2024年之前的订单不在开票", orderCode)
+                return false
+            }
+            data["order_code"] = orderCode
+            data["invoice_order_code"] = strings.Join(orderArr, ",")
+            data["only_Identifying"] = onlyIdentifying
+            data["invoice_money"] = Allmoney
+            data["invoice_order_money"] = money
+            data["product_type"] = productType
+            data["user_id"] = qutil.ObjToString((*orderInfo)["user_id"])
+            data["operator"] = operator
+            data["source"] = 1
+            data["code_url"] = fullUrl
+            if util.Mysql.Insert("invoice", data) <= 0 {
+                log.Println("扫码开票插入invoice表出错", orderCode)
+                return false
+            }
+            //订单发票状态改成已申请
+            if !util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "order_code": orderCode,
+            }, map[string]interface{}{
+                "applybill_status": 1,
+            }) {
+                log.Println("扫码开票更新dataexport_order表出错", orderCode)
+                return false
+            }
+        }
+        return true
+    }) {
+        return errors.New("发票信息保存失败")
+    }
+    return nil
 }
 
 func InvoiceFailRecord(oldOnlyIdentifying string) bool {
-	//开票失败再次提交
-	invoiceData := util.Mysql.Find("invoice", map[string]interface{}{"only_Identifying": oldOnlyIdentifying, "invoice_status": -1}, "", "", -1, -1)
-	if invoiceData == nil && len(*invoiceData) <= 0 {
-		log.Println("未找到开票记录", oldOnlyIdentifying)
-		return false
-	}
-	//插入开票失败记录表
-	ok := util.Mysql.ExecTx("插入开票失败记录表", func(tx *sql.Tx) bool {
-		for _, val := range *invoiceData {
-			delete(val, "id")
-			delete(val, "code_url")
-			if util.Mysql.InsertByTx(tx, "invoice_fail_record", val) <= 0 {
-				return false
-			}
-		}
-		return true
-	})
-	return ok
+    //开票失败再次提交
+    invoiceData := util.Mysql.Find("invoice", map[string]interface{}{"only_Identifying": oldOnlyIdentifying, "invoice_status": -1}, "", "", -1, -1)
+    if invoiceData == nil && len(*invoiceData) <= 0 {
+        log.Println("未找到开票记录", oldOnlyIdentifying)
+        return false
+    }
+    //插入开票失败记录表
+    ok := util.Mysql.ExecTx("插入开票失败记录表", func(tx *sql.Tx) bool {
+        for _, val := range *invoiceData {
+            delete(val, "id")
+            delete(val, "code_url")
+            if util.Mysql.InsertByTx(tx, "invoice_fail_record", val) <= 0 {
+                return false
+            }
+        }
+        return true
+    })
+    return ok
 }
 
 func (this *Invoice) GetCompanyCode() {
-	code := ""
-	companyInfo := util.Mysql.FindOne("entniche_info", map[string]interface{}{"name": this.GetString("companyName")}, "code", "")
-	if companyInfo != nil && len(*companyInfo) > 0 {
-		code = qutil.ObjToString((*companyInfo)["code"])
-	}
-	this.ServeJson(NewResult(map[string]interface{}{
-		"code": code,
-	}, nil))
-	return
+    code := ""
+    companyInfo := util.Mysql.FindOne("entniche_info", map[string]interface{}{"name": this.GetString("companyName")}, "code", "")
+    if companyInfo != nil && len(*companyInfo) > 0 {
+        code = qutil.ObjToString((*companyInfo)["code"])
+    }
+    this.ServeJson(NewResult(map[string]interface{}{
+        "code": code,
+    }, nil))
+    return
 }
 
 // 发票信息查询
 func (this *Invoice) InvoiceQuery() {
-	onlyIdentifying := encrypt.SE.DecodeString(this.GetString("onlyIdentifying"))
-	invoiceMoney := encrypt.SE.DecodeString(this.GetString("invoiceMoney"))
-	operator := ""
-	if onlyIdentifying == "" || invoiceMoney == "" {
-		this.ServeJson(NewResult("", errors.New("传入参数不正确")))
-		return
-	}
-	orderArr := []string{}
-	money := int64(0)
-	for _, v := range strings.Split(invoiceMoney, ",") {
-		invoiceMoneyArr := strings.Split(v, ":")
-		orderArr = append(orderArr, invoiceMoneyArr[0])
-		money += qutil.Int64All(invoiceMoneyArr[1])
-	}
-	var sData map[string]interface{}
-	invoiceOne := util.Mysql.FindOne("invoice", map[string]interface{}{
-		"only_Identifying": onlyIdentifying,
-	}, "id,invoice_changed,order_code, invoice_order_code,bank_account,invoice_code, create_time,invoice_number,company_phone,company_name, phone, mail,company_phone, invoice_type, invoice_content, url, invoice_status, invoice_serialnum, taxpayer_identnum,operator, operable_time, invoicing_entity, remark, invoice_variety, logistics_code, company_address, bank_name, recipient, delivery_address,only_Identifying", " create_time   DESC")
-	companyName := ""
-	if invoiceOne == nil {
-		//查询公司名称
-		querySQL := fmt.Sprintf("select company_name,user_phone  from   dataexport_order  where order_code  in  (%s)   and  company_name!=''   ORDER BY  create_time   DESC LIMIT 1", fmt.Sprintf("\"%s\"", strings.Join(orderArr, "\",\"")))
-		orderArr := util.Mysql.SelectBySql(querySQL)
-		if orderArr != nil && len(*orderArr) > 0 {
-			companyName = qutil.ObjToString((*orderArr)[0]["company_name"])
-			sData = ShowData(qutil.ObjToString((*orderArr)[0]["user_phone"]))
-			//回显内容
-		}
-	} else {
-		(*invoiceOne)["order_code"] = qutil.If((*invoiceOne)["invoice_order_code"] != nil, (*invoiceOne)["invoice_order_code"], (*invoiceOne)["order_code"])
-		(*invoiceOne)["id"] = encrypt.SE.Encode2Hex(qutil.InterfaceToStr((*invoiceOne)["id"]))
-		timeLimit := qutil.Int64All((*invoiceOne)["create_time"]) <= config.InvoiceConfig.Order_createtime //24年之前的发票不让换票
-		switch qutil.IntAll((*invoiceOne)["invoice_status"]) {
-		case 1:
-			isJyInvoice := !(qutil.InterfaceToStr((*invoiceOne)["invoice_number"]) != "" && qutil.InterfaceToStr((*invoiceOne)["invoice_code"]) == "") //非数电票
-			isJyEntity := (*invoiceOne)["invoicing_entity"] != nil && qutil.InterfaceToStr((*invoiceOne)["invoicing_entity"]) != config.InvoiceConfig.SigningSubject
-			isChanged := util.Mysql.Count("invoice", map[string]interface{}{
-				"only_Identifying": onlyIdentifying,
-				"order_code":       (*invoiceOne)["order_code"],
-			}) > 1
-			(*invoiceOne)["changed"] = qutil.If(isJyInvoice || isChanged || isJyEntity || timeLimit, true, false)
-		case -1: //失败支持重新提交否
-			if !timeLimit {
-				(*invoiceOne)["isReopen"] = util.Mysql.Count("invoice_fail_record", map[string]interface{}{
-					"only_Identifying": onlyIdentifying,
-					"order_code":       (*invoiceOne)["order_code"],
-				})+1 >= config.InvoiceConfig.SubmitNum
-			} else {
-				(*invoiceOne)["isReopen"] = false
-			}
-		}
-	}
-
-	this.ServeJson(NewResult(map[string]interface{}{
-		"orderCodes":   strings.Join(orderArr, ","),
-		"money":        money,
-		"invoice":      &invoiceOne,
-		"operator":     operator,
-		"company_name": companyName,
-		"showData":     sData, //回显近期信息
-		"isFollowWx":   1,
-	}, nil))
+    onlyIdentifying := encrypt.SE.DecodeString(this.GetString("onlyIdentifying"))
+    invoiceMoney := encrypt.SE.DecodeString(this.GetString("invoiceMoney"))
+    operator := ""
+    if onlyIdentifying == "" || invoiceMoney == "" {
+        this.ServeJson(NewResult("", errors.New("传入参数不正确")))
+        return
+    }
+    orderArr := []string{}
+    money := int64(0)
+    for _, v := range strings.Split(invoiceMoney, ",") {
+        invoiceMoneyArr := strings.Split(v, ":")
+        orderArr = append(orderArr, invoiceMoneyArr[0])
+        money += qutil.Int64All(invoiceMoneyArr[1])
+    }
+    var sData map[string]interface{}
+    invoiceOne := util.Mysql.FindOne("invoice", map[string]interface{}{
+        "only_Identifying": onlyIdentifying,
+    }, "id,invoice_changed,order_code, invoice_order_code,bank_account,invoice_code, create_time,invoice_number,company_phone,company_name, phone, mail,company_phone, invoice_type, invoice_content, url, invoice_status, invoice_serialnum, taxpayer_identnum,operator, operable_time, invoicing_entity, remark, invoice_variety, logistics_code, company_address, bank_name, recipient, delivery_address,only_Identifying", " create_time   DESC")
+    companyName := ""
+    if invoiceOne == nil {
+        //查询公司名称
+        querySQL := fmt.Sprintf("select company_name,user_phone  from   dataexport_order  where order_code  in  (%s)   and  company_name!=''   ORDER BY  create_time   DESC LIMIT 1", fmt.Sprintf("\"%s\"", strings.Join(orderArr, "\",\"")))
+        orderArr := util.Mysql.SelectBySql(querySQL)
+        if orderArr != nil && len(*orderArr) > 0 {
+            companyName = qutil.ObjToString((*orderArr)[0]["company_name"])
+            sData = ShowData(qutil.ObjToString((*orderArr)[0]["user_phone"]))
+            //回显内容
+        }
+    } else {
+        (*invoiceOne)["order_code"] = qutil.If((*invoiceOne)["invoice_order_code"] != nil, (*invoiceOne)["invoice_order_code"], (*invoiceOne)["order_code"])
+        (*invoiceOne)["id"] = encrypt.SE.Encode2Hex(qutil.InterfaceToStr((*invoiceOne)["id"]))
+        timeLimit := qutil.Int64All((*invoiceOne)["create_time"]) <= config.InvoiceConfig.Order_createtime //24年之前的发票不让换票
+        switch qutil.IntAll((*invoiceOne)["invoice_status"]) {
+        case 1:
+            isJyInvoice := !(qutil.InterfaceToStr((*invoiceOne)["invoice_number"]) != "" && qutil.InterfaceToStr((*invoiceOne)["invoice_code"]) == "") //非数电票
+            isJyEntity := (*invoiceOne)["invoicing_entity"] != nil && qutil.InterfaceToStr((*invoiceOne)["invoicing_entity"]) != config.InvoiceConfig.SigningSubject
+            isChanged := util.Mysql.Count("invoice", map[string]interface{}{
+                "only_Identifying": onlyIdentifying,
+                "order_code":       (*invoiceOne)["order_code"],
+            }) > 1
+            (*invoiceOne)["changed"] = qutil.If(isJyInvoice || isChanged || isJyEntity || timeLimit, true, false)
+        case -1: //失败支持重新提交否
+            if !timeLimit {
+                (*invoiceOne)["isReopen"] = util.Mysql.Count("invoice_fail_record", map[string]interface{}{
+                    "only_Identifying": onlyIdentifying,
+                    "order_code":       (*invoiceOne)["order_code"],
+                })+1 >= config.InvoiceConfig.SubmitNum
+            } else {
+                (*invoiceOne)["isReopen"] = false
+            }
+        }
+    }
+
+    this.ServeJson(NewResult(map[string]interface{}{
+        "orderCodes":   strings.Join(orderArr, ","),
+        "money":        money,
+        "invoice":      &invoiceOne,
+        "operator":     operator,
+        "company_name": companyName,
+        "showData":     sData, //回显近期信息
+        "isFollowWx":   1,
+    }, nil))
 }
 
 func ShowData(phone string) map[string]interface{} {
-	data := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT company_name,phone,mail,invoice_variety,invoice_type,company_address,bank_name,bank_account,remark,taxpayer_identnum FROM invoice WHERE phone = '%s' ORDER BY create_time desc LIMIT 1`, phone))
-	if data != nil && len(*data) > 0 {
-		return (*data)[0]
-	}
-	return nil
+    data := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT company_name,phone,company_phone,mail,invoice_variety,invoice_type,company_address,bank_name,bank_account,remark,taxpayer_identnum FROM invoice WHERE phone = '%s' ORDER BY create_time desc LIMIT 1`, phone))
+    if data != nil && len(*data) > 0 {
+        return (*data)[0]
+    }
+    return nil
 }
 
 // GetUserId 获取用户id从订单中
 func GetUserId(orderCode string) (userId string) {
-	rs := util.Mysql.SelectBySql(fmt.Sprintf("select user_id from %s where order_code=?", "dataexport_order"), orderCode)
-	if rs != nil && len(*rs) > 0 {
-		userId = qutil.ObjToString((*rs)[0]["userId"])
-	}
-	return userId
+    rs := util.Mysql.SelectBySql(fmt.Sprintf("select user_id from %s where order_code=?", "dataexport_order"), orderCode)
+    if rs != nil && len(*rs) > 0 {
+        userId = qutil.ObjToString((*rs)[0]["userId"])
+    }
+    return userId
 }
 
 // 调航天金税接口
 func htjs(body map[string]interface{}, orderCode []string, invoiceType, companyName, taxpayerIdentnum, mail, phone string) {
-	invoice_status := 0
-	client := &http.Client{}
-	b, _ := json.Marshal(body)
-	buffer := bytes.NewBuffer(b)
-	request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
-	response, err := client.Do(request)
-	if err == nil {
-		res, err := ioutil.ReadAll(response.Body)
-		if err != nil {
-			invoice_status = -1
-		} else {
-			resMap := qutil.ObjToMap(string(res))
-			if *resMap != nil {
-				if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
-					invoice_status = 1
-				} else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
-					invoice_status = 0
-				} else { //开票失败
-					invoice_status = -1
-				}
-			}
-			defer response.Body.Close()
-			resData := (*resMap)["data"].(map[string]interface{})
-			if invoice_status == 1 {
-				sendMail(invoiceType, strings.Join(orderCode, ","), companyName, taxpayerIdentnum, mail, phone, qutil.InterfaceToStr(resData["path"]), "")
-			}
-			for _, v := range orderCode {
-				util.Mysql.Update(dbname, map[string]interface{}{"order_code": v, "invoice_status": 0}, map[string]interface{}{
-					"invoice_serialnum": resData["swno"],
-					"invoice_code":      resData["fpdm"],
-					"invoice_number":    resData["fphm"],
-					"url":               resData["path"],
-					"invoice_status":    invoice_status,
-				})
-				//订单信息保存
-				updateData := map[string]interface{}{}
-				if InvoiceStatusHandle(v) {
-					updateData["applybill_status"] = 2
-				} else {
-					updateData["applybill_status"] = 3
-				}
-				util.Mysql.Update("dataexport_order", map[string]interface{}{
-					"order_code": v,
-				}, updateData)
-			}
-		}
-	}
+    invoice_status := 0
+    client := &http.Client{}
+    b, _ := json.Marshal(body)
+    buffer := bytes.NewBuffer(b)
+    request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
+    response, err := client.Do(request)
+    if err == nil {
+        res, err := ioutil.ReadAll(response.Body)
+        if err != nil {
+            invoice_status = -1
+        } else {
+            resMap := qutil.ObjToMap(string(res))
+            if *resMap != nil {
+                if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
+                    invoice_status = 1
+                } else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
+                    invoice_status = 0
+                } else { //开票失败
+                    invoice_status = -1
+                }
+            }
+            defer response.Body.Close()
+            resData := (*resMap)["data"].(map[string]interface{})
+            if invoice_status == 1 {
+                sendMail(invoiceType, strings.Join(orderCode, ","), companyName, taxpayerIdentnum, mail, phone, qutil.InterfaceToStr(resData["path"]), "")
+            }
+            for _, v := range orderCode {
+                util.Mysql.Update(dbname, map[string]interface{}{"order_code": v, "invoice_status": 0}, map[string]interface{}{
+                    "invoice_serialnum": resData["swno"],
+                    "invoice_code":      resData["fpdm"],
+                    "invoice_number":    resData["fphm"],
+                    "url":               resData["path"],
+                    "invoice_status":    invoice_status,
+                })
+                //订单信息保存
+                updateData := map[string]interface{}{}
+                if InvoiceStatusHandle(v) {
+                    updateData["applybill_status"] = 2
+                } else {
+                    updateData["applybill_status"] = 3
+                }
+                util.Mysql.Update("dataexport_order", map[string]interface{}{
+                    "order_code": v,
+                }, updateData)
+            }
+        }
+    }
 }
 
 // 判断是全额还是部分回款
 func InvoiceStatusHandle(orderCode string) bool {
-	orderData := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-		"order_code": orderCode,
-	}, "pay_money", "")
-	if orderData == nil {
-		return false
-	}
-	invoiceData := util.Mysql.SelectBySql("select sum(invoice_order_money) as  money  from  invoice where  order_code=?  and  invoice_status>=0  ", orderCode)
-	if invoiceData == nil || len(*invoiceData) == 0 {
-		return false
-	}
-	allMoney := qutil.Int64All((*invoiceData)[0]["money"])
-	pay_money := qutil.Int64All((*orderData)["pay_money"])
-	if pay_money == allMoney {
-		return true
-	}
-	return false
+    orderData := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+        "order_code": orderCode,
+    }, "pay_money", "")
+    if orderData == nil {
+        return false
+    }
+    invoiceData := util.Mysql.SelectBySql("select sum(invoice_order_money) as  money  from  invoice where  order_code=?  and  invoice_status>=0  ", orderCode)
+    if invoiceData == nil || len(*invoiceData) == 0 {
+        return false
+    }
+    allMoney := qutil.Int64All((*invoiceData)[0]["money"])
+    pay_money := qutil.Int64All((*orderData)["pay_money"])
+    if pay_money == allMoney {
+        return true
+    }
+    return false
 }
 
 // 电子普票发邮箱
 func sendMail(invoiceType, orderCode, companyName, taxpayerIdentnum, mail, phone, url, invoiceContent string) {
-	if invoiceType == "个人" {
-		emailHtml := emailHtml_gr
-		emailHtmls := fmt.Sprintf(emailHtml, phone, mail)
-		html := fmt.Sprintf(email_format, orderCode, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">查看发票</a>", url), "电子普通发票", invoiceContent, emailHtmls)
-		InvoiceSendMail(mail, html, "电子发票")
-	} else {
-		emailHtml := emailHtml_gs
-		emailHtmls := fmt.Sprintf(emailHtml, companyName, taxpayerIdentnum, phone, mail)
-		html := fmt.Sprintf(email_format, orderCode, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">查看发票</a>", url), "电子普通发票", invoiceContent, emailHtmls)
-		InvoiceSendMail(mail, html, "电子发票")
-	}
+    if invoiceType == "个人" {
+        emailHtml := emailHtml_gr
+        emailHtmls := fmt.Sprintf(emailHtml, phone, mail)
+        html := fmt.Sprintf(email_format, orderCode, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">查看发票</a>", url), "电子普通发票", invoiceContent, emailHtmls)
+        InvoiceSendMail(mail, html, "电子发票")
+    } else {
+        emailHtml := emailHtml_gs
+        emailHtmls := fmt.Sprintf(emailHtml, companyName, taxpayerIdentnum, phone, mail)
+        html := fmt.Sprintf(email_format, orderCode, "电子普通发票", fmt.Sprintf("<a href=\"%s\" download class=\"download\">查看发票</a>", url), "电子普通发票", invoiceContent, emailHtmls)
+        InvoiceSendMail(mail, html, "电子发票")
+    }
 }
 
 // 剩余金额
 func InvoicePrice(orderData map[string]interface{}) int64 {
-	residueMoney := int64(0)
-	if qutil.Int64All(orderData["applybill_status"]) == 2 {
-		return residueMoney
-	}
+    residueMoney := int64(0)
+    if qutil.Int64All(orderData["applybill_status"]) == 2 {
+        return residueMoney
+    }
 
-	return qutil.Int64All(orderData["pay_money"]) - InvoiceAmount(qutil.InterfaceToStr(orderData["order_code"]))
+    return qutil.Int64All(orderData["pay_money"]) - InvoiceAmount(qutil.InterfaceToStr(orderData["order_code"]))
 }
 
 // 订单剩余金额查询
 func ResidueMoney(orderCode string) (int64, string) {
-	residueMoney := int64(0)
-	//订单信息查询
-	orderData := util.Mysql.SelectBySql("select  pay_money,applybill_status,user_phone from  dataexport_order  where  order_code =?", orderCode)
-	if len(*orderData) == 0 || orderData == nil {
-		return residueMoney, ""
-	}
-	return InvoicePrice((*orderData)[0]), qutil.InterfaceToStr((*orderData)[0]["user_phone"])
-
-	//发票信息查询
-	//invoiceData := util.Mysql.SelectBySql("select invoice_status,sum(invoice_order_money) as  money  from  invoice where  order_code=?  and  invoice_status>=0  GROUP BY  invoice_status", orderCode)
-	//if len(*orderData) == 0 || orderData == nil {
-	//} else {
-	//    //开过几次票
-	//    payMoney := qutil.Int64All((*orderData)[0]["pay_money"])
-	//    allMoney := int64(0)
-	//    for _, invoice := range *invoiceData {
-	//        invoice_status := qutil.Int64All(invoice["invoice_status"])
-	//        money := qutil.Int64All(invoice["money"])
-	//        if invoice_status == 0 {
-	//            return residueMoney
-	//        } else {
-	//            allMoney += money
-	//        }
-	//    }
-	//    residueMoney = payMoney - allMoney
-	//}
-	//return residueMoney
+    residueMoney := int64(0)
+    //订单信息查询
+    orderData := util.Mysql.SelectBySql("select  pay_money,applybill_status,user_phone from  dataexport_order  where  order_code =?", orderCode)
+    if len(*orderData) == 0 || orderData == nil {
+        return residueMoney, ""
+    }
+    return InvoicePrice((*orderData)[0]), qutil.InterfaceToStr((*orderData)[0]["user_phone"])
+
+    //发票信息查询
+    //invoiceData := util.Mysql.SelectBySql("select invoice_status,sum(invoice_order_money) as  money  from  invoice where  order_code=?  and  invoice_status>=0  GROUP BY  invoice_status", orderCode)
+    //if len(*orderData) == 0 || orderData == nil {
+    //} else {
+    //    //开过几次票
+    //    payMoney := qutil.Int64All((*orderData)[0]["pay_money"])
+    //    allMoney := int64(0)
+    //    for _, invoice := range *invoiceData {
+    //        invoice_status := qutil.Int64All(invoice["invoice_status"])
+    //        money := qutil.Int64All(invoice["money"])
+    //        if invoice_status == 0 {
+    //            return residueMoney
+    //        } else {
+    //            allMoney += money
+    //        }
+    //    }
+    //    residueMoney = payMoney - allMoney
+    //}
+    //return residueMoney
 }