/**
* @Author: zou.yingbin
* @Create  : 2021/1/14 11:44
* @Modify  : 2021/1/14 11:44
 */

package models

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

// ErmcpOPLogModel 变更变记录
type ErmcpOPLogModel struct {
	BIZTYPE            int32   `json:"biztype"  xorm:"'BIZTYPE'"`               // 业务类型 - 1:套保计划 2:现货合同
	OPERATELOGTYPE     int32   `json:"operatelogtype"  xorm:"'OPERATELOGTYPE'"` // 操作流水类型
	RELATEDID          string  `json:"relatedid"  xorm:"'RELATEDID'"`           // 现货合同ID\套保计划
	LOGVALUE           float64 `json:"logvalue"  xorm:"'LOGVALUE'"`             // 数值
	BEFOREVALUE        float64 `json:"beforevalue"  xorm:"'BEFOREVALUE'"`       // 变更前
	AFTERVALUE         float64 `json:"aftervalue"  xorm:"'AFTERVALUE'"`         // 变更后
	UPDATETIME         string  `json:"updatetime"  xorm:"'UPDATETIME'"`         // 更新时间
	APPLYID            string  `json:"applyid"  xorm:"'APPLYID'"`               // 操作人ID
	CONTRACTTYPE       int32   `json:"contracttype"  xorm:"'CONTRACTTYPE'"`     // 现货合同类型 - 1:采购 -1:销售
	OPERATELOGTYPEDESC string  `json:"operatelogtypedesc"`                      // 操作流水类型名称
	APPLYNAME          string  `json:"applyname" xorm:"'APPLYNAME'"`            // 操作人名称
}

func (r *ErmcpOPLogModel) calc() {
	if r.APPLYNAME == "" {
		id, _ := strconv.ParseInt(r.APPLYID, 10, 64)
		r.APPLYNAME = mtpcache.GetSystemmangerLoginCode(id)
	}
}

func (r *ErmcpOPLogModel) decodeOperateLogType() {
	//1:点价价格 2:点价数量 3:结算量 4:其它费用 5:追加保证金 6溢短金额 7:调整金额 8:付款金额 9:收款金额 10:退款金额
	//11:收票金额 12:开票金额 13:提交审核(合同) 14:审核通过(合同) 15:审核拒绝(合同) 16:合同撤回 17:提交审核(计划)
	//18:审核通过(计划) 19:审核拒绝(计划) 20:计划撤回 21:正常完结(合同) 22:异常终止(合同) 23:退还保证金
	sDes := []string{"点价价格", "点价数量", "结算量", "其它费用", "追加保证金", "溢短金额", "调整金额", "付款金额", "收款金额", "退款金额",
		"收票金额", "开票金额", "提交审核(合同)", "审核通过(合同)", "审核拒绝(合同)", "合同撤回", "提交审核(计划)",
		"审核通过(计划)", "审核拒绝(计划)", "计划撤回", "正常完结(合同)", "异常终止(合同)", "退还保证金"}
	if r.OPERATELOGTYPE >= 1 && r.OPERATELOGTYPE <= 23 {
		r.OPERATELOGTYPEDESC = sDes[r.OPERATELOGTYPE-1]
	}
}

func (r *ErmcpOPLogModel) buildSql() string {
	str := "select BIZTYPE," +
		"       OPERATELOGTYPE," +
		"       RELATEDID," +
		"       LOGVALUE," +
		"       BEFOREVALUE," +
		"       AFTERVALUE," +
		"       to_char(UPDATETIME, 'yyyy-mm-dd hh24:mi:ss') UPDATETIME," +
		"       APPLYID," +
		"       CONTRACTTYPE," +
		"       l.logincode APPLYNAME" +
		"  from ermcp_contractoperatelog t" +
		"  left join loginaccount l" +
		"    on t.applyid = l.loginid" +
		" where t.relatedid = %v and t.operatelogtype in(13, 14, 15, 16, 21, 22)" +
		" order by t.UPDATETIME desc"
	return fmt.Sprintf(str, r.RELATEDID)
}

// GetData 从数据库中获取操作变更数据
func (r *ErmcpOPLogModel) GetData() ([]ErmcpOPLogModel, error) {
	e := db.GetEngine()
	sData := make([]ErmcpOPLogModel, 0)
	if err := e.SQL(r.buildSql()).Find(&sData); err != nil {
		return nil, err
	}
	// 类型解析成中文
	for i := range sData {
		sData[i].decodeOperateLogType()
		sData[i].calc()
	}
	return sData, nil
}
