#include "foc/core/thro_torque.h"
#include "foc/foc_config.h"
#include "foc/motor/motor.h"
#include "foc/motor/motor_param.h"
#include "foc/core/e_ctrl.h"
#include "foc/core/PMSM_FOC_Core.h"
#include "app/nv_storage.h"
#include "libs/logger.h"
#include "prot/can_foc_msg.h"
#include "foc/core/etcs.h"
#include "foc/motor/throttle.h"

static thro_torque_t _torque;

void thro_torque_reset(void) {
	_torque.accl = false;
	_torque.thro_filted = 0.0f;
	_torque.throttle_opening = _torque.throttle_opening_last = 0.0f;
	_torque.torque_req = _torque.torque_real = _torque.torque_acc_ = 0.0f;
	_torque.gear = mc_get_internal_gear();
}

void thro_torque_init(void) {
	thro_torque_reset();
	_torque.spd_filted = 0.0f;
}

static __INLINE float gear_rpm_torque(u8 torque, s16 max) {
	return (float)torque/100.0f * max;
}

float thro_torque_gear_map(s16 rpm, u8 gear) {
	gear_t *_current_gear = mc_gear_conf_by_gear(gear);
	if (_current_gear == NULL) {
		return 0;
	}

	if (rpm > _current_gear->max_speed) {
		rpm = _current_gear->max_speed;
	}
	if (rpm <= 1000) {
		return gear_rpm_torque(_current_gear->torque[0], _current_gear->max_torque);
	}

	for (int i = 1; i < CONFIG_GEAR_SPEED_TRQ_NUM; i++) {
		if (rpm <= 1000 * (i + 1)) { //线性插值
			float trq1 = gear_rpm_torque(_current_gear->torque[i-1], _current_gear->max_torque);
			float min_rpm = (i * 1000);
			float trq2 = gear_rpm_torque(_current_gear->torque[i], _current_gear->max_torque);
			float max_rpm = (i + 1) * 1000;
			return f_map((float)rpm, min_rpm, max_rpm, trq1, trq2);
		}
	}
	return gear_rpm_torque(_current_gear->torque[CONFIG_GEAR_SPEED_TRQ_NUM-1], _current_gear->max_torque);
}

/* 获取油门开度 */
float get_throttle_ration(float f_throttle) {
	if (f_throttle <= throttle_start_vol()) {
		return 0;
	}
	float delta = f_throttle - throttle_start_vol();
	int ration = (delta * 100.0f) / throttle_vol_range();
	return ((float)ration)/100.0f;
}

float thro_ration_to_voltage(float r) {
	if (r == 0) {
		return 0;
	}
	float vol = throttle_start_vol() + r * throttle_vol_range();
	return fclamp(vol, 0, throttle_end_vol());
}

static float _thro_torque_for_accelerate(float ration) {
	float max_torque = thro_torque_gear_map((s16)_torque.spd_filted, _torque.gear);
	float thro_torque = max_torque * ration;

	float acc_r = 1.0f;
	if (_torque.throttle_opening_last < 1.0f) {
		acc_r = (ration - _torque.throttle_opening_last)/ (1.0f - _torque.throttle_opening_last);
	}
	acc_r = fclamp(acc_r, 0, 1.0f);
	float acc_torque = _torque.torque_real + acc_r * (max_torque - _torque.torque_real);
	if (acc_torque < 0) {
		acc_torque = 0;
	}
	/*
	   直接获取油门开度对应的加速扭矩thro_torque 不小于间接计算得到的 acc_torque
	*/
	float torque_acc_ = thro_torque - acc_torque;
	float step = 0.0f;
	if (torque_acc_ > 0) {
		float acc_t = mc_gear_conf()->accl_time;
		step = torque_acc_ / (acc_t + 0.00001f);
	}else {
		torque_acc_ = 0;
	}
	step_towards(&_torque.torque_acc_, torque_acc_, step);
	return (acc_torque + _torque.torque_acc_);
}


static float thro_torque_for_accelerate(void) {
	return _thro_torque_for_accelerate(_torque.throttle_opening);
}

static float thro_torque_for_decelerate(void) {
	if (_torque.throttle_opening_last == 0.0f) {
		return 0;
	}
	float dec_r = _torque.throttle_opening / _torque.throttle_opening_last;
	dec_r = fclamp(dec_r, 0.0f, 1.0f);
	return dec_r * _torque.torque_real;
}

