<template>
  <div class="editrow_wrap" v-if="initStatus">
    <div class="config-type">参数值编辑：
      <!-- <el-checkbox v-model="isDefault">开启运动调试</el-checkbox>-->
    </div>
    <span class="fs-12  mar-left-10 mar-top-10" v-if="id"  style="position: relative; top:5px">动作名称修改后，可能会导致自定义模板生成失效！</span>
    <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="isMultiCameraMode">
        <el-select v-model="editRowData.point_name" placeholder="请选择点位" style="width: 110px;" @focus="refreshPointList">
          <el-option v-for="point in availablePoints" :key="point" :label="'点位 ' + point" :value="point"/>
        </el-select>
        <el-button size="small" plain style="margin-left: 8px;" @click="onRefreshPointList" v-log="{ describe: { action: '点击刷新点位列表' } }">刷新</el-button>
      </el-form-item>

      <!-- 多相机模式 - 仅拍照模式 -->
<!--      <el-form-item label="是否移动设备" v-if="isMultiCameraMode">
        <div class="flex-row">
          <el-radio-group v-model="editRowData.is_move_device">
            <el-radio :label="0">不移动</el-radio>
            <el-radio :label="1">移动</el-radio>
          </el-radio-group>
        </div>
      </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)" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">
        <el-input v-model="editRowData.camera_height" @change="changeNum('camera_high_motor',0, maxCameraHeight)" :min="0" :max="maxCameraHeight" :step="1"  style="width: 170px;" type="number" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
        </el-input>
        <div class="error-msg">最小0，最大{{ maxCameraHeight }}</div>
      </el-form-item>
      <el-form-item label="相机倾角" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">
        <el-input v-model="editRowData.camera_angle" :min="-5" :max="30" :step=".1" @change="changeNum('camera_steering',-5, 30)" style="width: 170px;" type="number" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
        </el-input>
        <div class="error-msg">最小-5，最大30</div>
      </el-form-item>
      <!-- 相机焦段距离 - 仅当设备支持时显示 -->
      <el-form-item label="焦段距离(mm)" v-if="hasCameraFocal" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">

        <template #label>

          焦段距离(mm)
          <el-tooltip class="box-item" effect="dark" placement="left-end">
            <template #content>
              请注意，焦段距离如果过大，可能会导致设备滑牙，需要重新调整设备以及初始化;
            </template>
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </template>
        <template #default>

          <el-input v-model="editRowData.camera_focal_distance" @change="changeNum('camera_focal_distance', 0, maxFocalDistance)" :min="0" :max="maxFocalDistance" :step="1" style="width: 100px;" type="number" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
          </el-input>
          <el-button size="small" plain style="margin-left: 8px;" @click="onRecheckFocal" v-log="{ describe: { action: '点击焦段距离初始化' } }">初始化</el-button>
          <div class="error-msg">最小0，最大{{ maxFocalDistance }}，</div>
        </template>
      </el-form-item>
      <el-form-item label="转盘前后位置" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">
        <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" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
        </el-input>
        <div class="error-msg">最小0，最大800</div>
      </el-form-item>
      <el-form-item label="转盘角度" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">
        <el-input v-model="editRowData.turntable_angle" @change="changeNum('turntable_steering',-720, 720)" :min="-720" :max="720" :step="1"  style="width: 170px;" type="number" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
        </el-input>
        <div class="error-msg">最小-720，最大720</div>
      </el-form-item>
      <el-form-item label="鞋子翻转" :class="{'is-disabled': isMultiCameraMode && editRowData.is_move_device === 0}">
        <div class="flex-row">
          <el-radio-group v-model="editRowData.shoe_upturn" :disabled="isMultiCameraMode && editRowData.is_move_device === 0">
            <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: '点击测试翻转' } }" v-if="!isMultiCameraMode || editRowData.is_move_device !== 0">测试翻转</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="refreshData" v-if="id" v-log="{ describe: { action: '点击刷新配置' } }">刷新</div>
      <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, computed } from 'vue'
import icpList from '@/utils/ipc';
import { digiCamControlWEB } from  '@/utils/appconfig'
import {ElMessage} from "element-plus";
import  { getDeviceConfigDetail,getDeviceConfigDetailQuery,saveDeviceConfig, getAllUserConfigs } from '@/apis/setting'
import client from "@/stores/modules/client";
import useUserInfo from '@/stores/modules/user';

