package dao

import (
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/model"
	"time"
)

func GetInvoiceInfo(db *DaoDB, vendorOrderId string) (data *model.InvoiceMsg, err error) {
	sql := ` SELECT * FROM invoice_msg WHERE order_id = ? OR remark LIKE ?`
	err = GetRow(db, &data, sql, []interface{}{vendorOrderId, "%" + fmt.Sprintf("%s", vendorOrderId) + "%"}...)
	return data, err
}

func GetStoreInvoiceList(storeID, vendorId int, startTime, endTime time.Time, status string, offset, pageSize int) (info *model.PagedInfo, err error) {
	parameter := []interface{}{}
	sql := ` SELECT * FROM invoice_msg WHERE 1=1 `
	if storeID != 0 {
		sql += ` AND store_id  = ? `
		parameter = append(parameter, storeID)
	}
	if !utils.IsTimeZero(startTime) {
		sql += ` AND created_at  >= ? `
		parameter = append(parameter, startTime)
	}
	if !utils.IsTimeZero(endTime) {
		sql += ` AND created_at  <= ? `
		parameter = append(parameter, endTime)
	}
	if vendorId != 0 {
		sql += ` AND vendor_id  = ? `
		parameter = append(parameter, vendorId)
	}
	if status != "" {
		switch status {
		case "1": // 未回复
			sql += ` AND invoice_url = ""`
		case "2": // 已回复
			sql += ` AND invoice_url <> ""`
		}
	}
	sql += " LIMIT ? OFFSET ?"
	parameter = append(parameter, jxutils.FormalizePageSize(pageSize), offset)
	db := GetDB()
	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	data := make([]*model.InvoiceMsg, 0, 0)
	if err = GetRowsTx(txDB, &data, sql, parameter...); err == nil {
		pagedInfo := &model.PagedInfo{
			TotalCount: GetLastTotalRowCount2(db, txDB),
			Data:       data,
		}
		return pagedInfo, nil
	}

	return nil, err
}

func GetInvoiceInfoByTaskId(db *DaoDB, taskId string) (*model.InvoiceMsg, error) {
	data := &model.InvoiceMsg{}
	sql := ` SELECT * FROM invoice_msg WHERE invoice_task_id = ?`
	err := GetRow(db, data, sql, []interface{}{taskId}...)
	return data, err
}

func GetInvoiceByStoreId(db *DaoDB, storeId, vendorId int) ([]*model.InvoiceMsg, error) {
	param := []interface{}{}
	data := make([]*model.InvoiceMsg, 0, 0)
	sql := ` SELECT * FROM invoice_msg WHERE store_id = ? `
	param = append(param, storeId)
	if vendorId != 0 {
		sql += ` AND vendor_id = ?`
		param = append(param, vendorId)

	}
	err := GetRows(db, data, sql, param...)
	return data, err
}
