/**
* @Author: zou.yingbin
* @Create  : 2021/1/13 11:16
* @Modify  : 2021/1/13 11:16
 */

package models

import (
	"fmt"
	"mtp2_if/db"
	"mtp2_if/logger"
	"mtp2_if/mtpcache"
	"mtp2_if/utils"
)

// 现货商品表
type ErmcpWrstandard struct {
	WRSTANDARDID    int64  `json:"wrstandardid"  xorm:"'WRSTANDARDID'"`       // 现货商品ID(SEQ_WRSTANDARD)
	WRSTANDARDCODE  string `json:"wrstandardcode"  xorm:"'WRSTANDARDCODE'"`   // 现货商品代码
	DELIVERYGOODSID int32  `json:"deliverygoodsid"  xorm:"'DELIVERYGOODSID'"` // 品种ID
	UNITID          int32  `json:"unitid"  xorm:"'UNITID'"`                   // 单位ID
	MINIVALUE       int32  `json:"minivalue"  xorm:"'MINIVALUE'"`             // 最小变动值
	MINIVALUEDP     int32  `json:"minivaluedp"  xorm:"'MINIVALUEDP'"`         // 最小变动值小数位
	REALMINIVALUE   int32  `json:"realminivalue"  xorm:"'REALMINIVALUE'"`     // 实际最小变动值
	REALMINIVALUEDP int32  `json:"realminivaluedp"  xorm:"'REALMINIVALUEDP'"` // 实际最小变动值小数位
	CREATORID       int64  `json:"creatorid"  xorm:"'CREATORID'"`             // 创建人
	CREATETIME      string `json:"createtime"  xorm:"'CREATETIME'"`           // 创建时间
	WRSTANDARDNAME  string `json:"wrstandardname"  xorm:"'WRSTANDARDNAME'"`   // 现货商品名称
	AREAUSERID      int    `json:"areauserid"  xorm:"'AREAUSERID'"`           // 所属机构
	EnumdicName     string `json:"enumdicname"`                               // 单位名称
	ISVALID         int32  `json:"isvalid"  xorm:"'ISVALID'"`                 // 是否有效 0-无效(停用) 1-有效(正常)
	UPDATETIME      string `json:"updatetime"  xorm:"'UPDATETIME'"`           // 更新时间
	REMARK          string `json:"remark"  xorm:"'REMARK'"`                   // 备注
}

func (r *ErmcpWrstandard) buildSql() string {
	str := "select WRSTANDARDID," +
		"       WRSTANDARDCODE," +
		"       DELIVERYGOODSID," +
		"       UNITID," +
		"       MINIVALUE," +
		"       MINIVALUEDP," +
		"       REALMINIVALUE," +
		"       REALMINIVALUEDP," +
		"       CREATORID," +
		"       to_char(CREATETIME, 'yyyy-mm-dd hh24:mi:ss') CREATETIME," +
		"       WRSTANDARDNAME," +
		"       ISVALID," +
		"       to_char(UPDATETIME, 'yyyy-mm-dd hh24:mi:ss') UPDATETIME," +
		"       REMARK," +
		"       AREAUSERID" +
		"  from wrstandard t" +
		" where t.AREAUSERID=%v"
	sqlId := fmt.Sprintf(str, r.AREAUSERID)
	if r.WRSTANDARDID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and WRSTANDARDID=%v", r.WRSTANDARDID)
	}
	if r.ISVALID >= 0 {
		sqlId = sqlId + fmt.Sprintf(" and t.ISVALID=%v", r.ISVALID)
	}
	sqlId += " order by createtime desc"
	return sqlId
}

// GetData 查询现货商品
func (r *ErmcpWrstandard) GetData() ([]ErmcpWrstandard, error) {
	sData := make([]ErmcpWrstandard, 0)
	e := db.GetEngine()
	if err := e.SQL(r.buildSql()).Find(&sData); err != nil {
		logger.GetLogger().Errorf("query wrstardard fail, %v", err)
		return sData, err
	}
	return sData, nil
}

