package Nmysql

import (
	"fmt"
	l4g "proxy/logger"
)

func QuerySyncMobileInfo() ([]SyncMobileInfo, error) {
	sqlStr := fmt.Sprintf("select PRE_ID, OPER_TYPE, IMSI, SERVICE_NBR, KI, IFNULL(OPC,'') as OPC, CUST_ID, ACCT_ID, PRD_INST_ID, MOBILE_TYPE, VMS_FLAG, IFNULL(BIRTH_DATE,'') as BIRTH_DATE, BALANCE, BALANCE_EXP_DATE, OFR_ID, EXP_DATE, IFNULL(CUG_ID,0) as CUG_ID from tb_sync_mobile where STATE=1 limit 10;")
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query tb_sync_mobile fail: %v", err)
		return nil, err
	}
	defer rows.Close()

	var rsp []SyncMobileInfo= nil
	for rows.Next(){
		var si SyncMobileInfo
		if err = rows.Scan(&si.PreId, &si.OperType, &si.Imsi, &si.ServiceNbr, &si.Ki, &si.Opc, &si.CustId, &si.AcctId, &si.PrdInstId,
			&si.MobileType, &si.VmsFlag, &si.BirthDate, &si.Balance, &si.BalanceExpDate, &si.OfrId, &si.ExpDate, &si.CugId); err != nil {
			l4g.MysqlLog.Errorf("query row of tb_sync_mobile fail: %v", err)
			return nil, err
		}
		if si.BirthDate == "" {
			si.BirthDate = "2000-01-01"
		}

		rsp = append(rsp, si)
	}

	return rsp, nil
}

type SyncMobileInfo struct {
	PreId int// auto incr
	OperType int// 1: create subs, 2: replace IMSI
	Imsi string
	ServiceNbr string
	Ki string
	Opc string
	CustId int
	AcctId int
	PrdInstId int
	MobileType int//0: postpaid, 1: prepaid
	VmsFlag int//0: not VMS service, 1: VMS service
	BirthDate string
	Balance int
	BalanceExpDate string
	OfrId int
	ExpDate string
	CugId int// 1: staff, 2: customer
}

func QueryOldImsiInfo(serviceNbr string) (*OldImsiInfo, error) {
	sqlStr := fmt.Sprintf("select PRE_ID, IMSI, PRD_INST_ID from tb_sync_mobile WHERE SERVICE_NBR='%s' and STATE>1 ORDER BY PRE_ID DESC limit 1;", serviceNbr)
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query tb_sync_mobile fail: %v", err)
		return nil, err
	}
	defer rows.Close()

	var rsp OldImsiInfo
	for rows.Next(){
		if err = rows.Scan(&rsp.PreId, &rsp.Imsi, &rsp.PrdInstId); err != nil {
			l4g.MysqlLog.Errorf("query row of tb_sync_mobile fail: %v", err)
			return nil, err
		}

		return &rsp, nil
	}

	return nil, nil
}

type OldImsiInfo struct {
	PreId int
	Imsi string
	PrdInstId int
}

func AddSmcliCmd2Mysql(cmdType int, nt int, serviceNbr string, cmdStr string) error {
	sqlStr := fmt.Sprintf("INSERT INTO tb_sync_cn_cmd SET cmd_type=%d, node_type=%d, node_name='%s', srv_num='%s', command='%s', state=1, result=0, timestamp=NOW();", 
		cmdType, nt, NodeName[nt], serviceNbr, cmdStr)
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec()
	if err != nil {
		l4g.MysqlLog.Errorf("AddSmcliCmd2Mysql, cmdType[%d], nt[%d], prdInstId[%s], cmd[%s] error: %v", cmdType, nt, serviceNbr, cmdStr, err)
		return err
	}

	l4g.MysqlLog.Debugf("AddSmcliCmd2Mysql, cmdType[%d], nt[%d], prdInstId[%s], cmd[%s] succ!", cmdType, nt, serviceNbr, cmdStr)
	return nil
}

func AddSmcliCmdSucc2Mysql(cmdType int, nt int, serviceNbr string, cmdStr string) error {
	cause := "000:Command Successful"
	sqlStr := fmt.Sprintf("INSERT INTO tb_sync_cn_cmd SET cmd_type=%d, node_type=%d, node_name='%s', srv_num='%s', command='%s', state=2, result=1, cause='%s', timestamp=NOW();", 
		cmdType, nt, NodeName[nt], serviceNbr, cmdStr, cause)
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec()
	if err != nil {
		l4g.MysqlLog.Errorf("AddSmcliCmd2Mysql, cmdType[%d], nt[%d], prdInstId[%s], cmd[%s] error: %v", cmdType, nt, serviceNbr, cmdStr, err)
		return err
	}

	l4g.MysqlLog.Debugf("AddSmcliCmd2Mysql, cmdType[%d], nt[%d], prdInstId[%s], cmd[%s] succ!", cmdType, nt, serviceNbr, cmdStr)
	return nil
}

func UpdateSyncMobileState(preId int, state int) error {
	sqlStr := fmt.Sprintf("UPDATE tb_sync_mobile set STATE=%d where PRE_ID=%d;", state, preId)
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec()
	if err != nil {
		l4g.MysqlLog.Errorf("UpdateSyncMobileState, preId[%d], state[%d] error: %v", preId, state, err)
		return err
	}

	l4g.MysqlLog.Debugf("UpdateSyncMobileState, preId[%d], state[%d] succ!", preId, state)
	return nil
}

func QuerySyncCnCmd() ([]CnCmdInfo, error) {
	sqlStr := fmt.Sprintf("select id, node_type, command from tb_sync_cn_cmd where state=1 limit 40;")
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query tb_sync_cn_cmd fail: %v", err)
		return nil, err
	}
	defer rows.Close()

	var rsp []CnCmdInfo= nil
	for rows.Next(){
		var si CnCmdInfo
		if err = rows.Scan(&si.Id, &si.NodeType, &si.Command); err != nil {
			l4g.MysqlLog.Errorf("query row of tb_sync_cn_cmd fail: %v", err)
			return nil, err
		}

		rsp = append(rsp, si)
	}

	return rsp, nil
}

type CnCmdInfo struct {
	Id int// auto incr
	NodeType int
	Command string
}

func UpdateCnCmdResult(id int, state int, result int, desc string) error {
	sqlStr := fmt.Sprintf("update tb_sync_cn_cmd set state=%d,result=%d,cause='%s',timestamp=NOW() where id=%d;", 
		state, result, desc, id)
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec()
	if err != nil {
		l4g.MysqlLog.Errorf("UpdateCnCmdResult, id[%d], state[%d], result[%d], cause[%s] error: %v", id, state, result, desc, err)
		return err
	}

	l4g.MysqlLog.Debugf("UpdateCnCmdResult, id[%d], state[%d], result[%d], cause[%s] succ!", id, state, result, desc)
	return nil
}

