#include "common.h"
#include "gpio_control.h"
#include "tank_angle.h"
#include "device_init.h"
#include "gpio_init.h"
#include "devcontrol_common.h"
#include "http_request.h"
#include "delay.h"

#define GPIO_ID_THREAD_COUNT 3

int gpio_device_id[GPIO_ID_THREAD_COUNT]={DEVICE_TANK0202,DEVICE_TANK0203,DEVICE_TANK0204};//需要打开线程池设备号

const gpiocontrol_t *gpio_control_config_t = NULL ;//gpio结构体标识

ThreadPool_t *g_pool_device_gpio_control_t;//gpio限位线程池标识，只在特地设备中打开

void public_pin_value(int pin,int value);
void car0103_pin_value(int pin,int value);
void car0104_pin_value(int pin,int value);

void public_pwm_value(int pin ,int value);
void tank0202_pwm_value(int pin,int value);
void tank0203_pwm_value(int pin,int value);
void tank0204_pwm_value(int pin,int value);
void tank0206_pwm_value(int pin,int value);
void ship0301_pwm_value(int pin,int value); 
void dog0501_pwm_value(int pin,int value);

uint64_t g_tank_shot_interval_ms=5000; //冷却时间
 
uint64_t g_tank_shot_ms=1000; //射击时间

TankFireControl g_device_shot_t;   // 真正的结构体变量

/*获取时间戳函数*/
// uint64_t get_shot_timestamp_ms() {
//     struct timeval tv;
//     if (gettimeofday(&tv, NULL) == -1) {
//         my_zlog_error("gettimeofday failed");
//         return 0;
//     }
//     return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
// }

/**
 * @brief 初始化坦克射击控制器
 * @param this 控制器指针
 * @param interval_ms 冷却时间（毫秒）
 * @param duration_ms 射击持续时间（毫秒）
 */
void device_shot_fire_init(TankFireControl* this, uint32_t interval_ms, uint32_t duration_ms) {
    this->last_shot_end_time = 0;
    this->shooting_start_time = 0;
    this->state = TANK_STATE_READY;
    this->shot_interval_ms = interval_ms;
    this->shot_duration_ms = duration_ms;
}

/*
**射击需要的相关设备冷却初始化
**对需要射击冷却的进行初始化
*/
int device_shot_cooling_init(){
    if(g_device_type ==DEVICE_TANK0202||g_device_type ==DEVICE_TANK0203){
        my_zlog_info("using %d shot init",g_device_type);
        device_shot_fire_init(&g_device_shot_t,g_tank_shot_interval_ms,g_tank_shot_ms);
    }else {
        return -1;
    }

    return 0; 
}

/**
 * @brief 检查坦克射击状态
 * @param this 控制器指针
 * @return 0=允许射击, -1=禁止射击（冷却中或射击中）
 */
int device_fire_check(TankFireControl* this) {
    uint64_t current_time = get_current_time_millis(); // 假设已实现此函数

    switch (this->state) {
        case TANK_STATE_READY:
            if (current_time - this->last_shot_end_time < this->shot_interval_ms) {
                return -1; // 仍在冷却
            }
            my_zlog_info("shot start");
            // 开始新射击
            this->shooting_start_time = current_time;
            this->state = TANK_STATE_SHOOTING;
            return 0;

        case TANK_STATE_SHOOTING:
            if (current_time - this->shooting_start_time > this->shot_duration_ms) {
                // 射击结束，进入冷却
                my_zlog_info("shotend，cooling");
                this->last_shot_end_time = current_time;
                this->state = TANK_STATE_COOLDOWN;
                g_tank_shot_index_cool=0;
                return -1;
            }
            my_zlog_info("shot continue");
            return 0; // 继续射击

        case TANK_STATE_COOLDOWN:
            if (current_time - this->last_shot_end_time >= this->shot_interval_ms) {
                this->state = TANK_STATE_READY;
                my_zlog_info("coolend");
                return 0; // 冷却完成
            }
            return -1; // 仍在冷却
    }
    return -1;
}

/*
*设备加上冷却射击切换
*/
int device_shoting_check(int pin,int val){
    if(device_fire_check(&g_device_shot_t)!=0){
        softPwmWrite(pin, 0);
    }else{
        softPwmWrite(pin, val);
    }
}