const clientStore = client();
import socket from "@/stores/modules/socket";
const socketStore = socket(); // WebSocket状态管理实例
import checkInfo from '@/stores/modules/check';

const checkInfoStore = checkInfo();
const userInfoStore = useUserInfo();

// 是否为多相机模式
const isMultiCameraMode = computed(() => userInfoStore.isMultiCameraMode)

// 已配置相机的点位列表
const availablePoints = ref<string[]>(['A'])

// 刷新点位列表（从 getAllUserConfigs API 获取已绑定相机的点位）
// 同时会校验当前选中的点位：若该点位已不再可用，自动回退到第一个可用点位
const refreshPointList = async () => {
  try {
    const result = await getAllUserConfigs({})
    if (result.code == 0 && result.data?.configs?.camera_configs?.iso_config) {
      const isoConfig = result.data.configs.camera_configs.iso_config
      availablePoints.value = Object.keys(isoConfig).filter(key => {
        const config = isoConfig[key]
        return config && config.CameraKey && config.CameraKey !== ''
      })
    }
  } catch (err) {
    console.error('获取点位配置失败:', err)
  }
  if (availablePoints.value.length === 0) {
    availablePoints.value = ['A']
  }

  // 若当前选中的点位已经不在可用列表里（例如在设置页修改相机配置后），
  // 自动回退到第一个可用点位，避免下拉框停留在一个无效值上
  if (
    isMultiCameraMode.value &&
    initStatus.value &&
    editRowData.value.point_name &&
    !availablePoints.value.includes(editRowData.value.point_name)
  ) {
    editRowData.value.point_name = availablePoints.value[0]
    ElMessage.warning(`原点位相机不可用，已自动切换到点位 ${availablePoints.value[0]}`)
  }
}

/**
 * 点击「刷新点位」按钮：重新拉取点位列表，并强制通知父组件按当前选中的点位刷新预览。
 * 解决：在设置页修改相机配置后，因 el-select 单选项不展开 / @focus 不触发，
 *       导致 availablePoints 无法更新、当前点位可能已无效。
 */
const onRefreshPointList = async () => {
  const previousPoint = editRowData.value.point_name
  await refreshPointList()
  // 即便点位没变也 emit 一次，确保父组件预览按最新点位重新打开
  // （watch 监听 point_name 在新旧值相同时不会触发，这里手动补一次）
  if (editRowData.value.point_name) {
    emit('onPointChange', editRowData.value.point_name)
  } else if (previousPoint !== editRowData.value.point_name && availablePoints.value[0]) {
    emit('onPointChange', availablePoints.value[0])
  }
}



const onRecheckFocal = async () => {
  socketStore.sendMessage({
    type: 'to_recheck_focal',
    data: 'to_recheck_focal'
  });

}

// 定义 props
const props = defineProps({
  id:{
    type: Number||String,
    default: 0
  },
  addRowData:{
    type: Object,
    default: () => {
      return { }
    }
  },
  // 是否禁用点位和拍照模式编辑（用于拍摄物体镜头矫正等场景）
  disablePointConfig: {
    type: Boolean,
    default: false
  }
})

const initStatus = ref(false)
const isDefault = ref(true); // 是否为默认配置
const editRowData = ref({}); // 当前编辑行的数据
const maxCameraHeight = ref(350); // 相机高度最大值，默认350，通过get_device_info从后端获取
const hasCameraFocal = ref(false); // 是否支持相机焦段距离
const maxFocalDistance = ref(8000); // 相机焦段距离最大值，默认8000，通过get_device_info从后端获取

// 监听点位变化，切换预览
watch(() => editRowData.value.point_name, (newPoint, oldPoint) => {
  if (initStatus.value && newPoint && newPoint !== oldPoint) {
    emit('onPointChange', newPoint)
  }
})

/**
 * 从后端获取设备信息，更新相机高度最大值等参数。
 */
async function fetchDeviceInfo() {
  if (!clientStore.isClient) return;
  socketStore.sendMessage({
    type: 'get_device_info',
    data: 'get_device_info'
  });

  clientStore.ipc.on(icpList.socket.message + '_get_device_info', (event, result) => {
    console.log('_get_device_info', result);
    if (result.code === 0 && result.data?.camera_height) {
      maxCameraHeight.value = result.data.camera_height;
    }
    // 解析相机焦段距离信息
    if (result.code === 0 && result.data?.camera_focal_data) {
      const focalData = result.data.camera_focal_data;
      hasCameraFocal.value = focalData.is_camera_has_focal === true;
      if (focalData.camera_focal_distance) {
        maxFocalDistance.value = Number(focalData.camera_focal_distance);
      }
    }
    clientStore.ipc.removeAllListeners(icpList.socket.message + '_get_device_info');
  });
}

