#include "tank_common.h"
#include "devcontrol_common.h"
#include "modules_common.h"
#include "gpio_common.h"

int tank_shot_back_stop(int pin,int val);

static const tank_common_back *s_tank_common_config = NULL;

int g_tank_shot_index=0;//状态机，用于状态机,坦克接收射击倒退状态机全局变量
static bool s_tank_shot_index_cool=1;//状态机，用于冷却状态机,坦克接收射击倒退状态机全局变量

/*击打后退速度设置，混空模式下为单路，单独模式下为双路控制，后续需要优化*/
void tank_shot_back(int gval) {

	int b=0;
	int valt[3]={0};
	valt[1]=2;
	if(gval==0) valt[2]=0;
	else valt[2]=gval;
	device_walk_control(g_device_type,valt);
}
 
 
static const tank_common_back s_tank_common_configs[]={
    {
        .device_id = DEVICE_TANK0202,
        .back_time=30,//后退多少ms
        .back_interval_back=1000, //间隔多少次才能再次使用，一次等于5ms
        .shot_back_speed=90,
        .shot_back=tank_shot_back_stop
        
    },
    {
        .device_id = DEVICE_TANK0203,
        .back_time=30,//后退多少ms
        .back_interval_back=1000, //间隔多少次才能再次使用，一次等于5ms
        .shot_back_speed=90,
        .shot_back=tank_shot_back_stop
    },
	{
        .device_id = DEVICE_TANK0204,
        .back_time=30,//后退多少ms
        .back_interval_back=1000, //间隔多少次才能再次使用，一次等于5ms
        .shot_back_speed=90,
        .shot_back=tank_shot_back_stop
    },


    { .device_id = -1 }
};

static bool s_back_status=false;
static bool s_backshot_status=false;

/*获取后退状态*/
bool get_backstatus(){
	return s_back_status;
}

/*获取是否在射击，射击状态*/
bool get_backshotstatus(){
	return s_backshot_status;
}

/*获取是否在射击，射击状态*/
bool set_backshotstatus(bool flag){
	s_backshot_status=flag;
}

/*后退函数*/
static int tank_delay_shot_back(){			
	if(g_device_delay_back_count  <= s_tank_common_config->back_time) {
		tank_shot_back(s_tank_common_config->shot_back_speed);
		my_zlog_debug("击打成功");	
	}
	else if(g_device_delay_back_count  > s_tank_common_config->back_time&&g_device_delay_back_count  < (s_tank_common_config->back_time+30)){
		tank_shot_back(0);
		my_zlog_debug("击打完成");
	}
	else if(g_device_delay_back_count>s_tank_common_config->back_interval_back){
		g_tank_shot_index = 1;
		s_back_status=false;
	}
}

//射击冷却检测计时变量
static bool s_cool_count_index =true;

/*用来判断有射击冷却的检测的状态获取*/
bool getshot_detection_index(){
	return s_cool_count_index;
}
/*用来设置有射击冷却的检测的状态获取*/
bool setshot_detection_index(bool flag){
	s_cool_count_index=flag;
}

// 坦克射击操作互斥锁
static pthread_mutex_t s_tankshot_detection_mutex = PTHREAD_MUTEX_INITIALIZER; 

static int s_tankshot_detectionback_count=0;
/*flag=0时初始化冷却时间，1是计时，2是返回计时值,3是重置计时*/
int tankshot_detection_backcount(int *cool_time,int flag){
	static int cool_count_init=0;
	static int cool_count=0;

	pthread_mutex_lock(&s_tankshot_detection_mutex);
	if(flag==0){
		cool_count_init=*cool_time;
		my_zlog_info("cool_count_init的值：%d",cool_count_init);
	}
	else if(flag==1){
		cool_count++;
		if(cool_count>cool_count_init*2){
			setshot_detection_index(true);
		}
		if(cool_count>200000) cool_count=200001;
	}else if(flag==2){
		return cool_count;
	}else if(flag==3){
		cool_count=0;
		s_tankshot_detectionback_count=0;
		my_zlog_info("冷却计时重置");
	}else if(flag==4){
		s_tankshot_detectionback_count=0;
	}
	pthread_mutex_unlock(&s_tankshot_detection_mutex);
}