/*坦克限位线程函数*/
void tank_angle_limit_function(void *arg_gpio){
    static int limit_log_count=0;
     if (arg_gpio != NULL) {
        free(arg_gpio);
    }
    my_zlog_debug("limit task started.");
    while(1){
        int limit_status = angle_limit();
        if(limit_status==1) {
            device_gpio_control(g_device_type,5,0);
            my_zlog_debug("lift limit stop");
        }
        else if(limit_status==2) {
            device_gpio_control(g_device_type,7,0);
            my_zlog_debug("right limit stop");
        }
        else if(limit_status==0) {
            delay_ms(5);
            limit_log_count++;
            if(limit_log_count>=400){
                my_zlog_debug("limit stop");
                limit_log_count=0;
            }
            
        }
    }
    free(arg_gpio);
}

/*角度限位线程池初始化*/
void device_gpio_control_threadpoll_init(){
    int *arg_gpio = malloc(sizeof(int));
    my_zlog_info("device_gpio_control_threadpoll_init start\n");
    *arg_gpio = 2;
    g_pool_device_gpio_control_t = thread_pool_init(1,1);
    thread_pool_add_task(g_pool_device_gpio_control_t, tank_angle_limit_function, arg_gpio);
}

/*设备拉低引脚结构体数组*/
const gpiocontrol_t gpio_configs[] = {
    {
        .device_id = DEVICE_CAR0101,
        .device_pin_value =public_pin_value,
        .device_pwm_value =public_pwm_value
    },
    {
        .device_id = DEVICE_CAR0102,
        .device_pin_value =public_pin_value,
        .device_pwm_value =public_pwm_value
    },
    {
        .device_id = DEVICE_CAR0103,
        .device_pin_value =car0103_pin_value,
        .device_pwm_value =public_pwm_value
    },
    {
        .device_id = DEVICE_CAR0104,
        .device_pin_value =car0104_pin_value,
        .device_pwm_value =public_pwm_value
    },
    {
        .device_id = DEVICE_TANK0202,
        .device_pin_value =public_pin_value,
        .device_pwm_value =tank0202_pwm_value,
        .device_gpio_pthread_create=device_gpio_control_threadpoll_init
    },
    {
        .device_id = DEVICE_TANK0203,
        .device_pin_value =public_pin_value,
        .device_pwm_value =tank0203_pwm_value,
        .device_gpio_pthread_create=device_gpio_control_threadpoll_init
    },
    {
        .device_id = DEVICE_TANK0204,
        .device_pin_value =public_pin_value,
        .device_pwm_value =tank0204_pwm_value,
        .device_gpio_pthread_create=device_gpio_control_threadpoll_init
    },
    {
        .device_id = DEVICE_TANK0206,
        .device_pin_value =public_pin_value,
        .device_pwm_value =tank0206_pwm_value
    },
    {
        .device_id = DEVICE_SHIP0301,
        .device_pin_value =public_pin_value,
        .device_pwm_value =ship0301_pwm_value
    },
    {
        .device_id = DEVICE_PAO_PTZ0401,
        .device_pin_value =public_pin_value,
        .device_pwm_value =public_pwm_value
    },
    {
        .device_id = DEVICE_ROBOT_DOG0501,
        .device_pin_value =public_pin_value,
        .device_pwm_value =dog0501_pwm_value
    },
    // 结束标记
    { .device_id = -1 }
};

/*
设备控制代码
*/
void device_gpio_control(int device_id,int pin,int val) {

    if (!gpio_control_config_t || gpio_control_config_t->device_id != device_id) {
        // 查找设备配置
        for(int i = 0; gpio_configs[i].device_id != -1; i++) {
            if(gpio_configs[i].device_id == device_id) {
                gpio_control_config_t = &gpio_configs[i];
                break;
            }
        }
        for(int i=0;i<GPIO_ID_THREAD_COUNT;i++ ){
            if(gpio_control_config_t && device_id == gpio_device_id[i]){
                my_zlog_info("线程函数:%d", device_id);
                gpio_control_config_t->device_gpio_pthread_create(); //创建线程，线程关闭在tank.common.h中何tank需要的其他线程关闭
            }
        }
    }
    
    if(!gpio_control_config_t) {
        my_zlog_error("Error: Device gpio stop ID %d not found!", device_id);
        return;
    }

    gpio_control_config_t->device_pin_value(pin,val);
    gpio_control_config_t->device_pwm_value(pin,val);         
}

