package Nmysql

import "C"
import (
	"fmt"
	. "proxy/config"
	l4g "proxy/logger"
	"strconv"
)

func UpdateUserStatus2Mdb(accountId uint32, status byte) error {
	statusInCrm := 1001
	switch status {
	case 1:
		statusInCrm = 1001
	case 2:
		statusInCrm = 1205
	case 4:
		statusInCrm = 1101
	case 6:
		statusInCrm = 1202
	}

	if false {
		stmt, _ := MySqlDb.Prepare("update tb_prd_prd_inst_551 set PRD_INST_STAS_ID=?, MOD_DATE=NOW() where ACCT_ID=?;")
		defer stmt.Close()

		_, _ = stmt.Exec(statusInCrm, accountId)
	}

	if status == 4 {
		stmt, _ := MySqlDb.Prepare("INSERT INTO tb_mobile_disc_cmd set ACCT_ID=?, ACCT_STATUS=0, UPDATE_DATE=NOW();")
		defer stmt.Close()

		_, err := stmt.Exec(accountId)
		if err != nil {
			l4g.MysqlLog.Errorf("UpdateUserStatus2Mdb acctId[%d] err: %v", accountId, err)
			//return err
		}

		l4g.MysqlLog.Debugf("UpdateUserStatus2Mdb acctId[%d] succ!", accountId)

		_ = InsertPrepaidUserDeleteCliCmd(accountId)
	}
	return nil
}

func InsertPrepaidUserDeleteCliCmd(accountId uint32) error {
	//sqlStr := "select  PRE_ID, OPER_TYPE, IMSI, SERVICE_NBR, KI, OPC, CUST_ID, STATE, PRD_INST_ID, MOBILE_TYPE, VMS_FLAG, BIRTH_DATE, BALANCE, "
	//sqlStr += "BALANCE_EXP_DATE, OFR_ID, EXP_DATE, CUG_ID from tb_sync_mobile where ACCT_ID=? ORDER BY PRE_ID DESC limit 1;"
	sqlStr := "select  IMSI, SERVICE_NBR, PRD_INST_ID "
	sqlStr += "from tb_sync_mobile where ACCT_ID=" + strconv.Itoa(int(accountId)) + " ORDER BY PRE_ID DESC limit 1;"
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query tb_sync_mobile, accountId[%d] fail: %v", accountId, err)
		return err
	}
	//defer rows.Close()

	var imsi, msisdn string
	var prdInstId int
	for rows.Next(){
		if err = rows.Scan(&imsi, &msisdn, &prdInstId); err != nil {
			l4g.MysqlLog.Errorf("query row of tb_sync_mobile fail: %v", err)
			_ = rows.Close()
			return err
		}

		break
	}
	_ = rows.Close()

	if imsi != "" {
		cmd := "delete subscriber -imsi " + imsi
		stmt, _ := MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
		//defer stmt.Close()
		_, err := stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_HSS, NodeName[NT_HSS], prdInstId, cmd)
		if err != nil {
			l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
			//return err
		} else {
			l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
		}
		stmt.Close()

		cmd = "delete aucSubscriber -imsi " + imsi
		stmt, _ = MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
		//defer stmt.Close()
		_, err = stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_AUC, NodeName[NT_AUC], prdInstId, cmd)
		if err != nil {
			l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
			//return err
		} else {
			l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
		}
		stmt.Close()

		cmd = "delete vmsSubscriber -msisdn " + msisdn
		stmt, _ = MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
		//defer stmt.Close()
		_, err = stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_VMS, NodeName[NT_VMS], prdInstId, cmd)
		if err != nil {
			l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
			//return err
		} else {
			l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
		}
		stmt.Close()
	}
	return nil
}