static void tankshot_detectionback(){
	static bool index=0;
	if(digitalRead(12)==LOW) {
			delay_ms(10);
		if(digitalRead(12)==LOW){
			s_back_status=true;
			index=1;
			delay_ms(90); // 延时 100ms，防止抖动	
			g_device_delay_back_count=0;
			softPwmWrite(27, 0);
			set_backshotstatus(false);
			my_zlog_info("检测引脚12拉低");
		}
		
	}
	if(s_back_status==true&&index==1) {
		tank_delay_shot_back();
	}
	s_tankshot_detectionback_count++;
	if(s_tankshot_detectionback_count>3000){
		softPwmWrite(27, 0);
	}
}

//多线程处理坦克发射后退线程池
void tank_shot_back_stop_task_function(void *arg) {
	
	if(arg!= NULL){
		free(arg);
	}

	// 设置 GPIO 23 为输入模式，启用内部上拉电阻
    // pinMode(23, INPUT);
    // pullUpDnControl(23, PUD_UP);
    // my_zlog_debug("开始监测 GPIO 23 状态...\n");

	while(1){

		switch(g_device_type){
			case DEVICE_TANK0202:
            case DEVICE_TANK0203:
                tank_delay_shot_back();
                break;
			case DEVICE_TANK0204:
				tankshot_detection_backcount(0,1);
				tankshot_detectionback();
				break;
            default:
                break;
		}
				
		delay_us(500);

	}
	free(arg);
}

static ThreadPool_t *s_pool_tank_t;//坦克后退线程函数

/*坦克后退线程池打开*/
void tank_shot_pthrpoll_task_init(){
	int *arg = malloc(sizeof(int));
	*arg = 1;
	s_pool_tank_t=thread_pool_init(1,1);
	thread_pool_add_task(s_pool_tank_t, tank_shot_back_stop_task_function, arg);
	my_zlog_info("线程池打开");
}

/*坦克后退射击*/
int tank_shot_back_stop(int pin,int val){

	if(pin !=27){
		my_zlog_debug("非27引脚");
		return 1;
	}	
	
	if(val == 0) {
		tank_shot_back(0);
	}
	if(val != 0) {
		if(g_tank_shot_index == 0){
			tank_shot_pthrpoll_task_init();
			g_tank_shot_index=1;
		}
		if(g_tank_shot_index == 1 && s_tank_shot_index_cool==0){
			g_device_delay_back_count =0;
			g_tank_shot_index = 2;
			s_tank_shot_index_cool=1;
		}
	}
	
}

/*设置s_tank_shot_index_cool，将他置0，让坦克后退*/
void set_tank_shot_index_cool(bool index){
	s_tank_shot_index_cool=index;
}

/*
* @brief 销毁坦克使用的线程池，让其正常销毁，只有在tank相关设备号下才有用，最后销毁都会到device——common.h中
*/
void device_poilthread_close(){
	if(s_pool_tank_t)  thread_pool_destroy(s_pool_tank_t);
	if(g_pool_device_gpio_control_t) thread_pool_destroy(g_pool_device_gpio_control_t);
}

/*坦克射击接口，只有在特定设备号下使用*/
void tank_shot_stop_control(int device_id,int pin,int val) {

    if (!s_tank_common_config || s_tank_common_config->device_id != device_id) {
        // 查找设备配置
        for(int i = 0; s_tank_common_configs[i].device_id != -1; i++) {
            if(s_tank_common_configs[i].device_id == device_id) {
                s_tank_common_config = &s_tank_common_configs[i];
                break;
            }
        }
    }
    
    if(!s_tank_common_config) {
        // 同一个 device_id 反复失败时避免刷屏日志
        static int s_last_not_found_id = -1;
        if (device_id != s_last_not_found_id) {
            my_zlog_error("Error: Device tank stop ID %d not found!", device_id);
            s_last_not_found_id = device_id;
        }
        return;
    }
    s_tank_common_config->shot_back(pin,val);
             
}