void public_pin_value(int pin,int value) {	//引脚控制
	for(int i = 0 ; i <= g_gpiocount ; i++) {
        if(pin == g_gpiowpi[i]) {
            break;
        }if(i == g_gpiocount) {
            return ;
        }   
    }
    if(value==1) {
		digitalWrite(pin, HIGH);
		my_zlog_debug("pin:%d,%d",pin,HIGH);
	}else if(value==0) {
		digitalWrite(pin, LOW);
		my_zlog_debug("pin:%d,%d",pin,LOW);
	}
	
}

/*挖机pin控制*/
void car0103_pin_value(int pin,int value){
    if(pin == 26 && value==1) {
        public_pin_value(27,1);
        public_pin_value(pin,value);
    }else if(pin == 26 && value==0){
        public_pin_value(27,0);
        public_pin_value(pin,value);
    }else if(pin == 253 && value==1){
        public_pin_value(27,0);
        public_pin_value(26,1);
        public_pin_value(24,1);
    }else if(pin == 254 && value==1){
        public_pin_value(27,1);
        public_pin_value(26,0);
        public_pin_value(24,0);
    }else if((pin == 254||pin == 253) && value==0){
        public_pin_value(27,0);
        public_pin_value(26,0);
        public_pin_value(24,0);
    }else {
        public_pin_value(pin,value);
    }
}

/*推土机pin控制*/
void car0104_pin_value(int pin,int value){
    if(pin==24){
        public_pin_value(26,value);
    }else if(pin==26){
        public_pin_value(24,value);
    }else public_pin_value(pin,value);
}

void public_pwm_value(int pin ,int value){
        for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
            if(pin == g_gpioPwm[i]) {
                break;
            }
            if(i == g_gpio_softpwmcount) {
                return ;
            }
    }
     
    int shot_speed = (int)(g_shot_speed_value*100);
    if(value==1) {
		
		if(pin == 27){
                softPwmWrite(pin, shot_speed);
                my_zlog_debug("pwm:%d,%d",pin,shot_speed);
        } else {
                softPwmWrite(pin, shot_speed);
                 my_zlog_debug("pwm:%d,%d",pin,shot_speed);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
    my_zlog_debug("public pwm");

}

void tank0202_pwm_value(int pin,int value) {	//软件陪我们控制调速
    for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    
    if(value==1) {
		if(pin == 27){
            device_shoting_check(27,30);   
        } else {
            softPwmWrite(pin, 40);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
     my_zlog_debug("tank0202 pwm");
}

void tank0203_pwm_value(int pin,int value) {	//软件陪我们控制调速
    for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    if(value==1) {
		
		if(pin == 27){
            device_shoting_check(27,30); 
        } else {
            softPwmWrite(pin, 35);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
    my_zlog_debug("tank0203 pwm");
}

void tank0204_pwm_value(int pin,int value){
        for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    if(value==1) {
		
		if(pin == 27){
          device_shoting_check(27,30); 
        } else {
            softPwmWrite(pin, 35);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
    my_zlog_debug("tank0204 pwm");
}

void tank0206_pwm_value(int pin,int value) {	//软件陪我们控制调速
    for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    
    if(value==1) {
		if(pin == 27){
            softPwmWrite(26, 35);
        } else {
            softPwmWrite(pin, 35);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
        if(pin == 27) softPwmWrite(26, 0);
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
     my_zlog_debug("tank0206 pwm");
}

void ship0301_pwm_value(int pin,int value) {	//软件陪我们控制调速
    for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    
    if(value==1) {
		if(pin == 27){
            softPwmWrite(pin, 50);
        } else {
            softPwmWrite(pin, 35);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
     my_zlog_debug("ship0301 pwm");
}


void dog0501_pwm_value(int pin,int value) {	//软件陪我们控制调速
    for(int i = 0 ; i <= g_gpio_softpwmcount ; i++) {
        if(pin == g_gpioPwm[i]) {
            break;
        }
        if(i == g_gpio_softpwmcount) {
            return ;
        }
    }
    
    if(value==1) {
		if(pin == 27){
            softPwmWrite(pin, 50);
        } else {
            softPwmWrite(pin, 35);
            my_zlog_debug("pwm:%d",pin);
        }
        
	}else if(value==0) {
		softPwmWrite(pin, 0);
		my_zlog_debug("pwm:%d,0",pin);
	}
     my_zlog_debug("dog0501 pwm");
}


