/**
* @Author: zou.yingbin
* @Create  : 2021/1/12 10:38
* @Modify  : 2021/1/12 10:38
 */

package models

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

// ErmcpOPApplyModel 现货合同操作数据
type ErmcpOPApplyModel struct {
	USERID            int64   `json:"userid"  xorm:"'USERID'"`                       // 用户ID
	OPERATEAPPLYID    string  `json:"operateapplyid"  xorm:"'OPERATEAPPLYID'"`       // 操作申请ID(603+Unix秒时间戳(10位)+xxxxxx)
	OPERATEAPPLYTYPE  int32   `json:"operateapplytype"  xorm:"'OPERATEAPPLYTYPE'"`   // 操作申请类型 - 1:点价 2:结算登记 3:款项登记 4:发票登记
	RELATEDID         string  `json:"relatedid"  xorm:"'RELATEDID'"`                 // 现货合同ID
	DETAILJSON        string  `json:"-"  xorm:"'DETAILJSON'"`                        // 明细JSON
	APPLYID           string  `json:"applyid"  xorm:"'APPLYID'"`                     // 申请人
	APPLYTIME         string  `json:"applytime"  xorm:"'APPLYTIME'"`                 // 申请时间
	APPLYSTATUS       int32   `json:"applystatus"  xorm:"'APPLYSTATUS'"`             // 申请状态 - 1:待审核 2:审核通过 3:审核拒绝 4:处理失败 5:已撤回
	AUDITTIME         string  `json:"audittime"  xorm:"'AUDITTIME'"`                 // 审核时间
	CONTRACTTYPE      int32   `json:"contracttype"  xorm:"'CONTRACTTYPE'"`           // 现货合同类型 - 1:采购 -1:销售
	CONTRACTNO        string  `json:"contractno"  xorm:"'CONTRACTNO'"`               // 合同编号
	PRICETYPE         int32   `json:"pricetype"  xorm:"'PRICETYPE'"`                 // 定价类型 - 1:一口价 2:点价 3:暂定价
	PRICEMOVE         float64 `json:"pricemove"  xorm:"'PRICEMOVE'"`                 // 升贴水
	GOODSNAME         string  `json:"goodsname"  xorm:"'GOODSNAME'"`                 // 商品名称
	GOODSCODE         string  `json:"goodscode"  xorm:"'GOODSCODE'"`                 // 点价合约
	EnumdicName       string  `json:"enumdicname"  xorm:"'ENUMDICNAME'"`             // 单位名称
	BUYUSERNAME       string  `json:"buyusername"  xorm:"'BUYUSERNAME'"`             // 采购方名称
	SELLUSERNAME      string  `json:"sellusername"  xorm:"'SELLUSERNAME'"`           // 销售方名字
	AUDITID           string  `json:"auditid"  xorm:"'AUDITID'"`                     // 审核人ID
	APPLYNAME         string  `json:"applyname"  xorm:"'APPLYNAME'"`                 // 申请人名称
	AUDITNAME         string  `json:"auditname"  xorm:"'AUDITNAME'"`                 // 审核人名称
	CONTRACTSTATUS    int32   `json:"contractstatus"  xorm:"'CONTRACTSTATUS'"`       // 合同状态- 0:未提交 1:待审核 2:执行中 3:正常完结 4:审核拒绝 5:异常完结 6:已撤回
	ATTACHURL         string  `json:"attachurl"  xorm:"'ATTACHURL'"`                 // 附件
	WRSTANDARDNAME    string  `json:"wrstandardname"  xorm:"'WRSTANDARDNAME'"`       // 品类名称
	WRSTANDARDCODE    string  `json:"wrstandardcode"  xorm:"'WRSTANDARDCODE'"`       // 品类代码
	WRSTANDARDID      int     `json:"wrstandardid"  xorm:"'WRSTANDARDID'"`           // 品类id
	DELIVERYGOODSID   int     `json:"deliverygoodsid"  xorm:"'DELIVERYGOODSID'"`     // 现货商品ID
	DELIVERYGOODSCODE string  `json:"deliverygoodscode"  xorm:"'DELIVERYGOODSCODE'"` // 现货品种代码
	DELIVERYGOODSNAME string  `json:"deliverygoodsname"  xorm:"'DELIVERYGOODSNAME'"` // 现货品种名称

	FilterAppStatus string `json:"-"` // 状态过滤条件
	UserType        int32  `json:"-"`
}

