package talent_service

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"youngmini_server/app/dao"
	"youngmini_server/app/model"
	"youngmini_server/app/model/talent_model"
	"youngmini_server/app/utils"
)

// GetBoBoCoinList 获取卜卜币收入支出记录列表
func GetBoBoCoinList(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	//res, err := g.DB().Model(dao.BobocoinIncomeRecord.Table, "coin").Where("coin.talent_id", tid).OrderDesc("complete_date").
	//	LeftJoin(dao.OrderInfo.Table, "order", "order.order_id=coin.order_id").
	//	LeftJoin(dao.TaskBaseInfo.Table, "task", "task.task_id=order.task_id").
	//	Fields("task.task_name", "coin.*").All()
	//var res []*talent_model.BoBoCoinIncomeInfo
	//err = g.DB().Model(dao.BobocoinIncomeRecord.Table).WithAll().Where("talent_id", tid).Scan(&res)
	//if err != nil {
	//	return &TalentHttpResult{Code: -2, Msg: "query income info failed"}
	//}
	//
	//res1, err := g.DB().Model(dao.BobocoinWithdrawalRecord.Table).Where("talent_id = ?", tid).OrderDesc("complete_date").All()
	//if err != nil {
	//	return &TalentHttpResult{Code: -3, Msg: "query draw info failed"}
	//}
	//
	//if res == nil {
	//	res = make([]*talent_model.BoBoCoinIncomeInfo, 0)
	//}
	//
	//if res1 == nil {
	//	res1 = make([]gdb.Record, 0)
	//}
	//
	//allInfo := talent_model.BoBoCoinDetailAccount{IncomeList: res, DrawMoneyList: res1}
	//
	//return &TalentHttpResult{Code: 0, Msg: "success", Data: allInfo}



	// 计算待结算卜卜币
	var waitSettleValue, settleUpValue int64
	var talentAllOrder []*model.OrderInfo
	err = g.DB().Model(dao.OrderInfo.Table).Scan(&talentAllOrder, dao.OrderInfo.Columns.TalentId, tid)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "query talent order info failed"}
	}

	for _, v := range talentAllOrder {
		if v.CompleteStatus < int(utils.OrderCompleteTypeNormal) {
			if v.OrderStatus > 1 {
				// 执行中的订单，稿费计入待结算
				waitSettleValue += v.SettleAmount
			}
		}

		if v.CompleteStatus == int(utils.OrderCompleteTypeNormal) {
			// 执行完成订单，稿费计入已结算
			settleUpValue += v.SettleAmount
		}
	}

	// 查询总收入
	var incomeRes []*model.BobocoinIncomeRecord
	err = g.DB().Model(dao.BobocoinIncomeRecord.Table).Scan(&incomeRes, dao.BobocoinIncomeRecord.Columns.TalentId, tid)
	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: "query income info failed"}
	}

	incomeRecMap := make(map[uint64]*model.BobocoinIncomeRecord)

	var incomeValue int64
	// 校验总收入和上面统计的已结算是否相等
	for _, v := range incomeRes {
		incomeValue += v.BobocoinValue

		incomeRecMap[uint64(v.OrderId)] = v
	}

	if incomeValue != settleUpValue {
		return &TalentHttpResult{Code: -4, Msg: "income value not equ settle up value"}
	}

	// 查询扣款记录
	var deductRes []*model.BobocoinDeductRecord
	err = g.DB().Model(dao.BobocoinDeductRecord.Table).Scan(&deductRes, dao.BobocoinDeductRecord.Columns.TalentId, tid)
	if err != nil {
		return &TalentHttpResult{Code: -5, Msg: "query income info failed"}
	}

	// 查询提现记录
	var withdrawRes []*model.BobocoinWithdrawalRecord
	err = g.DB().Model(dao.BobocoinWithdrawalRecord.Table).Scan(&withdrawRes, dao.BobocoinWithdrawalRecord.Columns.TalentId, tid)
	if err != nil {
		return &TalentHttpResult{Code: -6, Msg: "query income info failed"}
	}

	// 计算已提现和待打款
	var waitPay, hasPaied int64
	for _, v := range withdrawRes {
		if v.PayState == 2 {
			hasPaied += v.DrawAmount
		} else {
			waitPay += v.DrawAmount
		}
	}

	allInfo := talent_model.BoBoCoinDetailAccount{
		WaitSettle:    waitSettleValue,
		SettleUp:      settleUpValue,
		CanWithdraw:   settleUpValue - hasPaied - waitPay,  // 可提现金额为: 已结算金额 - 已打款金额 - 待打款金额
		HasWithDraw:   hasPaied,
		WaitPay:       waitPay,
		IncomeList:    incomeRes,
		DrawMoneyList: withdrawRes,
		DeductList:    deductRes,
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: allInfo}
}

