package service

import (
	"errors"
	"strings"
	"time"

	. "app.yhyue.com/moapp/jybase/date"
	. "bp.jydev.jianyu360.cn/BaseService/resourceCenter/public/entity"
)

/*
 * 资源扣减
 * @param appid
 * @param function_code 功能代码
 * @param userId 用户id
 * @param entId 企业id
 * @param count 扣减数量
 * @param ids 业务id
 * @return 状态 0：失败 1：成功 -1：不在有效期内 -2：数量不足 -3：没有授权
 */
func Deduction(appid, function_code string, account_id, ent_account_id int64, count int64, ids []string) (int64, error) {
	if appid == "" {
		return 0, errors.New("无效的参数appid")
	} else if function_code == "" {
		return 0, errors.New("无效的参数function_code")
	} else if count <= 0 {
		return 0, errors.New("无效的参数count")
	} else if account_id == 0 && ent_account_id == 0 {
		return 0, errors.New("无效的参数account_id、ent_account_id")
	}
	function := Base_function.FindByCode(appid, function_code)
	if function == nil {
		return 0, errors.New("功能原始表中没有找到该功能")
	}
	myPowers := Base_power.FindMyPowersByFc(appid, function_code, account_id, ent_account_id)
	if myPowers == nil || len(*myPowers) == 0 {
		return -1, errors.New("功能权益表中没有找到权益记录")
	}
	use_values, detail_values := []interface{}{}, [][]interface{}{}
	update := [][]interface{}{}
	surplus_count := int64(-1)
	deduct_count := count
	var use_account_id int64
	if function.Power_rule == 2 { //周期+数量
		my_surplus_count := int64(0)
		for _, v := range *myPowers {
			if v.Surplus_count <= 0 {
				continue
			}
			if v.Power_type == 1 {
				use_account_id = account_id
			} else if v.Power_type == 2 {
				use_account_id = ent_account_id
			} else {
				continue
			}
			if deduct_count > 0 {
				this_deduct_count := deduct_count
				if v.Surplus_count >= deduct_count { //本次记录的数据足够扣减
					v.Surplus_count -= deduct_count
					deduct_count = 0
				} else { //本次不够扣减，把本次的扣完，进入下次扣减
					v.Surplus_count = 0
					this_deduct_count = v.Surplus_count
					deduct_count -= v.Surplus_count
				}
				update = append(update, []interface{}{v.Id, v.Surplus_count, NowFormat(Date_Full_Layout)})
				detail_values = append(detail_values, []interface{}{appid, v.Id, v.Surplus_count, this_deduct_count, NowFormat(Date_Full_Layout)})
			}
			my_surplus_count += v.Surplus_count
		}
		//剩余的总数成功完成了本次的扣减
		if deduct_count == 0 {
			surplus_count = my_surplus_count
		}
	} else if function.Power_rule == 3 { //周期+频率+数量
		for _, v := range *myPowers {
			if v.Power_type == 1 {
				use_account_id = account_id
			} else if v.Power_type == 2 {
				use_account_id = ent_account_id
			} else {
				continue
			}
			use, err := Base_resource_use.FindLastOne(appid, function_code, use_account_id)
			if err != nil {
				return 0, errors.New("查询资源使用记录失败，" + err.Error())
			}
			if use != nil {
				create_time, err := time.ParseInLocation(Date_Full_Layout, use.Create_time, time.Local)
				if err != nil {
					return 0, errors.New("资源充值/消耗表创建时间错误，" + use.Create_time + "，" + err.Error())
				}
				now := time.Now()
				if v.Limit_strategy == "1d" {
					if create_time.Year() == now.Year() && create_time.Month() == now.Month() && create_time.Day() == now.Day() {
						surplus_count = use.Surplus_count - count
					} else {
						surplus_count = v.Strategy_count - count
					}
				} else if v.Limit_strategy == "1m" {
					if create_time.Year() == now.Year() && create_time.Month() == now.Month() {
						surplus_count = use.Surplus_count - count
					} else {
						surplus_count = v.Strategy_count - count
					}
				} else {
					return 0, errors.New("limit_strategy格式错误，" + v.Limit_strategy)
				}
			} else {
				surplus_count = v.Strategy_count - count
			}
			if surplus_count >= 0 {
				detail_values = append(detail_values, []interface{}{appid, v.Id, surplus_count, count, NowFormat(Date_Full_Layout)})
				break
			}
		}
	}
	if surplus_count < 0 {
		return -2, nil
	} else {
		use_values = append(use_values, appid, use_account_id, function_code, 0, surplus_count, count, strings.Join(ids, ","), NowFormat(Date_Full_Layout))
	}
	if len(use_values) > 0 && len(detail_values) > 0 && Base_resource_use.Deduction(use_values, detail_values, update) {
		return 1, nil
	}
	return 0, nil
}