static void thro_torque_request(void) {
#ifdef CONFIG_CRUISE_ENABLE_ACCL
	if (mc_is_cruise_enabled() && mc_throttle_released()) {
		return;
	}
#endif
	if (mc_throttle_released() && eCtrl_enable_eBrake(true)) {
		return;
	}
	if (!mc_throttle_released()) {
		float curr_rpm = PMSM_FOC_GetSpeed();
		if (_torque.accl) { //加速需求
			float ref_torque = thro_torque_for_accelerate();
			float hold_torque = PMSM_FOC_Get()->out.f_autohold_trq;
			if (hold_torque < 0) { //下坡驻车,最小给0扭矩
				hold_torque = 0;
			}
			ref_torque	= MAX(hold_torque, ref_torque);
			if (curr_rpm <= CONFIG_ZERO_SPEED_RPM) {//从静止开始加速
				if (_torque.torque_req < hold_torque) {
					_torque.torque_req = hold_torque;
					eCtrl_reset_Torque(hold_torque);
				}
			}else {
				PMSM_FOC_Get()->out.f_autohold_trq = 0;
			}
			/* 处理加速ramp时间的变化，需要缓慢变小，变大可以立即处理，
			*  加速时间缓慢变小可以防止突然大扭矩加速
			*/
			u16 now_ramp_time = eCtrl_get_torque_acc_time();
			u16 next_ramp_time = mc_gear_conf()->accl_time;
			if (curr_rpm < CONFIG_ZERO_SPEED_RAMP_RMP) {
				next_ramp_time = mc_gear_conf()->zero_accl;
			}
			if (next_ramp_time == 0) {
				next_ramp_time = 100;
			}
			if (now_ramp_time != next_ramp_time) {
				if (next_ramp_time > now_ramp_time) {
					eCtrl_set_accl_time(next_ramp_time);
				}else {
					float f_now = (float)now_ramp_time;
					float f_next = (float)next_ramp_time;
					step_towards(&f_now, f_next, 0.5f);
					if (f_now <= 10) {
						f_now = 10;
					}
					eCtrl_set_accl_time((u16)f_now);
				}
			}
			_torque.torque_req = ref_torque;
		}else {
			float ref_torque = thro_torque_for_decelerate();
			/* autohold 启动的情况下，转把在0位置附近小幅抖动 */
			if (curr_rpm <= CONFIG_ZERO_SPEED_RPM) {
				float hold_torque = PMSM_FOC_Get()->out.f_autohold_trq;
				ref_torque = MAX(hold_torque, ref_torque);
			}
			_torque.torque_req = ref_torque;
		}
		etcs_set_torque(_torque.torque_req);
	}else if (mc_throttle_released() && eCtrl_get_FinalTorque() != 0){
		_torque.torque_req = 0.0f;
		etcs_set_torque(_torque.torque_req);
	}
}

#define THRO_RPM_LP_CEOF 0.01f
void thro_torque_process(u8 run_mode, float f_throttle) {

	float thro_r = get_throttle_ration(f_throttle);
	_torque.gear = mc_get_internal_gear();
	LowPass_Filter(_torque.spd_filted, PMSM_FOC_GetSpeed(), THRO_RPM_LP_CEOF);

	if (thro_r > _torque.throttle_opening) {
		if (!_torque.accl) {
			_torque.throttle_opening_last = _torque.throttle_opening;
			_torque.torque_real = PMSM_FOC_Get()->in.s_targetTorque;
			if (_torque.torque_real < 0) { //电子刹车的时候，扭矩可能为负
				_torque.torque_real = 0;
			}
			_torque.torque_acc_ = 0;
		}
		_torque.accl = true;
	}else if (thro_r < _torque.throttle_opening) {
		if (_torque.accl) {
			_torque.throttle_opening_last = _torque.throttle_opening;
			_torque.torque_real = PMSM_FOC_Get()->in.s_targetTorque;
			if (_torque.torque_real < 0) { //电子刹车的时候，扭矩可能为负
				_torque.torque_real = 0;
			}
		}
		_torque.accl = false;
	}

	_torque.throttle_opening = thro_r;
	if (run_mode == CTRL_MODE_TRQ) {
		thro_torque_request();
	}else if (run_mode == CTRL_MODE_SPD) {
		if (!mc_is_cruise_enabled()) {
			float speed_Ref = PMSM_FOC_GetSpeedLimit() * _torque.throttle_opening;
			PMSM_FOC_Set_TgtSpeed(speed_Ref);
		}
	}else if (run_mode == CTRL_MODE_EBRAKE) {
		float vel = PMSM_FOC_GetSpeed();
		float ebrk_trq = motor_get_ebreak_toruqe(vel);

		if (ebrk_trq >= -PMSM_FOC_GetEbrkTorque()/2){
			eCtrl_Set_eBrk_RampTime(1);
		}
		if (ebrk_trq != 0) {
			eCtrl_set_TgtTorque(ebrk_trq);
		}

		if (eCtrl_get_FinalTorque() < 0.0001f && vel < CONFIG_MIN_RPM_EXIT_EBRAKE) {
			eCtrl_enable_eBrake(false);
			thro_torque_reset();
		}
		if (!mc_throttle_released() || (mc_throttle_released() && (vel == 0.0f))) {
			eCtrl_enable_eBrake(false);
			thro_torque_reset();
		}
	}
}

/* 定速巡航需要判断是否需要加速 */
float get_user_request_torque(void) {
	if (_torque.accl) {
		return thro_torque_for_accelerate();
	}
	return thro_torque_for_decelerate();
}

void thro_torque_log(void) {
	sys_debug("accl %d, real %f, req %f\n", _torque.accl, _torque.torque_real, _torque.torque_req);
	sys_debug("ration %f - %f - %f - %d\n", _torque.throttle_opening, _torque.throttle_opening_last, thro_torque_for_accelerate(), _torque.gear);
}