func (r *ErmcpOPApplyModel) calc() {
	// 管理端applyid存的是管理员表的autoid
	if len(r.APPLYID) < 8 && r.APPLYNAME == "" {
		if id, err := strconv.ParseInt(r.APPLYID, 10, 64); err == nil {
			r.APPLYNAME = mtpcache.GetSystemmangerLoginCode(id)
		}
	}

	if len(r.AUDITID) < 8 && r.AUDITNAME == "" {
		if id, err := strconv.ParseInt(r.AUDITID, 10, 64); err == nil {
			r.AUDITNAME = mtpcache.GetSystemmangerLoginCode(id)
		}
	}
}

func (r *ErmcpOPApplyModel) buildSql(opType int32) string {
	sqlId := "select to_char(t.OPERATEAPPLYID) OPERATEAPPLYID," +
		"       t.OPERATEAPPLYTYPE," +
		"       to_char(t.RELATEDID) RELATEDID," +
		"       t.DETAILJSON," +
		"       to_char(t.APPLYID) APPLYID," +
		"       to_char(t.APPLYTIME, 'yyyy-mm-dd hh24:mi:ss') APPLYTIME," +
		"       t.APPLYSTATUS," +
		"       to_char(t.auditid) auditid," +
		"       to_char(t.AUDITTIME, 'yyyy-mm-dd hh24:mi:ss') AUDITTIME," +
		"       t.CONTRACTTYPE," +
		"       to_char(t.attachurl) attachurl," +
		"       s.CONTRACTNO," +
		"       s.PRICETYPE," +
		"       s.pricemove," +
		"       s.userid," +
		"       s.contractstatus," +
		"       dg.deliverygoodsid," +
		"       dg.deliverygoodscode," +
		"       dg.deliverygoodsname," +
		"       w.wrstandardname," +
		"       w.wrstandardcode," +
		"       w.wrstandardid," +
		"       g.GOODSNAME," +
		"       g.GOODSCODE," +
		"       e.EnumdicName," +
		"       u3.logincode APPLYName," +
		"       u4.logincode auditName," +
		"       u1.accountname buyuserName," +
		"       u2.accountname selluserName" +
		"  from ermcp_contractoperateapply t" +
		"  left join ermcp_spotcontract s" +
		"    on t.relatedid = s.spotcontractid" +
		"  left join goods g" +
		"    on s.goodsid = g.goodsid" +
		"  left join wrstandard w" +
		"    on s.wrstandardid = w.wrstandardid" +
		"  left join loginaccount u3" +
		"    on t.applyid = u3.loginid" +
		"  left join loginaccount u4" +
		"    on t.auditid = u4.loginid" +
		"  left join useraccount u1" +
		"    on s.buyuserid = u1.userid" +
		"  left join useraccount u2" +
		"    on s.selluserid = u2.userid" +
		"  left join deliverygoods dg" +
		"    on t.deliverygoodsid = dg.deliverygoodsid" +
		"  left join enumdicitem e" +
		"    on e.enumitemname = w.unitid" +
		"   and e.enumdiccode = 'goodsunit'" +
		" where t.operateapplytype = %v"

	if len(r.RELATEDID) > 0 {
		sqlId = sqlId + " and t.relatedid=" + r.RELATEDID
	}

	if len(r.OPERATEAPPLYID) > 0 {
		sqlId += " and t.operateapplyid =" + r.OPERATEAPPLYID
	}

	if len(r.FilterAppStatus) > 0 {
		sqlId += fmt.Sprintf(" and t.applystatus in(%v)", r.FilterAppStatus)
	}
	// 终端没传用户类型过来
	if r.UserType == 0 {
		areaUserId := mtpcache.GetAreaUserId(r.USERID, r.UserType)
		if areaUserId == r.USERID {
			// 所属机构=自己, 则为机构用户类型
			r.UserType = 2
		} else {
			r.UserType = 7
		}
	}
	if r.UserType == 7 {
		sqlId += fmt.Sprintf(" and %v in(s.saleuserid, s.tradeuserid, s.meruserid)", r.USERID)
	} else {
		sqlId += fmt.Sprintf(" and s.userid = %v", r.USERID)
	}

	return fmt.Sprintf(sqlId, opType)
}

// GetData 从数据库中查询合同操作申请相关信息, opType 操作申请类型 - 1:点价 2:结算登记 3:款项登记 4:发票登记
func (r *ErmcpOPApplyModel) GetData(opType int32) ([]ErmcpOPApplyModel, error) {
	sData := make([]ErmcpOPApplyModel, 0)
	e := db.GetEngine()
	s := e.SQL(r.buildSql(opType))
	if err := s.Find(&sData); err != nil {
		logger.GetLogger().Errorf("ermcp query fail:%v", err)
		return sData, err
	}
	for i := range sData {
		sData[i].calc()
	}
	return sData, nil
}
