<template>
  <div class="editrow_wrap" v-if="initStatus">
    <div class="config-type">参数值编辑：<el-checkbox v-model="isDefault">开启运动调试</el-checkbox></div>
    <el-form class="editForm" :model="editRowData" label-width="100px">
      <el-form-item label="动作名称">
        <el-input v-model="editRowData.action_name" style="width: 170px;"/>
      </el-form-item>
      <el-form-item label="是否拍照">
        <el-radio-group v-model="editRowData.take_picture">
          <el-radio :label="true">拍照</el-radio>
          <el-radio :label="false">不拍照</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="相机高度(mm)">
        <el-input v-model="editRowData.camera_height" @change="changeNum('camera_high_motor',0, 400)" :min="0" :max="400" :step="1"  style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大400</div>
      </el-form-item>
      <el-form-item label="相机倾角">
        <el-input v-model="editRowData.camera_angle" :min="-40" :max="40" :step=".1" @change="changeNum('camera_steering',-40, 40)" style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小-40，最大40</div>
      </el-form-item>
      <el-form-item label="转盘前后位置">
        <el-input v-model="editRowData.turntable_position" @change="changeNum('turntable_position_motor',0, 800)" :min="0" :max="800" :step="1"  style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大800</div>
      </el-form-item>
      <el-form-item label="转盘角度">
        <el-input v-model="editRowData.turntable_angle" @change="changeNum('turntable_steering',-720, 720)" :min="-720" :max="720" :step="1"  style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小-720，最大720</div>
      </el-form-item>
      <el-form-item label="鞋子翻转">
        <div class="flex-row">
          <el-radio-group v-model="editRowData.shoe_upturn">
            <el-radio :label="true">翻转</el-radio>
            <el-radio :label="false">不翻转</el-radio>
          </el-radio-group>
          <a class="cursor-pointer" @click="changeNum('overturn_steering')">测试翻转</a>
        </div>
      </el-form-item>
      <el-form-item label="LED灯光开光" @change="changeNum('laser_position')">
        <el-radio-group v-model="editRowData.led_switch">
          <el-radio :label="false">关闭</el-radio>
          <el-radio :label="true">开启</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="对焦次数">
        <el-input v-model="editRowData.number_focus" @change="changeNum('take_picture',0, 1)" :min="0" :max="1" :step="1"  style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大1</div>
      </el-form-item>
      <el-form-item label="拍照前延时（秒）">
        <el-input v-model="editRowData.pre_delay" :min="0" :max="99" :step="1" @change="changeNum('pre_delay',0, 99)" style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大99</div>
      </el-form-item>
      <el-form-item label="拍照后延时（秒）">
        <el-input v-model="editRowData.after_delay" :min="0" :max="99" :step="1" @change="changeNum('after_delay',0, 99)" style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大99</div>
      </el-form-item>
    </el-form>
    <div class="btn-row mar-top-20">
      <div class="normal-btn" @click="close" v-if="id">取消</div>
      <div class="primary-btn" @click="saveRow" v-if="id">{{ id ? '保存并关闭' : '保存' }}</div>
      </div>
  </div>

</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits , watch, onMounted } from 'vue'
import icpList from '@/utils/ipc';
import { digiCamControlWEB } from  '@/utils/appconfig'
import {ElMessage} from "element-plus";
import client from "@/stores/modules/client";
const clientStore = client();
import socket from "@/stores/modules/socket";
const socketStore = socket(); // WebSocket状态管理实例

// 定义 props
const props = defineProps({
  id:{
    type: Number||String,
    default: 0
  },
  addRowData:{
    type: Object,
    default: () => {
      return { }
    }
  }
})

const initStatus = ref(false)
const isDefault = ref(true); // 是否为默认配置
const editRowData = ref({}); // 当前编辑行的数据
onMounted(()=>{
  if(props.addRowData.mode_type){
    console.log(props.addRowData);
    initStatus.value = true
    editRowData.value = props.addRowData;
    return
  }
  let params = {
    id: props.id
  }
  if(!props.id) params = {
    mode_type:"执行左脚程序",
    action_name:"侧视图",
  }
  clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigDetail);
  clientStore.ipc.send(icpList.setting.getDeviceConfigDetail, params);
  clientStore.ipc.on(icpList.setting.getDeviceConfigDetail, (event, result) => {
    editRowData.value = result.data;
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigDetail);
    initStatus.value = true;
  });

})


/**
 * 修改设备配置数值。
 * @param {string} type - 配置类型
 */
async function changeNum(type, min, max) {
  let socketValue = {
    'camera_high_motor': 'camera_height',
    'turntable_steering': 'turntable_angle',
    'turntable_position_motor': 'turntable_position',
    'camera_steering': 'camera_angle',
    'overturn_steering': 'shoe_upturn',
    'laser_position': 'led_switch',
    'take_picture': 'number_focus',
  };
  if(min || max){
    if(editRowData.value[socketValue[type]] < min || editRowData.value[socketValue[type]] > max){
      if(editRowData.value[socketValue[type]] < min){
        editRowData.value[socketValue[type]] = min;
      }else{
        editRowData.value[socketValue[type]] = max;
      }
      ElMessage.error(`${type}值应在${min}到${max}之间`);
      return;
    }
  }
  if(type=='pre_delay' || type=='after_delay'){
    return
  }
  if (isDefault.value) {
    socketStore.sendMessage({
      type: 'control_mcu',
      data: {
        device_name: type,
        value: type == 'laser_position' ? (editRowData.value.led_switch ? "1" : "0") : editRowData.value[socketValue[type]]
      }
    });
  }
}