// GoodsTypeModel 商品型号表
type GoodsTypeModel struct {
	MODELID         int     `json:"modelid"  xorm:"'MODELID'"`             // 型号ID
	MODELNAME       string  `json:"modelname"  xorm:"'MODELNAME'"`         // 型号名称
	WRSTANDARDID    int64   `json:"-"  xorm:"'WRSTANDARDID'"`              // 现货商品ID
	DELIVERYGOODSID int32   `json:"-"  xorm:"'DELIVERYGOODSID'"`           // 现货品种ID
	AREAUSERID      int     `json:"-"  xorm:"'AREAUSERID'"`                // 所属机构
	ISVALID         int32   `json:"-"  xorm:"'ISVALID'"`                   // 是否有效 - 0:无效 1:有效
	CREATORSRC      int32   `json:"-"  xorm:"'CREATORSRC'"`                // 创建人来源 - 1:管理端 2:终端
	CREATORID       int32   `json:"-"  xorm:"'CREATORID'"`                 // 创建人
	CREATETIME      string  `json:"-"  xorm:"'CREATETIME'"`                // SYSDATE		创建时间
	UPDATORSRC      int32   `json:"-"  xorm:"'UPDATORSRC'"`                // 更新人来源 - 1:管理端 2:终端
	UPDATORID       int32   `json:"-"  xorm:"'UPDATORID'"`                 // 更新人
	UPDATETIME      string  `json:"updatetime"  xorm:"'UPDATETIME'"`       // 更新时间
	CONVERTFACTOR   float64 `json:"convertfactor"  xorm:"'CONVERTFACTOR'"` // 标仓系数
}

// GetData 获取商品型号表数据
func (r *GoodsTypeModel) GetData() ([]GoodsTypeModel, error) {
	sData := make([]GoodsTypeModel, 0)
	if err := db.GetEngine().SQL(r.buildSql()).Find(&sData); err != nil {
		logger.GetLogger().Errorf("query goodsTypeModel fail, %v", err)
		return nil, err
	}
	return sData, nil
}

func (r *GoodsTypeModel) buildSql() string {
	sqlId := "select MODELID," +
		"       MODELNAME," +
		"       WRSTANDARDID," +
		"       DELIVERYGOODSID," +
		"       AREAUSERID," +
		"       ISVALID," +
		"       CREATORSRC," +
		"       CREATORID," +
		"       to_char(CREATETIME, 'yyyy-mm-dd hh24:mi:ss') CREATETIME," +
		"       UPDATORSRC," +
		"       UPDATORID," +
		"       CONVERTFACTOR," +
		"       to_char(UPDATETIME, 'yyyy-mm-dd hh24:mi:ss') UPDATETIME" +
		"  from spotgoodsmodel where ISVALID=1"
	if r.AREAUSERID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and AREAUSERID=%v", r.AREAUSERID)
	}
	if r.WRSTANDARDID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and WRSTANDARDID=%v", r.WRSTANDARDID)
	}
	return sqlId
}

// GoodsBrand 商品品牌
type GoodsBrand struct {
	BRANDID         int    `json:"brandid"  xorm:"'bRANDID'"`     // 品牌ID
	BRANDNAME       string `json:"brandname"  xorm:"'BRANDNAME'"` // 品牌名称
	WRSTANDARDID    int64  `json:"-"  xorm:"'WRSTANDARDID'"`      // 现货商品ID
	DELIVERYGOODSID int32  `json:"-"  xorm:"'DELIVERYGOODSID'"`   // 现货品种ID
	AREAUSERID      int    `json:"-"  xorm:"'AREAUSERID'"`        // 所属机构
	ISVALID         int32  `json:"isvalid"  xorm:"'ISVALID'"`     // 是否有效 - 0:无效 1:有效
}

