#include "common.h"
#include "self_devicecontrol.h"
#include "modules_common.h"
#include "app_device_common.h"
#include "drivers_common.h"


static ThreadPool_t *s_self_devicecontrol_task;//自控任务线程函数

static bool s_self_control_switch=false;//自控开关。是否打开或者关闭

static int s_self_control_interval=0;

static int s_self_control_time_count=0;
static pthread_mutex_t s_self_control_time_mutex = PTHREAD_MUTEX_INITIALIZER;

static devicecontroltask_t *s_self_device_control_data=NULL;//设备自控全局数据指针
static pthread_mutex_t s_self_device_control_data_mutex = PTHREAD_MUTEX_INITIALIZER;

static device_automatic_date_t s_automatic_data[DEVICE_WALK_SIGN_MAX]={0};

/*
* @brief 释放内存
*/
void free_device_tasks_memory() { 
    if(s_self_device_control_data!=NULL){
        pthread_mutex_lock(&s_self_device_control_data_mutex);
        free(s_self_device_control_data);
        s_self_device_control_data=NULL;
        my_zlog_debug("free s_self_device_control_data");
        pthread_mutex_unlock(&s_self_device_control_data_mutex);
    } else return;  
   
}

/*
* @brief 分配内存封装函数
*/
void malloc_device_tasks_memory() {
    pthread_mutex_lock(&s_self_device_control_data_mutex);
    if(s_self_device_control_data==NULL){
        s_self_device_control_data=(devicecontroltask_t*)malloc(sizeof(devicecontroltask_t));
        memset(s_self_device_control_data, 0, sizeof(devicecontroltask_t)); // 清零内存 
        my_zlog_debug("malloc s_self_device_control_data");
    }
   pthread_mutex_unlock(&s_self_device_control_data_mutex);
}

/*
* @brief 自控线程中的计时函数接口,每20ms加一次
* @param[in] self_control_time_count，计时次数
*/
void set_self_control_time_countfuntion(){
    pthread_mutex_lock(&s_self_control_time_mutex);
    s_self_control_time_count++;
    if(s_self_control_time_count>30000) s_self_control_time_count=30001;
    pthread_mutex_unlock(&s_self_control_time_mutex);
}


/*
* @brief 自控线程中的任务
*/
void self_device_control_task(){
    static int i=0;

    static int valt[3];

    int time_now = s_self_control_time_count*20;


    if(i>s_self_device_control_data->id_run_count){
            
            if(s_self_control_interval>time_now){
                return;
            }

            pthread_mutex_lock(&s_self_control_time_mutex);
            s_self_control_time_count=0;//将计时重置
            pthread_mutex_unlock(&s_self_control_time_mutex);
            i=0;
    }
    time_now = s_self_control_time_count*20;

    if(time_now > s_self_device_control_data->run_cool[i]&&
        time_now <= (s_self_device_control_data->run_cool[i]+s_self_device_control_data->timed_run[i]))
    {
        for(int j=0;j<s_automatic_data[s_self_device_control_data->id_run[i]].action_count;j++){

            valt[1]=s_automatic_data[s_self_device_control_data->id_run[i]].mode[j];
            valt[2]=s_automatic_data[s_self_device_control_data->id_run[i]].val[j];
        
            if(valt[2]>2) device_walk_control(g_device_type,valt);
            else if(valt[2]<=2) {
                device_gpio_control(g_device_type,valt[1],valt[2]);
                car0102_pin27_stop_control(g_device_type, valt[1], valt[2]);
            }

        }


    }else if(time_now >
            (s_self_device_control_data->run_cool[i]+s_self_device_control_data->timed_run[i]))
    {
    
        device_stop(g_device_type);//停止

        pthread_mutex_lock(&s_self_control_time_mutex);
        s_self_control_time_count=0;//将计时重置
        pthread_mutex_unlock(&s_self_control_time_mutex); 
        ++i;
    }
  
}

static bool s_selfcontrol_task_index=true;
/*
* @brief 自控线程
*/
void self_device_control_task_function(){
    my_zlog_debug("自控线程池循环开始");
    static int s_status =0; 
    while(s_selfcontrol_task_index){
        if(s_self_control_switch==true){
            self_device_control_task();
            s_status=1;
        }else if(s_self_control_switch==false){
            if(s_status==1) {
                device_stop(g_device_type);
                s_status=0;
            }
            delay_ms(100);
        }
    }
    free_device_tasks_memory();
    my_zlog_debug("自控线程池循环终止");
    return ;
}