/*测试拍照*/
const captureLoading = ref(false)
const imageUrl = ref(digiCamControlWEB+'preview.jpg')
const imageUrlkey = ref(0)
function testShoesFlip(){
  if (clientStore.isClient) {

    socketStore.sendMessage({
      type: 'run_mcu_single',
      data: {
        camera_height: Number(editRowData.value.camera_height),
        camera_angle:  Number(editRowData.value.camera_angle),
        led_switch:editRowData.value.led_switch,
        id:0,
        mode_type:'执行'+ activeTab.value === 'left' ? '左脚' : '右脚'+'程序',
        turntable_position:Number(editRowData.value.turntable_position),
        action_name:editRowData.value.action_name || '测试',
        turntable_angle: Number(editRowData.value.turntable_angle),
        shoe_upturn: Number(editRowData.value.shoe_upturn),
        action_index:1,
        number_focus:0,
        take_picture:false,
        pre_delay:0,
        after_delay:0,
      }
    });
    captureLoading.value = true;


    clientStore.ipc.on(icpList.socket.message+'_run_mcu_single_finish', async (event, result) => {
      console.log('_run_mcu_single_finish')
      setTimeout(()=>{
        clientStore.ipc.removeAllListeners(icpList.camera.takePictures);
        clientStore.ipc.send(icpList.camera.takePictures,false);
        clientStore.ipc.on(icpList.camera.takePictures, async (event, result) => {
          setTimeout(()=>{
            imageUrlkey.value++;
            console.log('preview')
            preview(imageUrl.value+'?key='+imageUrlkey.value)
            captureLoading.value = false;
          },8000)
          clientStore.ipc.removeAllListeners(icpList.camera.takePictures);
        })
      },1000)


    })
  }
}

const emit = defineEmits([ 'confirm','onClose']);
const close = ()=>{
  console.log('onClose')
  emit('onClose')
}

/**
 * 保存当前编辑的配置。
 */
const saveRow = () => {
  clientStore.ipc.send(icpList.setting.saveDeviceConfig, {
    ...editRowData.value
  });
  clientStore.ipc.on(icpList.setting.saveDeviceConfig, (event, result) => {
    if (result.code == 0) {
      emit('confirm')
      ElMessage.success('保存成功');
      clientStore.ipc.removeAllListeners(icpList.setting.saveDeviceConfig);
    } else {
      ElMessage.error('保存失败');
    }
  });
};


</script>
<style>
</style>

<style lang="scss" scoped>
.editrow_wrap {
}
.config-type{
  font-size: 16px;
  color: #333333;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 10px;
  border-bottom: 1px solid #CCCCCC;
  .el-checkbox{
    margin-left: 10px;
  }
}
.editForm{
  padding: 10px;
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 0;
  .flex-row{
    display: flex;
    align-items: center;
    :deep(.el-radio){
      margin-right: 6px !important;
    }
    :deep(.el-radio__label){
      padding-left: 4px;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 0;
    .el-form-item__label {
      width: 120px !important;
      padding-right: 0 !important;
      background: #FBFCFF;
      border: 1px solid #EEEEEE;
      height: 41px;
      line-height: 41px;
      padding-left: 5px;
      text-align: left;
    }
    .el-form-item__content {
      width: 190px;
      position: relative;
      height: 41px;
      background: #FFFFFF;
      padding-left: 7px;
      border: 1px solid #EEEEEE;
      .el-input__wrapper {
        box-shadow: none;
      }
      .error-msg{
        display: none;
        position: absolute;
        top: 41px;
        top: 28px;
        left: 8px;
        z-index: 22;
        color: #dc2626;
        font-size: 12px;
      }
      &:hover{
        .error-msg{
          display: block;
        }
      }

      // 确保number类型输入框的上下箭头始终显示
      input[type="number"]::-webkit-inner-spin-button,
      input[type="number"]::-webkit-outer-spin-button {
        opacity: 1;
        height: 28px;
        position: absolute;
        top: 2px;
        right: 2px;
        cursor: pointer;
      }

      input[type="number"] {
        -moz-appearance: number-input; /* Firefox */
      }
    }
  }
}

.btn-row{
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}
.primary-btn{
  width: 100px;
  height: 30px;
  background: linear-gradient( 135deg, #2FB0FF 0%, #B863FB 100%);
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  cursor: pointer;
}
.normal-btn{
  width: 100px;
  height: 30px;
  background: #fff;
  border: 1px solid #CCCCCC;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  cursor: pointer;
}
</style>