func CrmDeleteSubsProfile(serviceNbr string, acctType string, acctId string) {
	if acctType == "1" {
		//sqlStr := "select  PRE_ID, OPER_TYPE, IMSI, SERVICE_NBR, KI, OPC, CUST_ID, STATE, PRD_INST_ID, MOBILE_TYPE, VMS_FLAG, BIRTH_DATE, BALANCE, "
		//sqlStr += "BALANCE_EXP_DATE, OFR_ID, EXP_DATE, CUG_ID from tb_sync_mobile where ACCT_ID=? ORDER BY PRE_ID DESC limit 1;"
		sqlStr := "select  IMSI, SERVICE_NBR, PRD_INST_ID, MOBILE_TYPE, VMS_FLAG "
		sqlStr += "from tb_sync_mobile where ACCT_ID=" + acctId + " ORDER BY PRE_ID DESC limit 1;"
		rows, err := MySqlDb.Query(sqlStr)
		if err != nil {
			l4g.MysqlLog.Errorf("Query tb_sync_mobile, accountId[%d] fail: %v", acctId, err)
			return
		}
		//defer rows.Close()

		var imsi, msisdn string
		var prdInstId, mobileType, vmsFlag int
		for rows.Next(){
			if err = rows.Scan(&imsi, &msisdn, &prdInstId, &mobileType, &vmsFlag); err != nil {
				l4g.MysqlLog.Errorf("query row of tb_sync_mobile fail: %v", err)
				_ = rows.Close()
				return
			}

			break
		}
		_ = rows.Close()

		if imsi != "" {
			cmd := "delete subscriber -imsi " + imsi
			stmt, _ := MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
			//defer stmt.Close()
			_, err := stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_HSS, NodeName[NT_HSS], strconv.Itoa(prdInstId), cmd)
			if err != nil {
				l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
				//return err
			} else {
				l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
			}
			stmt.Close()

			cmd = "delete aucSubscriber -imsi " + imsi
			stmt, _ = MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
			//defer stmt.Close()
			_, err = stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_AUC, NodeName[NT_AUC], strconv.Itoa(prdInstId), cmd)
			if err != nil {
				l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
				//return err
			} else {
				l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
			}
			stmt.Close()

			if mobileType == 1{
				cmd = "delete ppsSubscriber -msisdn " + msisdn
				stmt, _ = MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=2, result=1, cause='0000:Command successful', timestamp=NOW();")
				//defer stmt.Close()
				_, err = stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_OCS, NodeName[NT_OCS], strconv.Itoa(prdInstId), cmd)
				if err != nil {
					l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
					//return err
				} else {
					l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
				}
				stmt.Close()
			}

			if vmsFlag == 1{
				cmd = "delete vmsSubscriber -msisdn " + msisdn
				stmt, _ = MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=0, timestamp=NOW();")
				//defer stmt.Close()
				_, err = stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_VMS, NodeName[NT_VMS], strconv.Itoa(prdInstId), cmd)
				if err != nil {
					l4g.MysqlLog.Errorf("add cmd[%s], msisdn[%s], prdInstId[%d] err: %v", cmd, msisdn, prdInstId, err)
					//return err
				} else {
					l4g.MysqlLog.Debugf("add cmd[%s], msisdn[%s], prdInstId[%d]", cmd, msisdn, prdInstId)
				}
				stmt.Close()
			}
		}
	} else if acctType == "2" {
		ssEntryIdInCrm := Config.Provision.SsEntryIdInCrm
		orderId := queryOrderIdByServiceNbr(serviceNbr)
		if orderId == 0 {
			return
		}

		examNumStr := queryResourceExamNumByOrderId(orderId)
		if examNumStr == "" {
			return
		}
		kronePairId, _ := strconv.Atoi(examNumStr)
		if kronePairId <= 0 {
			return
		}

		examNumStr = querySsEntryByResIdAndOrderId(ssEntryIdInCrm, orderId)
		if examNumStr == "" {
			return
		}
		ssEntry, _ := strconv.Atoi(examNumStr)

		cmdDelPstn := fmt.Sprintf("delete pstn user isdn=%s, krone_pair_id=%d, ssentry=%d, state=Deleted, account_id=%s;",
			serviceNbr,kronePairId, ssEntry,acctId)
		insertCmdDelPstn(cmdDelPstn, serviceNbr)
	}
	return
}