/*
* @brief 开启自控线程
*/
void self_device_pthrpoll_task_init(){

	s_self_devicecontrol_task=thread_pool_init(1,1);
	thread_pool_add_task(s_self_devicecontrol_task, self_device_control_task_function, NULL);
	my_zlog_debug("自控线程池打开");
}

/*
* @brief 自控的线程开启标识设置。
* @param[in]  当index为，true为开，false为关
*/
void set_self_control_index(bool index){    
    s_self_control_switch =index;
}

/*
* @brief 获取自控的线程开启标识。
*/
bool get_self_control_index(){
    return s_self_control_switch;
}

/*
* @brief 销毁自控的线程
*/
void self_control_thread_close(){
    if(get_self_control_index()==true){
        my_zlog_debug("Destroy the thread of the automatic control device");
        s_selfcontrol_task_index=false;
	    thread_pool_destroy(s_self_devicecontrol_task);
        return ;
    }
    my_zlog_debug("The thread of the automatic control device is not opened");
}

/*
* @brief 返回MQTT自控打开或者关闭的函数 
*/
void send_self_contorl_mqtt(){
    // 创建根对象
    cJSON *root = cJSON_CreateObject();
    
    // 创建head对象
    cJSON *head = cJSON_CreateObject();
    cJSON_AddNumberToObject(head, "message_type", 3018);
    cJSON_AddItemToObject(root, "head", head);
    
    // 创建body对象
    cJSON *body = cJSON_CreateObject();
    cJSON_AddStringToObject(body, "cmd", "device_mycontrol");
    cJSON_AddNumberToObject(body, "switch_reply_status", get_self_control_index());
    cJSON_AddItemToObject(root, "body", body);
    
    // 将cJSON对象转换为字符串
    char *json_str = cJSON_PrintUnformatted(root);

    my_zlog_debug("%s",json_str);

    mqtt_publish_to_all(mqtt_topic_pure_number(), json_str, 0);

    free(json_str);
    cJSON_Delete(root);
}

/*
* @brief MQTT发送自控的相关的动作控制消息的函数，找后端要动作组合
*/
void send_self_contorl_date_mqtt(){
        // 创建根对象
    cJSON *root = cJSON_CreateObject();
    
    // 创建head对象
    cJSON *head = cJSON_CreateObject();
    cJSON_AddNumberToObject(head, "message_type", 3019);
    cJSON_AddItemToObject(root, "head", head);
    
    // 创建body对象
    cJSON *body = cJSON_CreateObject();
    cJSON_AddStringToObject(body, "cmd", "device_control_demand_date");
    cJSON_AddNumberToObject(body, "status", 1);
    cJSON_AddItemToObject(root, "body", body);
    
    // 将cJSON对象转换为字符串
    char *json_str = cJSON_PrintUnformatted(root);

    my_zlog_debug("%s",json_str);

    mqtt_publish_to_all(mqtt_topic_pure_number(), json_str, 0);

    free(json_str);
    cJSON_Delete(root);
}


