<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"  v-loading="captureLoading" label-width="100px" >
      <el-form-item label="动作名称">
        <el-input v-model="editRowData.action_name" :disabled="editRowData.is_system" style="width: 170px;"/>
      </el-form-item>
      <el-form-item label="是否拍照" v-if="!editRowData.is_system">
        <el-radio-group v-model="editRowData.take_picture">
          <el-radio :label="1">拍照</el-radio>
          <el-radio :label="0">不拍照</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, 350)" :min="0" :max="350" :step="1"  style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小0，最大350</div>
      </el-form-item>
      <el-form-item label="相机倾角">
        <el-input v-model="editRowData.camera_angle" :min="-5" :max="30" :step=".1" @change="changeNum('camera_steering',-40, 40)" style="width: 170px;" type="number">
        </el-input>
        <div class="error-msg">最小-5，最大30</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="1">翻转</el-radio>
            <el-radio :label="0">不翻转</el-radio>
          </el-radio-group>
          <a class="cursor-pointer" @click="changeNum('overturn_steering')" v-log="{ describe: { action: '点击测试翻转' } }">测试翻转</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="0">关闭</el-radio>
          <el-radio :label="1">开启</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" v-log="{ describe: { action: '点击关闭编辑行' } }">取消</div>
      <div class="normal-btn"  v-loading="captureLoading"  v-if="!id && editRowData.is_system" @click="testShoesFlip" v-log="{ describe: { action: '点击运行测试拍照' } }">运行</div>
      <div class="primary-btn"  v-loading="captureLoading" @click="saveRow" v-log="{ describe: { action: '点击保存设备配置' } }">{{ 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  { getDeviceConfigDetail,getDeviceConfigDetailQuery,saveDeviceConfig } from '@/apis/setting'
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(async ()=>{
  console.log('editrow')
  if(props.addRowData.mode_type){
    console.log(props.addRowData);
    initStatus.value = true
    editRowData.value = props.addRowData;
    testShoesFlip()
    return
  }
  let fun = getDeviceConfigDetail;
  let params = {
    id: props.id
  }
  if(!props.id){
    params = {
      mode_type:"执行左脚程序",
      action_name:"侧视",
    }
    fun =  getDeviceConfigDetailQuery
  }



  const result = await fun(params)

  if(result.code == 0 && result.data){
    editRowData.value = result.data;
    initStatus.value = true;
    testShoesFlip()
  }

})


/**
 * 修改设备配置数值。
 * @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)
function testShoesFlip(){
  if (captureLoading.value) {
    return
  }
  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:editRowData.value.mode_type,
        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', async (event, result) => {

      captureLoading.value = false;

      emit('onRunMcuSingle')

    })
  }
}

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

/**
 * 保存当前编辑的配置。
 */
const saveRow = async () => {
  if (captureLoading.value) {
    return
  }

  if(!editRowData.value.action_name){
    ElMessage.error('请输入动作名称')
    return;
  }

  captureLoading.value = true
  const result = await  saveDeviceConfig({
    ...editRowData.value
  })
  captureLoading.value = false
  if (result.code == 0) {
    emit('confirm')
    ElMessage.success('保存成功');
    clientStore.ipc.removeAllListeners(icpList.setting.saveDeviceConfig);
  }



};

// 暴露给父组件
defineExpose({
  editRowData, // 父组件可通过 editData.value.editRowData 访问
});
</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>