func insertCmdDelPstn(cmd string, serviceNbr string) {
	stmt, _ := MySqlDb.Prepare("INSERT INTO tb_sync_cn_cmd SET cmd_type=?, node_type=?, node_name=?, srv_num=?, command=?, state=1, result=1, timestamp=NOW();")
	//defer stmt.Close()
	_, err := stmt.Exec(CT_DISCONNECT_ACCOUNT, NT_PSTN, NodeName[NT_PSTN], serviceNbr, cmd)
	if err != nil {
		l4g.MysqlLog.Errorf("insertCmdDelPstn cmd[%s], msisdn[%s] err: %v", cmd, serviceNbr, err)
		//return err
	} else {
		l4g.MysqlLog.Debugf("insertCmdDelPstn cmd[%s], msisdn[%s]", cmd, serviceNbr)
	}
	stmt.Close()
}

func queryOrderIdByServiceNbr(serviceNbr string) int {
	sqlStr := "select ORDER_ID from tb_sync_pstn where SERVICE_NBR=" + serviceNbr + " ORDER by ORDER_ID desc limit 1;"
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query tb_sync_pstn, serviceNbr[%s] fail: %v", serviceNbr, err)
		return 0
	}
	defer rows.Close()

	var orderId int
	for rows.Next(){
		if err = rows.Scan(&orderId); err != nil {
			l4g.MysqlLog.Errorf("query row of tb_sync_pstn fail: %v", err)
			//_ = rows.Close()
			return 0
		}

		return orderId
	}
	//_ = rows.Close()
	return 0
}

func queryResourceExamNumByOrderId(orderId int) string {
	sqlStr := "SELECT C.RESOURCE_EXAM_NUM FROM TB_PRD_RES_INST_551 A, TB_PRD_RES_INST_DETAIL_551 B, TB_RESOURCE_EXAM C "
	sqlStr += "WHERE A.RES_INST_ID=B.RES_INST_ID AND B.RESOURCE_EXAM_ID=C.RESOURCE_EXAM_ID AND C.RESOURCE_ID=1046 AND A.ORDER_ID=" + strconv.Itoa(orderId)+";"
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query TB_RESOURCE_EXAM, orderId[%d] fail: %v", orderId, err)
		return ""
	}
	defer rows.Close()

	var resExamNum string
	for rows.Next(){
		if err = rows.Scan(&resExamNum); err != nil {
			l4g.MysqlLog.Errorf("query row of TB_RESOURCE_EXAM fail: %v", err)
			//_ = rows.Close()
			return ""
		}

		return resExamNum
	}
	//_ = rows.Close()
	return ""
}

func querySsEntryByResIdAndOrderId(resId, orderId int) string {
	sqlStr := fmt.Sprintf("%s%sC.RESOURCE_ID=%d AND A.ORDER_ID=%d;",
		"SELECT C.RESOURCE_EXAM_NUM FROM TB_PRD_RES_INST_551 A, TB_PRD_RES_INST_DETAIL_551 B, TB_RESOURCE_EXAM C ",
		"WHERE A.RES_INST_ID=B.RES_INST_ID AND B.RESOURCE_EXAM_ID=C.RESOURCE_EXAM_ID AND ", resId, orderId)
	rows, err := MySqlDb.Query(sqlStr)
	if err != nil {
		l4g.MysqlLog.Errorf("Query TB_RESOURCE_EXAM, orderId[%d] fail: %v", orderId, err)
		return ""
	}
	defer rows.Close()

	var resExamNum string
	for rows.Next(){
		if err = rows.Scan(&resExamNum); err != nil {
			l4g.MysqlLog.Errorf("query row of TB_RESOURCE_EXAM fail: %v", err)
			return ""
		}

		return resExamNum
	}

	return ""
}
