// Models generated by mesh dev cli,@Author: David Yan(david.yan@qq.com).
package models

import (
	"time"

	"git.apinb.com/bsm-sdk/core/types"
	"gorm.io/gorm"
)

// OrderSummary 订单表/*
type OrderSummary struct {
	gorm.Model
	types.Std_Identity
	types.Std_Passport

	// 订单信息
	OrderNo         string `gorm:"column:order_no;type:varchar(36);index;not null;" json:"order_no"`           // 订单号
	StoreID         uint   `gorm:"column:store_id;Index;"`                                                     // 店铺ID
	StoreIdentity   string `gorm:"column:store_identity;type:varchar(36);Index;"`                              // 店铺唯一标识，24位NanoID,36位为UUID
	PartnerID       int32  `gorm:"column:partner_id;default:0;" json:"partner_id"`                             // 分销商id
	TotalPrice      int64  `gorm:"column:total_price;default:0;" json:"total_price"`                           // 订单金额
	LogisticsFee    int64  `gorm:"column:logistics_fee;default:0;" json:"logistics_fee"`                       // 运费
	TransPrice      int64  `gorm:"column:trans_price;default:0;" json:"trans_price"`                           // 订单金额（实际）
	RefundPrice     int64  `gorm:"column:refund_price;default:0;" json:"refund_price"`                         // 已退款金额
	CouponIdentity  string `gorm:"column:coupon_identity;type:varchar(64);default:'';" json:"coupon_identity"` // 优惠卷唯一码
	CouponAmount    int64  `gorm:"column:coupon_amount;default:0;" json:"coupon_amount"`                       // 优惠金额
	Remark          string `gorm:"column:remark;type:text;default:'';" json:"remark"`                          // 备注
	Args            string `gorm:"column:args;type:text;default:'';" json:"args"`                              // 相关参数
	Status          int32  `gorm:"default:0;index;" json:"status"`                                             // 订单状态 1：未支付 2：已支付 3：已发货 4：已收货 5:已完成  6:已收货退款 7：未发货退款 8:已退货 -1：已取消
	AddressIdentity string `gorm:"column:address_identity;type:varchar(36);"`                                  // 地址库唯一标识，24位NanoID,36位为UUID
	County          string `gorm:"column:county;type:varchar(255);default:'';" json:"county"`                  // 国家
	Province        string `gorm:"column:province;type:varchar(50);default:'';" json:"province"`               // 省
	City            string `gorm:"column:city;type:varchar(255);default:'';" json:"city"`                      // 市
	Area            string `gorm:"column:area;type:varchar(255);default:'';" json:"area"`                      // 县
	Address         string `gorm:"column:address;type:varchar(255);default:'';" json:"address"`                // 详细地址
	Contact         string `gorm:"column:contact;type:varchar(50);default:'';" json:"contact"`                 // 联系人
	Phone           string `gorm:"column:phone;type:varchar(50);default:'';" json:"phone"`                     // 联系电话
	Approve         int8   `gorm:"column:approve;default:0;" json:"approve"`                                   // 状态：-2：未通过，0：默认 1:申请退款 2:申请退货 3：申请退款退货 4：申请通过
	Reason          string `gorm:"column:reason;type:varchar(255);default:'';" json:"reason"`                  //退货原因

	// 配送信息
	LogisticsNumber  string `gorm:"column:logistics_number;type:varchar(64);default:'';" json:"logistics_number"` // 物流号
	DeliveryTime     string `gorm:"column:delivery_time;type:varchar(255);" json:"delivery_time"`                 // 配送时间
	DeliveryAddress  string `gorm:"column:delivery_address;type:varchar(255);" json:"delivery_address"`           // 配送地址
	DeliveryIdentity string `gorm:"column:delivery_identity;type:varchar(36);" json:"delivery_identity"`          // 配送工作人员唯一标识，24位NanoID,36位为UUID
	CarIdentity      string `gorm:"column:car_identity;type:varchar(36);" json:"car_identity"`                    // 配送车辆唯一标识，24位NanoID,36位为UUID
	CarBrand         string `gorm:"column:car_brand;type:varchar(255);default:'';" json:"car_brand"`              // 配送车辆品牌
	CarVersion       string `gorm:"column:car_version;type:varchar(255);default:'';" json:"car_version"`          // 配送车辆型号
	LicenseNumber    string `gorm:"column:license_number;type:varchar(255);default:'';" json:"license_number"`    // 配送车辆车牌号
	MemberName       string `gorm:"column:member_name;type:varchar(255);default:'';" json:"member_name"`          // 配送人员名称
	MemberPhone      string `gorm:"column:member_phone;type:varchar(255);default:'';" json:"member_phone"`        // 配送人员电话

	// 支付信息
	PayType    int8      `gorm:"column:pay_type;default:0;" json:"pay_type"`                           // 支付类型：0:待支付，1:线下支付，2:微信 3:支付宝,4:余额
	PayAmount  int64     `gorm:"column:pay_amount;default:0;" json:"pay_amount"`                       // 支付金额
	PayTradeNo string    `gorm:"column:pay_trade_no;type:varchar(36);default:'';" json:"pay_trade_no"` // 支付交易号
	PayTime    time.Time `gorm:"column:pay_time;" json:"pay_time"`                                     // 支付时间
	PayRemark  string    `gorm:"column:pay_remark;type:text;default:'';" json:"pay_remark"`            // 支付备注

	OrderDetails []OrderDetails `gorm:"foreignKey:SummaryIdentity;references:Identity;" json:"details"` // 订单详情
}