func (r *GoodsBrand) buildSql() string {
	sqlId := "select BRANDID," +
		"       BRANDNAME," +
		"       WRSTANDARDID," +
		"       DELIVERYGOODSID," +
		"       AREAUSERID," +
		"       ISVALID" +
		"  from spotgoodsbrand" +
		" where ISVALID = 1"
	if r.AREAUSERID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and AREAUSERID=%v", r.AREAUSERID)
	}
	if r.WRSTANDARDID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and WRSTANDARDID=%v", r.WRSTANDARDID)
	}
	return sqlId
}

// GetData 获取品牌数据
func (r *GoodsBrand) GetData() ([]GoodsBrand, error) {
	sData := make([]GoodsBrand, 0)
	if err := db.GetEngine().SQL(r.buildSql()).Find(&sData); err != nil {
		logger.GetLogger().Errorf("query GoodsBrand fail, %v", err)
		return nil, err
	}
	return sData, nil
}

// WRSConverTDetail 现货商品折算配置明细表
type WRSConverTDetail struct {
	WRSTANDARDID      int64   `json:"wrstandardid"  xorm:"'WRSTANDARDID'"`           // 品类ID
	DELIVERYGOODSID   int32   `json:"deliverygoodsid"  xorm:"'DELIVERYGOODSID'"`     // 现货品种ID
	MIDDLEGOODSID     int64   `json:"middlegoodsid"  xorm:"'MIDDLEGOODSID'"`         // 套保品种ID
	CONVERTRATIO      float64 `json:"convertratio"  xorm:"'CONVERTRATIO'"`           // 套保系数
	MODIFYTIME        string  `json:"modifytime"  xorm:"'MODIFYTIME'"`               // 修改时间
	MIDDLEGOODSNAME   string  `json:"middlegoodsname"  xorm:"'middlegoodsname'"`     // 套保品种名称
	MIDDLEGOODSCODE   string  `json:"middlegoodscode"  xorm:"'middlegoodscode'"`     // 套保品种代码
	GOODSUNITID       int32   `json:"goodsunitid"  xorm:"'GOODSUNITID'"`             // 套保品种单位id
	DELIVERYGOODSCODE string  `json:"deliverygoodscode"  xorm:"'DELIVERYGOODSCODE'"` // 现货商品代码
	DELIVERYGOODSNAME string  `json:"deliverygoodsname"  xorm:"'DELIVERYGOODSNAME'"` // 现货商品名称
	ENUMDICNAME       string  `json:"enumdicname"`                                   // 单位名称
}

func (r *WRSConverTDetail) calc() {
	r.ENUMDICNAME = mtpcache.GetEnumDicitemName(r.GOODSUNITID)
}

func (r *WRSConverTDetail) buildSql() string {
	sqlId := "select t.WRSTANDARDID," +
		"       t.DELIVERYGOODSID," +
		"       t.MIDDLEGOODSID," +
		"       t.CONVERTRATIO," +
		"       to_char(t.MODIFYTIME, 'yyyy-mm-dd hh24:mi:ss') MODIFYTIME," +
		"       m.middlegoodsname," +
		"       m.middlegoodscode," +
		"       m.goodsunitid," +
		"       g.deliverygoodscode," +
		"       g.deliverygoodsname" +
		"  from Erms2_Wrsconvertdetail t" +
		"  left join erms_middlegoods m" +
		"    on t.middlegoodsid = m.middlegoodsid" +
		"  left join deliverygoods g" +
		"    on t.deliverygoodsid = g.deliverygoodsid" +
		" where 1 = 1"
	if r.WRSTANDARDID > 0 {
		sqlId = sqlId + fmt.Sprintf(" and t.wrstandardid=%v", r.WRSTANDARDID)
	}
	if r.DELIVERYGOODSID > 0 {
		sqlId += fmt.Sprintf(" and t.DELIVERYGOODSID=%v", r.DELIVERYGOODSID)
	}
	return sqlId
}

