package eta_business

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

const (
	EtaBusinessSigningStatusFirst = iota + 1
	EtaBusinessSigningStatusContinue
	EtaBusinessSigningStatusTerminate
	EtaBusinessSigningStatusWait
)

type EtaBusiness struct {
	EtaBusinessId    int       `orm:"column(eta_business_id);pk"`
	BusinessName     string    `description:"商家名称"`
	BusinessCode     string    `description:"商家编码"`
	CodeEncrypt      string    `description:"商家编码加密"`
	CreditCode       string    `description:"社会统一信用码"`
	RegionType       string    `description:"所属区域：国内；海外"`
	Province         string    `description:"省份"`
	City             string    `description:"城市"`
	Address          string    `description:"商家地址"`
	SellerId         int       `description:"销售ID"`
	SellerName       string    `description:"销售名称"`
	Leader           string    `description:"决策人"`
	IndustryId       int       `description:"行业ID"`
	IndustryName     string    `description:"行业名称"`
	CapitalScale     string    `description:"资金规模"`
	ResearchTeamSize string    `description:"研究团队规模"`
	UserMax          int       `description:"用户上限"`
	SigningStatus    int       `description:"签约状态：1-首次签约；2-续约中；3-已终止；4-待签约"`
	Enable           int       `description:"状态：0-禁用；1-启用"`
	ContractId       int       `description:"当前合约ID"`
	SigningTime      time.Time `description:"当前合约的签约时间"`
	ExpiredTime      time.Time `description:"当前合约的到期时间"`
	CreateTime       time.Time `description:"创建时间"`
	ModifyTime       time.Time `description:"更新时间"`
	Nation           string    `description:"所属国家"`
}

func (m *EtaBusiness) TableName() string {
	return "eta_business"
}

func (m *EtaBusiness) PrimaryId() string {
	return EtaBusinessColumns.EtaBusinessId
}

var EtaBusinessColumns = struct {
	EtaBusinessId    string
	BusinessName     string
	BusinessCode     string
	CreditCode       string
	RegionType       string
	Province         string
	City             string
	Address          string
	SellerId         string
	SellerName       string
	Leader           string
	IndustryId       string
	IndustryName     string
	CapitalScale     string
	ResearchTeamSize string
	UserMax          string
	SigningStatus    string
	Enable           string
	ContractId       string
	SigningTime      string
	ExpiredTime      string
	CreateTime       string
	ModifyTime       string
}{
	EtaBusinessId:    "eta_business_id",
	BusinessName:     "business_name",
	BusinessCode:     "business_code",
	CreditCode:       "credit_code",
	RegionType:       "region_type",
	Province:         "province",
	City:             "city",
	Address:          "address",
	SellerId:         "seller_id",
	SellerName:       "seller_name",
	Leader:           "leader",
	IndustryId:       "industry_id",
	IndustryName:     "industry_name",
	CapitalScale:     "capital_scale",
	ResearchTeamSize: "research_team_size",
	UserMax:          "user_max",
	SigningStatus:    "signing_status",
	Enable:           "enable",
	ContractId:       "contract_id",
	SigningTime:      "signing_time",
	ExpiredTime:      "expired_time",
	CreateTime:       "create_time",
	ModifyTime:       "modify_time",
}

func (m *EtaBusiness) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EtaBusinessId = int(id)
	return
}

func (m *EtaBusiness) CreateMulti(items []*EtaBusiness) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *EtaBusiness) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *EtaBusiness) Del() (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	_, err = o.Raw(sql, m.EtaBusinessId).Exec()
	return
}