/*
* @brief MQTT接收自控消息的函数 
*/
void receive_self_contorl_mqtt(cJSON *body){

    if (!body) {
        my_zlog_error("JSON error!");
        return;
    }

    cJSON *switch_status = cJSON_GetObjectItem(body, "switch_status");

    if (switch_status == NULL || !cJSON_IsNumber(switch_status)) {
    my_zlog_error("Invalid switch_status!");
    return;
    }

    static int s_switch_status = 0;
    static bool s_thread_index=0;
    s_switch_status=switch_status->valueint;

    if(s_switch_status == DEVICE_SELF_CONTROL_OPEN){
       if(s_thread_index==0) {
        self_device_pthrpoll_task_init();
        malloc_device_tasks_memory();//分配内存
       }

       pthread_mutex_lock(&s_self_control_time_mutex);
       s_self_control_time_count=0;
       pthread_mutex_unlock(&s_self_control_time_mutex);

       s_self_control_switch =true;
       s_thread_index=1;
       my_zlog_info("open device auto");
    }else if(s_switch_status == DEVICE_SELF_CONTROL_CLOSE) {
       s_self_control_switch =false;
       my_zlog_info("close device auto");
       return ;
    }

    cJSON *interval=cJSON_GetObjectItem(body, "interval");
    s_self_control_interval=interval->valueint;


    // 2️ id_run 数组
    cJSON *id_run = cJSON_GetObjectItem(body, "id_run");

    pthread_mutex_lock(&s_self_device_control_data_mutex);//加锁

    s_self_device_control_data->id_run_count = 0;
    if (cJSON_IsArray(id_run)) {
        int size = cJSON_GetArraySize(id_run);
        for (int i = 0; i < size && i < DEVICE_WALK_SIGN_MAX; i++) {
            cJSON *item = cJSON_GetArrayItem(id_run, i);
            s_self_device_control_data->id_run[i] = item->valueint;
            s_self_device_control_data->id_run_count=i;
        }
    }

     // 3 run_cool 数组
    cJSON *run_cool = cJSON_GetObjectItem(body, "run_cool");
    if (cJSON_IsArray(run_cool)) {
        int size = cJSON_GetArraySize(run_cool);
        for (int i = 0; i < size&& i < DEVICE_WALK_SIGN_MAX ; i++) {
            cJSON *item = cJSON_GetArrayItem(run_cool, i);
            s_self_device_control_data->run_cool[i] = item->valueint;
        }
    }

      // 4 timed_run 数组
    cJSON *timed_run = cJSON_GetObjectItem(body, "timed_run");
    if (cJSON_IsArray(timed_run)) {
        int size = cJSON_GetArraySize(timed_run);
        for (int i = 0; i < size && i < DEVICE_WALK_SIGN_MAX ; i++) {
            cJSON *item = cJSON_GetArrayItem(timed_run, i);
            s_self_device_control_data->timed_run[i] = item->valueint;
        }
    }

    pthread_mutex_unlock(&s_self_device_control_data_mutex);//解锁

    send_self_contorl_mqtt();

    my_zlog_debug("count:%d",s_self_device_control_data->id_run_count);

    return;
}

/*
* @brief MQTT接收自控的相关的动作控制消息的函数，接收后端相应动作组合
*/
void receive_self_contorl_date_mqtt(cJSON *body){
    if (!body) {
        my_zlog_error("JSON error!");
        return;
    }

    static int s_action_id = 0;

    cJSON *switch_status = cJSON_GetObjectItem(body, "switch_status");
    if(switch_status==NULL) return;
    static int s_switch_status = 0;
    s_switch_status=switch_status->valueint;


    if(s_switch_status == 1){
        cJSON *config= cJSON_GetObjectItem(body, "config");
        if(config==NULL)  return;
        if (cJSON_IsArray(config)) {
            int config_size = cJSON_GetArraySize(config);
            for (int i = 0; i < config_size && i < DEVICE_WALK_SIGN_MAX; i++) {

                cJSON *config_item = cJSON_GetArrayItem(config, i);
                cJSON *action_id = cJSON_GetObjectItemCaseSensitive(config_item, "action_id");

                s_action_id=action_id->valueint;


                cJSON *action_array = cJSON_GetObjectItemCaseSensitive(config_item, "action");
                if(cJSON_IsArray(action_array)){
                    int action_size = cJSON_GetArraySize(action_array);

                    for (int j = 0; j < action_size && j < DEVICE_WALK_SIGN_MAX; j++) {

                        cJSON *item = cJSON_GetArrayItem(action_array, j);

                        // 获取 combination 和 speed
                        cJSON *combination = cJSON_GetObjectItemCaseSensitive(item, "combination");
                        cJSON *speed = cJSON_GetObjectItemCaseSensitive(item, "speed");
                        s_automatic_data[s_action_id].mode[j]=combination->valueint;
                        s_automatic_data[s_action_id].val[j]=speed->valueint;

                        s_automatic_data[s_action_id].action_count++;

                       my_zlog_debug("combination:%d",s_automatic_data[s_action_id].mode[j]);
                       my_zlog_debug("speed:%d",s_automatic_data[s_action_id].val[j]);
                  
                    }
                }     
                
            }
        }
        
    }else if(s_switch_status == 0){
        memset(s_automatic_data[s_action_id].mode, 0, sizeof(s_automatic_data[s_action_id].mode));
        memset(s_automatic_data[s_action_id].val, 0, sizeof(s_automatic_data[s_action_id].val));
    }

    my_zlog_debug("action_count:%d",s_automatic_data[s_action_id].action_count);

    return;

}


/*
* @brief 开机需要进行配置自控相关的初始化
*/
int get_device_self_control_configuration_initialization(){
    static bool index=0;
    if(index == 0){
        send_self_contorl_date_mqtt();
        index = 1;
        return 0;
    }else return -1; 
}