// GetData 获取现货商品折算配置明细表数据
func (r *WRSConverTDetail) GetData() ([]WRSConverTDetail, error) {
	sData := make([]WRSConverTDetail, 0)
	if err := db.GetEngine().SQL(r.buildSql()).Find(&sData); err != nil {
		logger.GetLogger().Errorf("query WRSConverTDetail fail, %v", err)
		return nil, err
	}
	for i := range sData {
		sData[i].calc()
	}
	return sData, nil
}

// RelatedGoodsEx 现货关联的交易商品
type RelatedGoodsEx struct {
	GoodsId   int    `json:"goodsid"  xorm:"'GoodsId'"`     // 商品id
	GoodsCode string `json:"goodscode"  xorm:"'GoodsCode'"` // 商品代码
	GoodsName string `json:"goodsname"  xorm:"'GoodsName'"` // 商品名称

	WRSTANDARDID int64 `json:"-"  xorm:"'WRSTANDARDID'"` // 现货商品ID
	AREAUSERID   int   `json:"-"  xorm:"'AREAUSERID'"`   // 所属机构
}

func (r *RelatedGoodsEx) buildSql() string {
	var sqlId utils.SQLVal = "select distinct g.goodsid, g.goodscode, g.goodsname" +
		"  from wrstandard t" +
		" inner join ERMS2_WRSConvertDetail w" +
		"    on t.wrstandardid = w.wrstandardid" +
		" inner join erms_middlegoods m" +
		"    on w.middlegoodsid = m.middlegoodsid" +
		" inner join ERMCP_GGConvertConfig gc" +
		"    on m.goodsgroupid = gc.destgoodsgroupid" +
		" inner join goods g" +
		"    on gc.srcgoodsgroupid = g.goodsgroupid" +
		" where 1=1"
	sqlId.And("t.areauserid", r.AREAUSERID)
	if r.WRSTANDARDID > 0 {
		sqlId.And("t.wrstandardid", r.WRSTANDARDID)
	}
	sqlId.Join(" order by g.goodsid")
	return sqlId.String()
}

// GetData 获取关联交易商品
func (r *RelatedGoodsEx) GetData() ([]RelatedGoodsEx, error) {
	sData := make([]RelatedGoodsEx, 0)
	if err := db.GetEngine().SQL(r.buildSql()).Find(&sData); err != nil {
		logger.GetLogger().Errorf("query RelatedGoodsEx fail, %v", err)
		return nil, err
	}
	return sData, nil
}

// ErmcpWrstandDetail 现货商品详细
type ErmcpWrstandDetail struct {
	Wrd       ErmcpWrstandard    `json:"wrd"`       // 基本信息
	GtList    []GoodsTypeModel   `json:"gtList"`    // 型号列表
	GbList    []GoodsBrand       `json:"gbList"`    // 品牌列表
	WrsList   []WRSConverTDetail `json:"wrsList"`   // 套保信息列表
	GoodsList []RelatedGoodsEx   `json:"goodsList"` // 关联交易商品列表

	QueryGoods bool `json:"-"`
}

// GetData 查询现货商品详细
func (r *ErmcpWrstandDetail) GetData() ([]ErmcpWrstandDetail, error) {
	if r.Wrd.WRSTANDARDID > 0 {
		return r.GetByWrstandId()
	}
	return r.GetAll()
}