// GetBoBoCoinOrderSettleInfo 获取订单结算卜卜币的信息
func GetBoBoCoinOrderSettleInfo(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	// 获取结束状态小于3(1进行中 2已结算)的订单
	var orderSettleInfo []*talent_model.BoBoCoinOrderInfo
	err = g.DB().Model(dao.OrderInfo.Table).Scan(&orderSettleInfo, "talent_id = ? and complete_status < 3 and order_status > 1", tid)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "query order info failed"}
	}

	orderListMap := make(map[uint64]*talent_model.BoBoCoinOrderInfo)

	// 分别存储已结算和未结算订单
	allOrderList := talent_model.BoBoCoinOrderSettleStateResult{}
	for _, v := range orderSettleInfo {
		if v.CompleteStatus == 1 {
			allOrderList.UnsettledOrders = append(allOrderList.UnsettledOrders, v)
		}

		if v.CompleteStatus == 2 {
			allOrderList.SettleUpOrders = append(allOrderList.SettleUpOrders, v)
			orderListMap[v.OrderId] = v
		}
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: allOrderList}
}

// GetBoBoCoinWithdrawalInfo 获取已有提现信息，目前只是支付宝账号
func GetBoBoCoinWithdrawalInfo(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	rec, err := g.DB().Model(dao.TalentInfo.Table).Fields(dao.TalentInfo.Columns.AliName, dao.TalentInfo.Columns.AliAccount).One("id", tid)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "query info failed"}
	}

	boboCoin, err := g.DB().Model(dao.BobocoinIncomeRecord.Table).Where("talent_id", tid).Sum(dao.BobocoinIncomeRecord.Columns.BobocoinValue)
	if err != nil {
		boboCoin = 0
	}

	drawMoney, err := g.DB().Model(dao.BobocoinWithdrawalRecord.Table).
		Where("talent_id = ? and (pay_state = 1 or pay_state = 2)", tid).
		Sum(dao.BobocoinWithdrawalRecord.Columns.DrawAmount)
	if err != nil {
		drawMoney = 0
	}

	data := talent_model.BoBoCoinWithdrawInfo{
		BoBoCoinValue: int64(boboCoin - drawMoney),
		AliName: rec["ali_name"].String(),
		AliAccount: rec["ali_account"].String(),
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: data}
}

// BindWithdrawalAccount 绑定提现账户信息
func BindWithdrawalAccount(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	var info *talent_model.BoBoCoinAliAccountInfo
	err = r.ParseForm(&info)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: err.Error()}
	}

	_, err = g.DB().Model(dao.TalentInfo.Table).Update(info, "id", tid)
	if err != nil {
		panic(err.Error())
	}

	return &TalentHttpResult{Code: 0, Msg: "success"}
}

// BoBoCoinWithdrawalReq 卜卜币提现申请
func BoBoCoinWithdrawalReq(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	// 查看提现账户信息是否完善
	accountRec, err := g.DB().Model(dao.TalentInfo.Table).
		Fields(dao.TalentInfo.Columns.AliName, dao.TalentInfo.Columns.AliAccount).
		One("id", tid)
	if err != nil || accountRec[dao.TalentInfo.Columns.AliName] == nil || accountRec[dao.TalentInfo.Columns.AliAccount] == nil {
		return &TalentHttpResult{Code: -2, Msg: "please complete withdrawal account info"}
	}

	var info *talent_model.BoBoCoinWithdrawalReq
	err = r.ParseForm(&info)
	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: err.Error()}
	}

	// 获取可提现金额
	inSum, err := g.DB().Model(dao.BobocoinIncomeRecord.Table).Where("talent_id", tid).Sum(dao.BobocoinIncomeRecord.Columns.BobocoinValue)
	if err != nil {
		return &TalentHttpResult{Code: -4, Msg: "query database failed"}
	}
	outSum, err := g.DB().Model(dao.BobocoinWithdrawalRecord.Table).
		Where("talent_id = ? and (pay_state = 1 or pay_state = 2)", tid).
		Sum(dao.BobocoinWithdrawalRecord.Columns.DrawAmount)
	if err != nil {
		return &TalentHttpResult{Code: -5, Msg: "query database failed"}
	}

	// 可提现金额小于申请提现金额，失败，返回
	withdrawAble := int64(inSum - outSum)
	if withdrawAble < info.WithdrawalAmount {
		return &TalentHttpResult{Code: -6, Msg: "bobocoin not enough"}
	}

	// 将请求写入数据库
	_, err = g.DB().Model(dao.BobocoinWithdrawalRecord.Table).Insert(model.BobocoinWithdrawalRecord{
		TalentId:     tid,
		DrawAmount:   info.WithdrawalAmount,
		PayAccount:   accountRec[dao.TalentInfo.Columns.AliAccount].String(),
		AccountName:  accountRec[dao.TalentInfo.Columns.AliName].String(),
		PayPlatform:  1,
		PayState:     1,
		SubmitDate:   gtime.Now(),
	})

	if err != nil {
		return &TalentHttpResult{Code: -7, Msg: "write to database failed"}
	}

	return &TalentHttpResult{Code: 0, Msg: "success"}
}