func (m *EtaBusiness) GetItemById(id int) (item *EtaBusiness, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *EtaBusiness) GetItemByCondition(condition string, pars []interface{}) (item *EtaBusiness, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s LIMIT 1`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *EtaBusiness) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *EtaBusiness) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*EtaBusiness, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *EtaBusiness) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*EtaBusiness, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// CreateEtaBusinessAndContract 新增商家和签约
func CreateEtaBusinessAndContract(businessItem *EtaBusiness, contractItem *EtaBusinessContract) (err error) {
	if businessItem == nil {
		err = fmt.Errorf("item empty")
		return
	}

	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	// 商家
	businessId, e := tx.Insert(businessItem)
	if e != nil {
		err = fmt.Errorf("business insert err: %s", e.Error())
		return
	}
	businessItem.EtaBusinessId = int(businessId)

	// 签约
	if contractItem != nil {
		contractItem.EtaBusinessId = businessItem.EtaBusinessId
		contractId, e := tx.Insert(contractItem)
		if e != nil {
			err = fmt.Errorf("contract insert err: %s", e.Error())
			return
		}

		// 更新商家当前签约ID
		businessItem.ContractId = int(contractId)
		cols := []string{"ContractId"}
		_, err = tx.Update(businessItem, cols...)
	}
	return
}

// EtaBusinessAddReq 新增商家请求体
type EtaBusinessAddReq struct {
	BusinessName     string `description:"商家名称"`
	CreditCode       string `description:"社会统一信用码"`
	RegionType       string `description:"所属区域：国内；海外"`
	Province         string `description:"省份"`
	City             string `description:"城市"`
	SellerId         int    `description:"销售ID"`
	SellerName       string `description:"销售名称"`
	Leader           string `description:"决策人"`
	IndustryId       int    `description:"行业ID"`
	IndustryName     string `description:"行业名称"`
	CapitalScale     string `description:"资金规模"`
	ResearchTeamSize string `description:"研究团队规模"`
	UserMax          int    `description:"用户上限"`
	SigningTime      string `description:"签约时间"`
	ExpiredTime      string `description:"到期时间"`
	IsCheck          bool   `description:"是否只做校验而不实际新增(业务操作上基础信息和签约时间分成两个步骤了)"`
	Nation           string `description:"所属国家"`
}

// EtaBusinessEditReq 编辑商家请求体
type EtaBusinessEditReq struct {
	EtaBusinessId    int    `description:"商家ID"`
	Province         string `description:"省份"`
	City             string `description:"城市"`
	Leader           string `description:"决策人"`
	IndustryId       int    `description:"行业ID"`
	IndustryName     string `description:"行业名称"`
	CapitalScale     string `description:"资金规模"`
	ResearchTeamSize string `description:"研究团队规模"`
	UserMax          int    `description:"用户上限"`
	Nation           string `description:"所属国家"`
}

// EtaBusinessSigningReq 商家签约请求体
type EtaBusinessSigningReq struct {
	EtaBusinessId int    `description:"商家ID"`
	SigningTime   string `description:"当前合约的签约时间"`
	ExpiredTime   string `description:"当前合约的到期时间"`
}

// EtaBusinessEnableReq 禁启用商家请求体
type EtaBusinessEnableReq struct {
	EtaBusinessId int `description:"商家ID"`
}

// EtaBusinessMoveSellerReq 移动商家销售请求体
type EtaBusinessMoveSellerReq struct {
	EtaBusinessId int    `description:"商家ID"`
	SellerId      int    `description:"销售ID"`
	SellerName    string `description:"销售名称"`
}

// CreateEtaBusinessCode 生成ETA商家编码
func CreateEtaBusinessCode() (code string, err error) {
	var num int
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS num FROM eta_business WHERE create_time >= ? `
	err = o.Raw(sql, time.Now().Format(utils.FormatDate)).QueryRow(&num)
	if err != nil {
		return
	}
	code = "E" + time.Now().Format("20060102") + fmt.Sprintf("%02d", num)
	return
}

// EtaBusinessListResp 商家分页列表响应体
type EtaBusinessListResp struct {
	List   []*EtaBusinessItem `description:"商家列表数据"`
	Paging *paging.PagingItem `description:"分页数据"`
}

// EtaBusinessItem ETA商家信息
type EtaBusinessItem struct {
	EtaBusinessId    int
	BusinessName     string `description:"商家名称"`
	BusinessCode     string `description:"商家编码"`
	CreditCode       string `description:"社会统一信用码"`
	RegionType       string `description:"所属区域：国内；海外"`
	Province         string `description:"省份"`
	City             string `description:"城市"`
	Address          string `description:"商家地址"`
	SellerId         int    `description:"销售ID"`
	SellerName       string `description:"销售名称"`
	Leader           string `description:"决策人"`
	IndustryId       int    `description:"行业ID"`
	IndustryName     string `description:"行业名称"`
	CapitalScale     string `description:"资金规模"`
	ResearchTeamSize string `description:"研究团队规模"`
	UserMax          int    `description:"用户上限"`
	SigningStatus    int    `description:"签约状态：1-首次签约；2-续约中；3-已终止"`
	Enable           int    `description:"状态：0-禁用；1-启用"`
	ContractId       int    `description:"当前合约ID"`
	SigningTime      string `description:"当前合约的签约时间"`
	ExpiredTime      string `description:"当前合约的到期时间"`
	CreateTime       string `description:"创建时间"`
	ModifyTime       string `description:"更新时间"`
	Nation           string `description:"所属国家"`
}

// EtaBusinessEditSignReq 编辑商家签约请求体
type EtaBusinessEditSignReq struct {
	EtaBusinessContractId int    `description:"商家合约ID"`
	SigningTime           string `description:"当前合约的签约时间"`
	ExpiredTime           string `description:"当前合约的到期时间"`
}

// EtaBusinessRemoveSignReq 删除商家签约请求体
type EtaBusinessRemoveSignReq struct {
	EtaBusinessContractId int `description:"商家合约ID"`
}
