package models

import (
	"fmt"
	"go-admin/app/admin/models/common"
	orm "go-admin/common/global"
	"go-admin/logger"
	"gorm.io/gorm"
)

type Supplier struct {
	Model

	Number                string             `json:"number" gorm:"index"`                  // 编号
	Name                  string             `json:"name"`                                 // 供应商名称
	Province              string             `json:"province"`                             // 省
	City                  string             `json:"city"`                                 // 市
	Area                  string             `json:"area"`                                 // 区
	Address               string             `json:"address"`                              // 详细地址
	Contact               string             `json:"contact"`                              // 联系人
	Tel                   string             `json:"tel"`                                  // 手机号
	Landline              string             `json:"landline"`                             // 座机电话
	Email                 string             `json:"email"`                                // 电子邮件
	CompanyWebsite        string             `json:"company_website"`                      // 公司网址
	PaymentCycle          uint32             `json:"payment_cycle"`                        // 付款周期/天
	TaxNumber             string             `json:"tax_number"`                           // 税号
	CooperativeBusinessId uint32             `json:"cooperative_business_id"`              // 合作商id
	AccountHolder         string             `json:"account_holder"`                       // 开户人
	OpeningBank           string             `json:"opening_bank"`                         // 开户银行
	BankAccount           string             `json:"bank_account"`                         // 银行账号
	BankData              string             `gorm:"type:json" json:"bank_data,omitempty"` // 开户银行信息
	BankList              []SupplierBankInfo `json:"bank_list" gorm:"-" `                  // 开户银行信息列表
}

// SupplierBankInfo 开户银行信息列表
type SupplierBankInfo struct {
	AccountHolder string `json:"account_holder"` // 开户人
	OpeningBank   string `json:"opening_bank"`   // 开户银行
	BankAccount   string `json:"bank_account"`   // 银行账号
}

func (s *Supplier) TableName() string {
	return "erp_supplier"
}

func (s *Supplier) BeforeCreate(tx *gorm.DB) error {
	if s.Number == "" {
		var count int64
		err := tx.Table(s.TableName()).
			Unscoped().
			Scopes(common.ScopeBusiness(s.CooperativeBusinessId)).
			Count(&count).Error
		if err != nil {
			logger.Error("get supplier count failed", logger.Field("err", err), logger.Field("s", s))
			return err
		}
		s.Number = fmt.Sprintf("%03d", count+1)
	}
	return nil
}

type GetSupplierRequest struct {
	Name                  string //供应商名称
	Number                string //供应商编号
	CooperativeBusinessId uint32 //合作商id
	PageIndex             int    `json:"pageIndex"` // 页码
	PageSize              int    `json:"pageSize"`  // 每页展示数据条数
}

type GetSupplierResp struct {
	List      []Supplier `json:"list"`
	Total     int        `json:"total"`     // 数据总条数
	PageIndex int        `json:"pageIndex"` // 页码
	PageSize  int        `json:"pageSize"`  // 每页展示条数
}

func GetSupplier(req *GetSupplierRequest) (*GetSupplierResp, error) {
	resp := &GetSupplierResp{
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
	}
	page := req.PageIndex - 1
	if page < 0 {
		page = 0
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	var list []Supplier
	m := orm.Eloquent.Model(Supplier{})
	if req.Name != "" {
		m = m.Where("name = ?", req.Name)
	}

	if req.Number != "" {
		m = m.Where("number = ?", req.Number)
	}

	m = m.Scopes(common.ScopeBusiness(req.CooperativeBusinessId))

	var count int64
	err := m.Count(&count).Error
	if err != nil {
		return nil, fmt.Errorf("query count err:%v", err)
	}

	offset := page * req.PageSize
	limit := req.PageSize
	err = m.Order("created_at desc").Offset(offset).Limit(limit).Find(&list).Error
	if err != nil {
		logger.Error("get supplier list err", logger.Field("err", err), logger.Field("req", req))
		return nil, err
	}

	// 反序列化 BankData
	for i, v := range list {
		if list[i].BankData != "" {
			list[i].BankList = DeserializeBankData(v.BankData)
			list[i].BankData = ""
		}
	}

	resp.List = list

	//跟之前保持一致
	resp.Total = int(count)
	resp.PageIndex = page + 1
	resp.PageSize = req.PageSize

	return resp, nil
}

func GetSupplierById(id uint32) (*Supplier, error) {
	var supplier Supplier
	err := orm.Eloquent.Table("erp_supplier").Where("id=?", id).Find(&supplier).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		return &supplier, err
	}
	return &supplier, nil
}
