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

int tank_shot_back_stop(unsigned char pin,unsigned char val);

const tank_common_back *g_tank_common_config_t = NULL;

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

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

	int b=0;
	unsigned char valt[3]={0};
	valt[1]=2;
	if(gval==0) valt[2]=0;
	else valt[2]=gval;
	device_walk_control(g_device_type,valt);
}
 
 
const tank_common_back tank_common_config_t[]={
    {
        .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  <= g_tank_common_config_t->back_time) {
		tank_shot_back(g_tank_common_config_t->shot_back_speed);
		my_zlog_debug("击打成功");	
	}
	else if(g_device_delay_back_count  > g_tank_common_config_t->back_time&&g_device_delay_back_count  < (g_tank_common_config_t->back_time+30)){
		tank_shot_back(0);
		my_zlog_debug("击打完成");
	}
	else if(g_device_delay_back_count>g_tank_common_config_t->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 tankshot_detection_i2c_mutex = PTHREAD_MUTEX_INITIALIZER; 

static int 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;

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

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

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

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

/*坦克后退射击*/
int tank_shot_back_stop(unsigned char pin,unsigned char 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 tank_thread_close(){
	thread_pool_destroy(pool_tank_t);
	thread_pool_destroy(g_pool_device_gpio_control_t);
}

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

    if (!g_tank_common_config_t || g_tank_common_config_t->device_id != device_id) {
        // 查找设备配置
        for(int i = 0; tank_common_config_t[i].device_id != -1; i++) {
            if(tank_common_config_t[i].device_id == device_id) {
                g_tank_common_config_t = &tank_common_config_t[i];
                break;
            }
        }
    }
    
    if(!g_tank_common_config_t) {
        my_zlog_error("Error: Device tank stop ID %d not found!", device_id);
        return;
    }
    g_tank_common_config_t->shot_back(pin,val);
             
}

