package lakala

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/lakala"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"time"
)

// ApplyContract 电子合同申请回调
func ApplyContract(callback *lakala.ApplyContractCallBack) error {
	var (
		db = dao.GetDB()
	)

	merchantInfo, err := dao.GetStoreContract(db, 0, callback.OrderNo, utils.Int64ToStr(callback.EcApplyId))
	if err != nil {
		return err
	}

	merchantInfo.ContractStatus = callback.AuditStatus
	merchantInfo.Desc = callback.AuditDesc
	_, err = dao.UpdateEntity(db, merchantInfo, "ContractStatus")
	if err != nil {
		return err
	}

	return nil
}

// ApplyContractByPeople 电子合同申请人工审核回调
func ApplyContractByPeople(callback *lakala.ApplyContractByPeopleCallBack) error {
	var (
		db = dao.GetDB()
	)
	if callback.Code == "000000" {
		merchantInfo, err := dao.GetStoreContract(db, 0, callback.RespData.OrderNo, "")
		if err != nil {
			return err
		}

		merchantInfo.ContractStatus = callback.RespData.AuditStatus
		merchantInfo.Desc = callback.RespData.AuditDesc
		_, err = dao.UpdateEntity(db, merchantInfo, "ContractStatus")
		if err != nil {
			return err
		}
	}

	return nil
}

// CreateSeparateShop 商户分账业务回调(创建/修改)
func CreateSeparateShop(callback *lakala.SeparateCallback) error {
	var (
		db = dao.GetDB()
	)
	merchantInfo, err := dao.GetStoreInfoByMerchantID(db, callback.MerCupNo, 0, utils.Int64ToStr(callback.ApplyId), "")
	if err != nil {
		return err
	}

	if callback.AuditStatus == utils.Int2Str(model.YES) {
		merchantInfo.OperateStatus = model.OperateStatusSuccess
	} else {
		merchantInfo.OperateStatus = model.OperateStatusFail
	}

	_, err = dao.UpdateEntity(db, merchantInfo, "OperateStatus")
	if err != nil {
		return err
	}

	return nil
}

// BindSeparateBand 绑定/解绑业务
func BindSeparateBand(callback *lakala.SeparateBindCallback) error {
	var (
		db = dao.GetDB()
	)
	bindInfo, err := dao.GetStoreInfoByMerchantID(db, callback.MerCupNo, 0, callback.ApplyId, "")
	if err != nil {
		return err
	}

	unBind := make(map[string]*model.BindAccountObj, 0)
	if err = json.Unmarshal([]byte(bindInfo.BindAccount), &unBind); err != nil {
		return err
	}
	if unBind[callback.ReceiverNo].ApplyId == callback.ApplyId {
		unBind[callback.ReceiverNo] = &model.BindAccountObj{
			ApplyId: callback.ApplyId,
			Status:  callback.AuditStatus,
			Remark:  fmt.Sprintf(callback.AuditStatusText + ":" + callback.Remark),
		}
	}

	byteBind, err := json.Marshal(unBind)
	if err != nil {
		return err
	}
	bindInfo.BindAccount = string(byteBind)

	if _, err = dao.UpdateEntity(db, bindInfo, "BindAccount"); err != nil {
		return err
	}
	return nil
}

// GetSeparateRecordsCallback 分账结果回调
func GetSeparateRecordsCallback(callback *lakala.SeparateResult) error {
	var (
		db = dao.GetDB()
	)
	separateRecord, err := dao.GetSeparateRecords(db, "", callback.SeparateNo, callback.CmdType)
	if err != nil {
		return err
	}
	separateRecord.CmdType = callback.CmdType
	separateRecord.FinishDate = callback.FinishDate
	separateRecord.Status = callback.Status
	separateRecord.FinalStatus = callback.FinalStatus
	separateRecord.UpdatedAt = time.Now()
	_, err = dao.UpdateEntity(db, separateRecord, "CmdType", "FinishDate", "Status", "FinalStatus", "UpdatedAt")
	return err
}