// TableName .
func (table *OrderSummary) TableName() string {
	return "order_summary" //对应数据库表名
}

// GetSummaryCnt 获取各类型订单数量
func GetSummaryCnt(identity, types string) ([]*SummaryCnt, error) {
	var data = make([]*SummaryCnt, 0)
	tx := DBService.Model(&OrderSummary{}).Select("status, count(status) cnt").Where("type = 1")
	if types == "buy" {
		tx = tx.Where("buyer_identity = ?", identity)
	} else if types == "sell" {
		tx = tx.Where("merchant_identity = ?", identity)
	}
	err := tx.Group("status").Find(&data).Error
	return data, err
}

// GetSummaryList 获取订单列表
func GetSummaryList(types, org, orderNo, productName, startTime, endTime string, page, size, status, minPrice, maxPrice, payStatus, logisticsStatus, invoiceStatus int) ([]*OrderSummary, int64, error) {
	var orderList = make([]*OrderSummary, 0)
	var cnt int64 = 0
	var tx = DBService.Model(&OrderSummary{}).Preload("OrderDetails").Where("type = 1")

	if productName != "" {
		var idList = []string{} // 获取包含title的数据
		err := DBService.Model(&OrderDetails{}).Select("summary_identity").Where("title like ?", "%"+productName+"%").Find(&idList).Error
		if err != nil {
			return nil, 0, err
		}
		tx = tx.Where("identity in ?", idList)
	}
	if types == "buy" {
		// 采购订单
		tx = tx.Where("buyer_identity =  ?", org)
	} else if types == "sell" {
		// 销售订单
		tx = tx.Where("merchant_identity =  ?", org)
	}
	if orderNo != "" {
		tx = tx.Where("order_no =  ?", orderNo)
	}
	if startTime != "" {
		// 按时间查询
		if endTime == "" {
			tx = tx.Where("created_at > ?", startTime)
		} else {
			tx = tx.Where("created_at between ? and ?", startTime, endTime)
		}
	} else {
		if endTime != "" {
			tx = tx.Where("created_at < ?", endTime)
		}
	}
	if minPrice != 0 {
		// 按价格查询
		if maxPrice == 0 {
			tx = tx.Where("trans_price > ?", minPrice)
		} else {
			tx = tx.Where("trans_price between ? and ?", minPrice, maxPrice)
		}
	} else {
		if maxPrice != 0 {
			tx = tx.Where("trans_price < ?", maxPrice)
		}
	}
	if payStatus != 0 {
		tx = tx.Where("pay_status  = ?", maxPrice)

	}
	if logisticsStatus != 0 {
		tx = tx.Where("logistics_status = ?", logisticsStatus)
	}
	if invoiceStatus != 0 {
		tx = tx.Where("invoice_status = ?", invoiceStatus)
	}
	if status != 0 {
		if status == 2 {
			tx = tx.Where("sign_status  in ?", []int64{1, 2, 3})
		}
		tx = tx.Where("status  = ?", status)
	}
	err := tx.Order("created_at desc").Count(&cnt).Limit(size).Offset((page - 1) * size).Find(&orderList).Error
	if err != nil {
		return nil, 0, err
	}
	return orderList, cnt, nil
}
