import { defineStore } from 'pinia';
import { ref, reactive, computed } from 'vue';
import socket from "./socket";
import icpList from "../../utils/ipc";
import client from "./client";
import {ElMessage} from "element-plus";
import  configInfo  from '@/stores/modules/config';
const socketStore = socket();
const clientStore = client();


/**
 * 定义检查信息的Store
 * 包含设备连接状态检查、错误信息获取和重置检查等功能
 */
export const checkInfo = defineStore('checkInfo', () => {

    // 定义设备列表
    const devices = reactive({
        mcu: {
            status: 0,
            msg_type: "connect_mcu",
            msg: "未连接",
        },
        blue_tooth: {
            status: 0,
            msg_type: "connect_bluetooth",
            msg: "未连接",
        },
        cam_control: {
            status: 0,
            msg_type: "cam_control",
            msg: "未连接",
        },
/*        camera: {
            status: 0,
            msg_type: "camera",
            msg: "未连接",
        },*/
    });

    // 定义蓝牙扫描编号
    const blue_tooth_scan_NO = ref('')
    // 定义检查时间
    const checkTime = ref(0)
    // 定义检查设备状态的定时器
    let CKTimerInterval:any = null
    // 定义检查相机控制的定时器
    let CKCamControlInterval:any = null
    // 定义初始化mcu的类型
    let init_mcu_type = ref(true)
    // 定义检查状态
    const isCheckStatus = ref(true)
    /**
     * 设置检查状态
     * @param value 检查状态值
     */
    const set_isCheckStatus = (value)=>{
        isCheckStatus.value = value
        //开始监听相机软件连接状态
        if(!value){
            CKCamControlInterval =   setInterval(()=>{
                checkcamControl()
            },3000)
        }
    }

    //mcu 初始化
    const mcu = reactive({
        isInitSend:false,
        status:0,
    })
    // 计算完成进度
    const getProgress = computed(() => {
        let completed = 0;
        const total = Object.keys(devices).length -1; //去掉蓝牙
        for (const device of Object.values(devices)) {
            if (device.status === 2 && device.msg_type !== 'connect_bluetooth') completed++;
        }
        let value = parseFloat((completed / total * 100).toFixed(2));
        return value
    });

    // 获取错误信息
    const getErrorMsg = computed(() => {

        if(mcu.status === -1){
            clearInterval(CKTimerInterval)
            checkTime.value = 0
            mcu.isInitSend = false
            return '拍照机连接失败，请重新检查，可以尝试重新启动拍照机，插拔USB口，强制初始化等，请检查相机和支撑转盘是否待机休眠。如果确认未休眠，请检查各种连接线是否，正常连上。然后再重试一次，一直无法解决问题，请致电:15957854217，18805712182。';
        }
        for (const device of Object.values(devices)) {
            if (device.status === -1  && device.msg_type !== 'connect_bluetooth') {
                clearInterval(CKTimerInterval)
                checkTime.value = 0
                mcu.isInitSend = false
                return device.msg;
            }
        }
        return null;
    });

    const configInfoStore = configInfo();
    /**
     * 检查相机控制
     */
    const checkcamControl = async ()=>{


              clientStore.ipc.removeAllListeners(icpList.camera.connect);
              clientStore.ipc.send(icpList.camera.connect,configInfoStore.digiCamControlPath);

              clientStore.ipc.on(icpList.camera.connect, async (event, result) => {


                  console.log('icpList.camera.connect');
                  console.log(result);
                  if (result && checkTime.value > 0) {
                      if([-1,0,2].includes(result.status)){
                          devices.cam_control.status = result.status;
                          devices.cam_control.msg = result.msg;
                      }
                  }

                  if(!result  && checkTime.value > 0){
                      devices.cam_control.status = -1;
                      devices.cam_control.msg = '相机未连接，请链接相机。';
                  }
              });

    }


    /**
     * 检查相机
     */
    const checkcamera = ()=>{
        clientStore.ipc.removeAllListeners(icpList.camera.hascamera);
        clientStore.ipc.send(icpList.camera.hascamera);
        clientStore.ipc.on(icpList.camera.hascamera, (event, result) => {
            if (result && checkTime.value > 0) {
                if([-1,0,2].includes(result.status)){
                    devices.cam_control.status = result.status;
                    devices.cam_control.msg = result.msg;
                }
            }
            console.log(result);
        });

    }

    //第二次才算mcu正在失败
    const mcuErrorCount = ref(0);
    /**
     * 通用设备检查函数
     * @param deviceName 设备名称
     * @param messageType 消息类型
     */
    const checkDevice = async (deviceName: string, messageType: string) => {
        try {
            await socketStore.connectSocket();
            await socketStore.sendMessage({ type: messageType });
            clientStore.ipc.on(icpList.socket.message+'_'+deviceName, (event, result) => {

                console.log(result);
                if (result && checkTime.value > 0) {
                    if(deviceName === 'mcu'){
                        if(result.status === 2 ){
                            if(!mcu.isInitSend){
                                socketStore.sendMessage({
                                    type: 'init_mcu',
                                    data:{
                                        value:init_mcu_type.value
                                    }
                                });
                                mcu.isInitSend = true
                                mcu.status = 1
                            }
                            if(mcu.isInitSend && result.msg === '设备初始化完成'){
                                devices[deviceName].status = result.status;
                                devices[deviceName].msg = result.msg;
                                mcu.status = 2
                                init_mcu_type.value = false;
                            }
                            if(checkTime.value >= 60 &&   mcu.status !== 2){
                                mcu.status == -1;
                            }
                        }
                        if([-1,0].includes(result.status)){
                   /*         if(result.status === -1 ){
                                if(mcuErrorCount.value  === 0){
                                    mcuErrorCount.value++;
                                    return;
                                }else{
                                    mcuErrorCount.value = 0
                                }
                            }*/
                            devices[deviceName].status = result.status;
                            devices[deviceName].msg = result.msg;
                        }
                    }
                    if(deviceName === 'blue_tooth'){
                        if (result.code === 0 && result.data?.data && result.data._type === 0 && typeof(result.data.data) === 'string'){
                            blue_tooth_scan_NO.value = result.data.data
                       //     ElMessage.success('商品货号'+result.data.data+'获取成功，请根据左右脚按遥控器上的左右脚按键启动拍摄')
                        }
                        if([-1,0,2].includes(result.status)){
                            devices[deviceName].status = result.status;
                            devices[deviceName].msg = result.msg;
                        }
                    }

                }
            });
        } catch (error) {
            console.error(`Error checking ${deviceName}:`, error);
            devices[deviceName].status = -1;
            devices[deviceName].msg = `检查失败: ${error.message}`;
        }
    };

    /**
     * 执行所有设备检查
     */
    const checkAction = async () => {
        for (const deviceName of Object.keys(devices)) {
            switch (deviceName){
                case 'cam_control':
                    if(CKCamControlInterval) clearInterval(CKCamControlInterval)
                    await checkcamControl();
                    break;
                case 'camera':
                 //   await checkcamera();
                    break;
                 default:
                     await checkDevice(deviceName, devices[deviceName].msg_type);
            }
        }

    };

    /**
     * 重新检查所有设备
     */
    const reCheckAction = async () => {
        for (const device of Object.values(devices)) {
            device.status = 0;
            device.msg = "未连接";
        }
        mcu.status = -0;
        mcu.isInitSend = false;
        checkTime.value++;
        CKTimerInterval = setInterval(()=>{
            checkTime.value++;


            if(checkTime.value >= 60){
       /*         if( devices.blue_tooth &&  devices.blue_tooth.status === 0){
                    devices.blue_tooth.status = -1;
                    devices.blue_tooth.msg = '遥控器未连接。';
                }*/
                if( devices.mcu.status !== 2 || mcu.status !== 2 ){
                    devices.mcu.status = -1;
                    mcu.status = -1;
                    mcu.isInitSend = false;
                    devices.mcu.msg = '拍照机连接失败';
                }
                if( devices.cam_control.status !== 2 ){
                    devices.cam_control.status = -1;
                    devices.cam_control.msg = '拍照机连接失败';
                }
            }
        },1000)
        await checkAction();

    };

    /**
     * 设置蓝牙扫描编号
     * @param value 蓝牙扫描编号值
     */
    function set_blue_tooth_scan_NO(value){
        blue_tooth_scan_NO.value = value
    }


    return {
        getProgress,
        getErrorMsg,
        devices,
        mcu,
        isCheckStatus,
        set_isCheckStatus,
        blue_tooth_scan_NO,
        set_blue_tooth_scan_NO,
        checkAction,
        reCheckAction,
    };
});

export default checkInfo;