// EwalletWithdrawD1Callback 结算信息回调
func EwalletWithdrawD1Callback(param *lakala.EwalletWithdrawD1CallBack) error {
	var (
		db = dao.GetDB()
	)
	withDraw, err := dao.GetEwalletWithDraw(db, param.MercId, param.DrawJnl)
	if err != nil {
		return err
	}
	withDraw.ReqDate = param.ReqDate
	withDraw.DrawAmt = param.DrawAmt
	withDraw.DrawFee = param.DrawFee
	withDraw.BatchAutoSettle = param.BatchAutoSettle
	withDraw.AcctNo = param.AcctNo
	withDraw.AcctName = param.AcctName
	withDraw.DrawState = param.DrawState
	withDraw.Memo = param.Memo
	withDraw.CreatedTime = utils.Str2Time(param.CreatedTime)
	withDraw.CompleteTime = utils.Str2Time(param.CompleteTime)

	_, err = dao.UpdateEntity(db, withDraw)
	return err
}

// OrderStatusCallback 订单状态回调 todo param.OrderStatus=6 时暂时无法区分全部退款还是部分退款
func OrderStatusCallback(param *lakala.QueryOrderCallBackResp) error {
	var (
		db = dao.GetDB()
	)

	order, err := partner.CurOrderManager.LoadOrder(param.OutOrderNo, model.VendorIDJX)
	if err != nil {
		return err
	}
	// 0:待支付 1:支付中 2:支付成功 3:支付失败 4:已过期 5:已取消 6：部分退款或者全部退款
	switch param.OrderStatus {
	case "0", "1":
		order.Status = model.OrderStatusWait4Pay
	case "2":
		if order.DeliveryType == model.OrderDeliveryTypeSelfTake {
			order.Status = model.OrderStatusFinished
			order.OrderFinishedAt = time.Now()
		} else {
			order.Status = model.OrderStatusAccepted
		}
	case "3":
		order.Status = model.OrderStatusWait4Pay
	case "4", "5":
		order.Status = model.OrderStatusCanceled
		order.OrderFinishedAt = time.Now()
	case "6":

	}
	order.VendorOrderID2 = param.OrderTradeInfo.LogNo
	order.VendorStatus = param.OrderStatus
	_, err = dao.UpdateEntity(db, order, "Status", "VendorOrderID2", "VendorStatus", "OrderFinishedAt")

	orderPay := &model.OrderPay{
		PayOrderID: param.PayOrderNo,
	}
	orderPay.DeletedAt = utils.DefaultTimeValue
	if err := dao.GetEntity(db, orderPay, "PayOrderID", "DeletedAt"); err == nil {
		if orderPay.Status != 0 {
			return err
		}
		loc, _ := time.LoadLocation("Local")
		t1, _ := time.ParseInLocation("20060102150405", param.OrderTradeInfo.TradeTime, loc)
		orderPay.PayFinishedAt = utils.Time2Pointer(t1)
		orderPay.OriginalData = utils.Format4Output(param, true)
		//TradeType              string `json:"trade_type"`                // M	String	16	交易类型	PAY-消费 REFUND-退款 CANCEL-撤销
		//TradeStatus            string `json:"trade_status"`              // M	String	2	支付状态	返回状态 S:成功 F:失败 C:被冲正 U:预记状态 X:发送失败 T: 发送超时 P: 处理中
		orderPay.TransactionID = param.OrderTradeInfo.LogNo
		switch param.OrderTradeInfo.TradeStatus {
		case "S":
			orderPay.Status = model.PayStatusYes
		default:
			orderPay.Status = model.PayStatusFailed
		}

		dao.UpdateEntity(db, orderPay)
	}

	separate, _ := dao.GetSeparateAmtByOrderID(order.VendorOrderID, lakala.SeparateType_SEPATRATE, "")
	if separate != nil {
		separate.LogNo = param.OrderTradeInfo.LogNo
		separate.Remark += "->收银台订单未分账"
		dao.UpdateEntity(db, separate, "LogNo", "Remark")
	}
	return err
}