onMounted(async ()=>{
  console.log('editrow')
  // 获取设备信息（相机高度最大值等）
  fetchDeviceInfo();
  // 刷新点位列表
  await refreshPointList()
  if(props.addRowData.mode_type){
    console.log(props.addRowData);
    initStatus.value = true
    editRowData.value = props.addRowData;
    // 多相机模式默认值
    if (isMultiCameraMode.value) {
      // 验证点位是否有效，无效则使用第一个可用点位
      if (!availablePoints.value.includes(editRowData.value.point_name)) {
        editRowData.value.point_name = availablePoints.value[0] || 'A'
      }
      editRowData.value.is_move_device = editRowData.value.is_move_device ?? 1
    }
    testShoesFlip()
    emit('onReady', editRowData.value.point_name || 'A')
    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;
    // 新增时设置相机焦段距离默认值
    if (!props.id && hasCameraFocal.value) {
      editRowData.value.camera_focal_distance = 0;
    }
    // 多相机模式默认值处理
    if (isMultiCameraMode.value) {
      // 验证点位是否有效，无效则使用第一个可用点位
      if (!availablePoints.value.includes(editRowData.value.point_name)) {
        editRowData.value.point_name = availablePoints.value[0] || 'A'
      }
      editRowData.value.is_move_device = editRowData.value.is_move_device ?? 1
    }
    initStatus.value = true;
    testShoesFlip()
    emit('onReady', editRowData.value.point_name || 'A')
  }

})


/**
 * 修改设备配置数值。
 * @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',
    'camera_focal_distance': 'camera_focal_distance',
  };
  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) {


    console.log('testShoesFlip')
    console.log({
      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,
      // 相机焦段距离（可选字段）
      camera_focal_distance: hasCameraFocal.value ? Number(editRowData.value.camera_focal_distance || 0) : undefined,
      // 多相机模式参数
      point_name: isMultiCameraMode.value ? (editRowData.value.point_name || 'A') : undefined,
      is_move_device: isMultiCameraMode.value ? editRowData.value.is_move_device : undefined,
    })
    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,
        // 相机焦段距离（可选字段）
        camera_focal_distance:Number(editRowData.value.camera_focal_distance || 0),
        // 多相机模式参数
        point_name: isMultiCameraMode.value ? (editRowData.value.point_name || 'A') : undefined,
        is_move_device: isMultiCameraMode.value ? editRowData.value.is_move_device : undefined,
      }
    });
   // 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','onReady','onPointChange']);
const close = ()=>{
  console.log('onClose')
  emit('onClose')
}

/**
 * 刷新当前编辑的配置数据。
 */
const refreshData = async () => {
  if (captureLoading.value) {
    return
  }
  if (!props.id) {
    return
  }

  captureLoading.value = true
  try {
    const result = await getDeviceConfigDetail({ id: props.id })
    if (result.code == 0 && result.data) {
      editRowData.value = result.data
      // 多相机模式默认值处理
      if (isMultiCameraMode.value) {
        if (!availablePoints.value.includes(editRowData.value.point_name)) {
          editRowData.value.point_name = availablePoints.value[0] || 'A'
        }
        editRowData.value.is_move_device = editRowData.value.is_move_device ?? 1
      }
      ElMessage.success('刷新成功')
    } else {
      ElMessage.error('刷新失败')
    }
  } catch (err) {
    console.error('刷新配置失败:', err)
    ElMessage.error('刷新失败')
  } finally {
    captureLoading.value = false
  }
}

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

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

  // 多相机模式校验
  if (isMultiCameraMode.value) {
    if (!editRowData.value.point_name) {
      ElMessage.error('请选择拍摄点位')
      return;
    }
  }

  captureLoading.value = true

  // 构建保存数据，包含新增字段
  const saveData = {
    ...editRowData.value,
  }

  // 多相机模式添加点位信息
  if (isMultiCameraMode.value) {
    saveData.point_name = editRowData.value.point_name
    saveData.is_move_device = editRowData.value.is_move_device
  }

  const result = await  saveDeviceConfig(saveData)
  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;
}

.mode-hint {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}
</style>