// GetByWrstandId 指定现货商品id获取
func (r *ErmcpWrstandDetail) GetByWrstandId() ([]ErmcpWrstandDetail, error) {
	// 获取基本信息
	m := ErmcpWrstandard{AREAUSERID: r.Wrd.AREAUSERID, WRSTANDARDID: r.Wrd.WRSTANDARDID, ISVALID: -1}
	d, err := m.GetData()
	if err != nil {
		return []ErmcpWrstandDetail{}, err
	}
	if d == nil || len(d) == 0 {
		return []ErmcpWrstandDetail{}, fmt.Errorf("no record")
	}
	rsp := ErmcpWrstandDetail{}
	rsp.Wrd = d[0]
	rsp.GtList = make([]GoodsTypeModel, 0)
	rsp.GbList = make([]GoodsBrand, 0)
	rsp.WrsList = make([]WRSConverTDetail, 0)
	rsp.GoodsList = make([]RelatedGoodsEx, 0)
	// 获取型号信息
	gt := GoodsTypeModel{AREAUSERID: rsp.Wrd.AREAUSERID, WRSTANDARDID: rsp.Wrd.WRSTANDARDID}
	if val, err := gt.GetData(); err == nil {
		rsp.GtList = val
	}

	// 获取品牌信息
	gb := GoodsBrand{AREAUSERID: rsp.Wrd.AREAUSERID, WRSTANDARDID: rsp.Wrd.WRSTANDARDID}
	if val, err := gb.GetData(); err == nil {
		rsp.GbList = val
	}

	// 获取套保信息
	wrs := WRSConverTDetail{WRSTANDARDID: rsp.Wrd.WRSTANDARDID}
	if val, err := wrs.GetData(); err == nil {
		rsp.WrsList = val
	}

	// 获取关联交易商品
	if r.QueryGoods {
		goodsLst := RelatedGoodsEx{AREAUSERID: r.Wrd.AREAUSERID, WRSTANDARDID: r.Wrd.WRSTANDARDID}
		if val, err := goodsLst.GetData(); err == nil {
			rsp.GoodsList = val
		}
	}

	rsp2 := make([]ErmcpWrstandDetail, 0)
	rsp2 = append(rsp2, rsp)

	return rsp2, nil
}

// GetAll 获取所有
func (r *ErmcpWrstandDetail) GetAll() ([]ErmcpWrstandDetail, error) {
	// 获取基本信息
	m := ErmcpWrstandard{AREAUSERID: r.Wrd.AREAUSERID, ISVALID: -1}
	d, err := m.GetData()
	if err != nil {
		return []ErmcpWrstandDetail{}, err
	}
	if d == nil || len(d) == 0 {
		return []ErmcpWrstandDetail{}, fmt.Errorf("no record")
	}

	// 获取型号信息
	gt := GoodsTypeModel{AREAUSERID: r.Wrd.AREAUSERID}
	gtList, _ := gt.GetData()

	// 获取品牌信息
	gb := GoodsBrand{AREAUSERID: r.Wrd.AREAUSERID}
	gbList, _ := gb.GetData()

	// 获取套保信息
	wrs := WRSConverTDetail{}
	wrsList, _ := wrs.GetData()

	var glist []RelatedGoodsEx
	// 获取关联交易商品
	if r.QueryGoods {
		goodsLst := RelatedGoodsEx{AREAUSERID: r.Wrd.AREAUSERID}
		if val, err := goodsLst.GetData(); err == nil {
			glist = val
		}
	}

	rsp := make([]ErmcpWrstandDetail, 0)
	for i := range d {
		val := ErmcpWrstandDetail{
			Wrd:       d[i],
			GtList:    make([]GoodsTypeModel, 0),
			GbList:    make([]GoodsBrand, 0),
			WrsList:   make([]WRSConverTDetail, 0),
			GoodsList: make([]RelatedGoodsEx, 0),
		}

		for k := range gtList {
			if gtList[k].WRSTANDARDID == d[i].WRSTANDARDID {
				val.GtList = append(val.GtList, gtList[k])
			}
		}

		for k := range gbList {
			if gbList[k].WRSTANDARDID == d[i].WRSTANDARDID {
				val.GbList = append(val.GbList, gbList[k])
			}
		}

		for k := range wrsList {
			if wrsList[k].WRSTANDARDID == d[i].WRSTANDARDID {
				val.WrsList = append(val.WrsList, wrsList[k])
			}
		}

		for k := range glist {
			if glist[k].WRSTANDARDID == d[i].WRSTANDARDID {
				val.GoodsList = append(val.GoodsList, glist[k])
			}
		}
		rsp = append(rsp, val)
	}

	return rsp, nil
}
