<template>
  <headerBar
    title="设置"
  />
  <div class="container">
    <nav class="settings-nav">
      <div class="nav-item" :class="{'active': activeIndex === 0}" @click="activeIndex = 0">
        <img src="@/assets/images/setting/icon1.png" class="nav-icon" v-if="activeIndex !== 0"/>
        <img src="@/assets/images/setting/icon1a.png" class="nav-icon" v-else/>
        <span>基础配置</span>
      </div>
      <div class="nav-item" :class="{'active': activeIndex === 1}" @click="activeIndex = 1">
        <img src="@/assets/images/setting/icon2.png" class="nav-icon" v-if="activeIndex !== 1"/>
        <img src="@/assets/images/setting/icon2a.png" class="nav-icon" v-else/>
        <span>拍照设置</span>
      </div>
      <div class="nav-item" :class="{'active': activeIndex === 2}" @click="activeIndex = 2">
        <img src="@/assets/images/setting/icon3.png" class="nav-icon" v-if="activeIndex !== 2"/>
        <img src="@/assets/images/setting/icon3a.png" class="nav-icon" v-else/>
        <span>其他设置</span>
      </div>
<!--      <div class="nav-item" :class="{'active': activeIndex === 3}" @click="activeIndex = 3">
        <img src="@/assets/images/setting/icon4.png" class="nav-icon" v-if="activeIndex !== 3"/>
        <img src="@/assets/images/setting/icon4a.png" class="nav-icon" v-else/>
        <span>遥控器设置</span>
      </div>-->
      <div class="nav-item" :class="{'active': activeIndex === 4}" @click="activeIndex = 4">
        <img src="@/assets/images/setting/icon4.png" class="nav-icon" v-if="activeIndex !== 4"/>
        <img src="@/assets/images/setting/icon4a.png" class="nav-icon" v-else/>
        <span>左右脚程序设置</span>
      </div>
    </nav>

    <div class="form-container">
<!--        <div class="captureBox" v-if="activeIndex === 0">
            <div class="form-item">
                <label>canpture_one图片输出文件夹：</label>
                <div class="input-group">
                  <el-input style="width: 430px;" type="textarea" :rows="2" v-model="formData.captureOneFolder" readonly></el-input>
                  <div class="select-btn" @click="selectFolder">
                   <img src="@/assets/images/setting/folder.png" /> 选择文件夹
                  </div>
                </div>
            </div>
&lt;!&ndash;            <p class="error-text">capture one的导出拍照图像自动和智能拍的待处理图像自不一致，请重新选择</p>&ndash;&gt;
          </div>-->
      <!--基础配置-->
          <div class="selectBox" v-if="activeIndex === 0">
                <div class="form-item">
                    <label>主图尺寸：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.basic_configs.main_image_size" placeholder="请选择">
                      <el-option v-for="item in mainImageSizeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>图片输出格式：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.basic_configs.image_out_format" placeholder="请选择">
                      <el-option v-for="item in imageFormatList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>图片锐化：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.basic_configs.image_sharpening" placeholder="请选择">
                      <el-option v-for="item in imageSharpeningList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
        </div>
      <!--基础配置-->
      <!--拍照设置-->
          <div class="selectBox" style="padding-top: 0px" v-if="activeIndex === 1">
                <div class="form-item">
                    <label>重复拍摄警告：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.take_photo_configs.repart_take_photo_warning" placeholder="请选择">
                      <el-option v-for="item in repeatWarningList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>单次张数警告：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.take_photo_configs.single_photo_warning" placeholder="请选择">
                      <el-option v-for="item in singleWarningList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>累计拍照警告：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.take_photo_configs.total_photo_warning" placeholder="请选择">
                      <el-option v-for="item in totalWarningList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
<!--                <div class="form-item">
                    <label>对焦时间：</label>
                    <div class="select-wrapper">
                      <el-input v-model="formData.focusTime" placeholder="请输入">
                        <template #append>秒</template>
                      </el-input>
                    </div>
                </div>-->
                <div class="form-item">
                    <label>拍照停留：</label>
                    <div class="select-wrapper">
                      <el-input v-model="formData.take_photo_configs.camera_delay" placeholder="请输入">
                        <template #append>秒</template>
                      </el-input>
                    </div>
                </div>
        </div>
      <!--拍照配置-->
      <!--其他设置-->
          <div class="selectBox" style="padding-top: 0px" v-if="activeIndex === 2">
                <div class="form-item">
                    <label>产品类型：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.other_configs.product_type" placeholder="请选择">
                      <el-option v-for="item in productTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>默认抠图模式：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.other_configs.cutout_mode" placeholder="请选择">
                      <el-option v-for="item in defaultCutoutModeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>设备运动速度：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.other_configs.device_speed" placeholder="请选择">
                      <el-option v-for="item in deviceSpeedList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>运行模式：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.other_configs.running_mode" placeholder="请选择">
                      <el-option v-for="item in runModeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
          </div>
      <!--其他设置-->
          <div class="selectBox" style="padding-top: 0px" v-if="activeIndex === 3">
                <div class="form-item">
                    <label>接收器：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.receiver" placeholder="请选择">
                      <el-option v-for="item in receiverList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>左：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.left" placeholder="请选择">
                      <el-option v-for="item in leftList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>右：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.right" placeholder="请选择">
                      <el-option v-for="item in rightList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>上：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.up" placeholder="请选择">
                      <el-option v-for="item in upList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
                <div class="form-item">
                    <label>下：</label>
                    <div class="select-wrapper">
                    <el-select v-model="formData.down" placeholder="请选择">
                      <el-option v-for="item in downList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    </div>
                </div>
          </div>
          <div class="selectBox" style="padding-top: 0px;padding-left: 0;" v-if="activeIndex === 4">
            <el-tabs v-model="activeTab" type="card">
              <el-tab-pane label="执行左脚程序" name="left">
              </el-tab-pane>
              <el-tab-pane label="执行右脚程序" name="right"></el-tab-pane>
            </el-tabs>
            <div class="form-table">
              <div class="btnBox">
                <div class="primary-btn" @click="addRow">新增一行</div>
                <div class="normal-btn" @click="resetConfig">重新初始化</div>
              </div>
              <el-table height="200px" :data="activeTab === 'left' ? lefttableData : righttableData" style="width: 100%" border>
                <el-table-column prop="id" label="id" />
                <el-table-column prop="action_name" label="步骤" />
                <el-table-column prop="take_picture" label="是否拍照" width="200px">
                  <template #default="scope">
                    <el-radio-group v-model="scope.row.take_picture">
                      <el-radio :label="true">拍照</el-radio>
                      <el-radio :label="false">不拍照</el-radio>
                    </el-radio-group>
                  </template>
                </el-table-column>
                <el-table-column prop="action_index" label="排序" >
                  <template #default="{row, $index}">
                    <a v-if="$index !== 0" class="cursor-pointer" @click="upRow(row)">上移</a>
                    <a class="mar-left-10 cursor-pointer" v-if="$index !== activeTab === 'left' ? lefttableData.length - 1 : righttableData.length - 1" @click="downRow(row)">下移</a>
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="操作" >
                  <template #default="{row, $index}">
                    <a class="mar-right-10 cursor-pointer" @click="editRow(row, $index)">编辑</a>
                    <a class="cursor-pointer" @click="deleteRow(row, $index)">删除</a>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
    </div>
      <div class="text-center mt-8">
        <button class="bg-gradient-to-r from-primary" @click="saveSetting(activeIndex)" v-if="activeIndex !== 4">
          保存
        </button>
      </div>
      <el-dialog custom-class="editDialog" v-model="dialogVisible" :title="editTitle" width="660px">
        <div class="config-type">配置类型：执行{{ activeTab === 'left' ? '左脚' : '右脚' }}程序 <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="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-item label="是否等待">
            <el-radio-group v-model="editRowData.wait_user">
              <el-radio :label="false">否</el-radio>
              <el-radio :label="true">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="待用户确认照片">
            <el-radio-group v-model="editRowData.confirm_photo">
              <el-radio :label="false">否</el-radio>
              <el-radio :label="true">是</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
        <template #footer>
          <div class="btn-row">
            <div class="normal-btn" @click="dialogVisible = false">关闭</div>
            <!-- <div class="primary-btn" @click="testShoesFlip">拍照测试</div> -->
            <div class="primary-btn" @click="saveRow">保存并关闭</div>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
/**
 * Vue组件逻辑部分，包含与设备配置相关的功能。
 * 主要功能包括：表单数据管理、设备配置列表获取、新增/编辑/删除步骤、保存配置等。
 */

// 引入Vue相关功能和第三方库
import { ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { onMounted, watch } from 'vue';
import socket from "@/stores/modules/socket";
import headerBar from '@/components/header-bar/index.vue';
import client from "@/stores/modules/client";
import icpList from '@/utils/ipc';
const clientStore = client();
import { ElMessage, ElMessageBox } from 'element-plus';

// 路由和状态管理初始化
const route = useRoute();
const router = useRouter();

// 定义响应式变量
const folderPath = ref(''); // 文件夹路径
const activeIndex = ref(0); // 当前激活的索引
const socketStore = socket(); // WebSocket状态管理实例

/**
 * 表单数据对象，用于存储设备配置信息。
 */
const formData = reactive({
  //基础配置
  basic_configs:{
    "main_image_size": "",//主图尺寸
    "image_out_format": "",//图片输出格式
    "image_sharpening": "" //图片锐化
  },
  //拍照配置
  take_photo_configs:{
    "repart_take_photo_warning": false,//重复拍摄警告
    "single_photo_warning": "",//单次张数警告
    "total_photo_warning": "",//累计拍照警告
    "camera_delay": ""//拍照停留
  },
  other_configs:{
    "product_type": "",//产品类型
    "cutout_mode": "",//默认抠图模式
    "device_speed": "",//设备运动速度
    "running_mode": "" //运行模式
  },
  captureOneFolder: '', // Capture One文件夹路径
  mainImageSize: '', // 主图尺寸
  imageFormat: '', // 图片格式
  imageSharpening: '', // 图片锐化
  repeatWarning: '', // 重复警告
  singleWarning: '', // 单次警告
  totalWarning: '', // 总警告
  focusTime: '', // 对焦时间
  photoTime: '', // 拍照时间
  productType: '', // 产品类型
  defaultCutoutMode: '', // 默认抠图模式
  deviceSpeed: '', // 设备速度
  runMode: '', // 运行模式
  receiver: '', // 接收器类型
  left: '', // 左脚配置
  right: '', // 右脚配置
  up: '', // 上移配置
  down: '', // 下移配置
});

// 配置选项列表
const mainImageSizeList = ref([
  { label: '800', value: '800' },
  { label: '1024', value: '1024' },
  { label: '1200', value: '1200' },
  { label: '1600', value: '1600' },
]);
const imageFormatList = ref([
  { label: 'jpg', value: 'jpg' },
  { label: 'png', value: 'png' },
  { label: 'jpeg', value: 'jpeg' },
]);
const imageSharpeningList = ref([
  { label: '0', value: '0' },
  { label: '1', value: '1' },
  { label: '2', value: '2' },
  { label: '3', value: '3' },
]);
const repeatWarningList = ref([
  { label: '关闭', value: false },
  { label: '开启', value: true },
]);
const singleWarningList = ref([
  { label: '11', value: '11' },
  { label: '12', value: '12' },
  { label: '13', value: '13' },
]);
const totalWarningList = ref([
  { label: '1.0', value: '1.0' },
  { label: '1.5', value: '1.5' },
  { label: '2.0', value: '2.0' },
]);
const productTypeList = ref([
  { label: '鞋类', value: '鞋类' },
  { label: '服装', value: '服装' },
  { label: '箱包', value: '箱包' },
]);
const defaultCutoutModeList = ref([
  { label: '普通抠图', value: '普通抠图' },
  { label: '智能抠图', value: '智能抠图' },
  { label: '手动抠图', value: '手动抠图' },
]);
const deviceSpeedList = ref([
  { label: '一档', value: '1' },
  { label: '二档', value: '2' },
  { label: '三档', value: '3' },
]);
const runModeList = ref([
  { label: '普通抠图', value: '普通抠图' },
  { label: '精细化抠图', value: '精细化抠图' }
]);
const receiverList = ref([
  { label: '蓝牙', value: '1' },
  { label: '2.4G', value: '2' },
  { label: '5.8G', value: '3' },
]);
const leftList = ref([
  { label: '左脚', value: '1' },
  { label: '右脚', value: '2' },
  { label: '左右脚', value: '3' },
]);
const rightList = ref([
  { label: '左脚', value: '1' },
  { label: '右脚', value: '2' },
  { label: '左右脚', value: '3' },
]);
const upList = ref([
  { label: '上移', value: '1' },
  { label: '下移', value: '2' },
  { label: '左右移', value: '3' },
]);
const downList = ref([
  { label: '上移', value: '1' },
  { label: '下移', value: '2' },
  { label: '左右移', value: '3' },
]);

// 表格数据和对话框状态
const lefttableData = ref([]); // 左脚配置表格数据
const righttableData = ref([]); // 右脚配置表格数据
const dialogVisible = ref(false); // 编辑对话框可见状态
const editTitle = ref(''); // 编辑对话框标题
const editRowData = ref({}); // 当前编辑行的数据
const activeTab = ref('left'); // 当前激活的标签页
const editIndex = ref(0); // 当前编辑行的索引
const isDefault = ref(false); // 是否为默认配置

const indexKey  ={
  0:"basic_configs",
  1:"take_photo_configs",
  2:"other_configs",
}

/**
 * 监听路由参数变化，更新activeIndex和activeTab。
 */
watch(() => route.query.type, async (newType,oldType) => {

  if(['0','1','2'].includes(oldType)){
    await  saveSetting(oldType)
  }
  const typeValue = parseInt(newType) || 0;
  switch (typeValue) {
      case 4:
        activeTab.value = 'left';
        clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
        clientStore.ipc.send(icpList.setting.getDeviceConfigList, {
          mode_type: '执行左脚程序'
        });
        clientStore.ipc.on(icpList.setting.getDeviceConfigList, (event, result) => {
          if (result?.data?.list) {
            lefttableData.value = result.data.list;
          }
          clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
        });
        break;
      default:
        clientStore.ipc.removeAllListeners(icpList.setting.getSysConfig);
        clientStore.ipc.send(icpList.setting.getSysConfig,{
          key: indexKey[typeValue]
        });
        clientStore.ipc.on(icpList.setting.getSysConfig, (event, result) => {
          if(result.code == 0 && result.data){
            formData[indexKey[typeValue]] = result.data
          }
          console.log('icpList.setting.getSysConfig')
          console.log(result)
          clientStore.ipc.removeAllListeners(icpList.setting.getSysConfig);
        });
        break;
    }
}, { immediate: true });

/**
 * 监听activeTab变化，获取对应标签页的设备配置列表。
 */
watch(() => activeTab.value, (newTab) => {
  if (newTab === 'left') {
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
    clientStore.ipc.send(icpList.setting.getDeviceConfigList, {
      mode_type: '执行左脚程序'
    });
    clientStore.ipc.on(icpList.setting.getDeviceConfigList, (event, result) => {
      if (result?.data?.list) {
        lefttableData.value = result.data.list;
      }
      clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
    });
  } else {
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
    clientStore.ipc.send(icpList.setting.getDeviceConfigList, {
      mode_type: '执行右脚程序'
    });
    clientStore.ipc.on(icpList.setting.getDeviceConfigList, (event, result) => {
      if (result?.data?.list) {
        righttableData.value = result.data.list;
      }
      clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
    });
  }
});

/**
 * 监听activeIndex变化，更新URL中的查询参数。
 */
watch(() => activeIndex.value, (newIndex) => {
  router.push({
    query: {
      ...route.query,
      type: newIndex.toString()
    }
  });
});

/**
 * 组件挂载时初始化activeIndex。
 */
onMounted(() => {
  if (route.query.type) {
    const typeValue = parseInt(route.query.type);
    if (!isNaN(typeValue) && typeValue >= 0 && typeValue <= 3) {
      activeIndex.value = typeValue;
    }
  }


});

/**
 * 打开文件夹选择对话框并更新表单数据。
 */
const selectFolder = () => {
  clientStore.ipc.removeAllListeners(icpList.utils.openDirectory);
  clientStore.ipc.send(icpList.utils.openDirectory);
  clientStore.ipc.on(icpList.utils.openDirectory, async (event, result) => {
    formData.captureOneFolder = result;
    clientStore.ipc.removeAllListeners(icpList.utils.openDirectory);
  });
};

/**
 * 保存当前表单配置。
 */
const saveSetting = async (index) => {

  await new Promise((resolve, reject) => {

    clientStore.ipc.removeAllListeners(icpList.setting.updateSysConfigs);
    clientStore.ipc.send(icpList.setting.updateSysConfigs,{
      key: indexKey[index],
      value:JSON.stringify({
        ...formData[indexKey[index]]
      })
    });
    clientStore.ipc.on(icpList.setting.updateSysConfigs, async (event, result) => {
      clientStore.ipc.removeAllListeners(icpList.setting.updateSysConfigs);
      if(result.code === 0 && result.msg){
        resolve(result)
      }

    });
  });


};

/**
 * 新增一行配置。
 */
const addRow = () => {
  if (activeTab.value === 'left') {
    editRowData.value = {
      mode_type: '执行左脚程序',
      action_name: '',
      take_picture: false,
      camera_height: 0,
      camera_angle: 0,
      turntable_position: 0,
      turntable_angle: 0,
      shoe_upturn: false,
      led_switch: false,
      number_focus: 0,
      pre_delay: 0,
      after_delay: 0,
    };
    dialogVisible.value = true;
    editTitle.value = '新增步骤';
  } else {
    editRowData.value = {
      mode_type: '执行右脚程序',
      action_name: '',
      take_picture: false,
      camera_height: 0,
      camera_angle: 0,
      turntable_position: 0,
      turntable_angle: 0,
      shoe_upturn: false,
      led_switch: false,
      number_focus: 0,
      pre_delay: 0,
      after_delay: 0,
    };
    dialogVisible.value = true;
    editTitle.value = '新增步骤';
  }
};

/**
 * 获取设备配置列表。
 */
const getList = () => {
  clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
  clientStore.ipc.send(icpList.setting.getDeviceConfigList, {
    mode_type: activeTab.value === 'left' ? '执行左脚程序' : '执行右脚程序'
  });
  clientStore.ipc.on(icpList.setting.getDeviceConfigList, (event, result) => {
    if (result.code == 0) {
      if (activeTab.value === 'left') {
        lefttableData.value = result.data.list;
      } else {
        righttableData.value = result.data.list;
      }
    } else {
      ElMessage.error('获取列表失败');
    }
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
  });
};

/**
 * 编辑指定行的配置。
 * @param {Object} row - 当前行的数据
 * @param {number} index - 当前行的索引
 */
const editRow = (row, index) => {
  dialogVisible.value = true;
  editTitle.value = row.action_name + '编辑';
  clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigDetail);
  clientStore.ipc.send(icpList.setting.getDeviceConfigDetail, {
    id: row.id
  });
  clientStore.ipc.on(icpList.setting.getDeviceConfigDetail, (event, result) => {
    editRowData.value = result.data;
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigDetail);
  });
  editIndex.value = index;
};

/**
 * 删除指定行的配置。
 * @param {Object} row - 当前行的数据
 * @param {number} index - 当前行的索引
 */
const deleteRow = (row, index) => {
  ElMessageBox.confirm('确定删除该步骤吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    clientStore.ipc.send(icpList.setting.removeDeviceConfig, {
      id: row.id
    });
    clientStore.ipc.on(icpList.setting.removeDeviceConfig, (event, result) => {
      if (result.code == 0) {
        getList();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
      clientStore.ipc.removeAllListeners(icpList.setting.removeDeviceConfig);
    });
  });
};

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

/**
 * 重置设备配置。
 */
const resetConfig = () => {
  ElMessageBox.confirm(`确定初始化执行${activeTab.value === 'left' ? '左脚' : '右脚'}程序吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    clientStore.ipc.send(icpList.setting.resetDeviceConfig, {
      mode_type: activeTab.value === 'left' ? '执行左脚程序' : '执行右脚程序'
    });
    clientStore.ipc.on(icpList.setting.resetDeviceConfig, (event, result) => {
      if (result.code == 0) {
        getList();
        ElMessage.success('重置成功');
      } else {
        ElMessage.error('重置失败');
      }
      clientStore.ipc.removeAllListeners(icpList.setting.resetDeviceConfig);
    });
  });
};

/**
 * 修改设备配置数值。
 * @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.led_switch ? 1 : 0) : editRowData.value[socketValue[type]]
      }
    });
  }
}
</script>


<style lang="scss" scoped>
body {
  background: #EAECED;
}
.container {
  margin: 0 auto;
  height: calc(100vh - 30px);
  background: #EAECED;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.settings-nav {
  display: flex;
  justify-content: center;
  gap: 40px;
  padding: 30px 0;
  background: #EDEFF0;
  border-bottom: 1px solid rgba(0,0,0,0.1);
}
.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  color: #666;
  transition: all 0.3s;
  width: 100px;
  justify-content: center;
  height: 70px;
  font-size: 14px;
}
.nav-item.active {
    background: #DFE2E3;
    border-radius: 10px;
    color: #2957FF;
}
.nav-item i {
  font-size: 24px;
  margin-bottom: 8px;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-radius: 8px;
}
.form-container {
  border-radius: 12px;
  padding: 30px;
  padding-top: 10px;
  width: 800px;
  margin: 0 auto;
  height: 306px;
}
.form-item {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}
.form-item label {
  display: block;
  min-width: 98px;
  text-align: right;
  font-size: 14px;
  color: #1A1A1A;
}
.input-group {
  display: flex;
  gap: 12px;
}
.input-group input {
  flex: 1;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
}
.select-wrapper {
  position: relative;
  width: 200px;
  :deep(.el-input__inner){
    border-radius: 6px;
  }
}
.error-text {
  color: #dc2626;
  font-size: 12px;
  margin-top: 4px;
}
.from-primary{
    width: 150px;
    height: 40px;
    color: #FFFFFF;
    background: linear-gradient( 135deg, #2FB0FF 0%, #B863FB 100%);
}
.nav-icon{
    width: 32px;
    height: 32px;
}
.captureBox{
  border-bottom: 1px solid rgba(0,0,0,0.1);
}
.selectBox{
    padding-top: 30px;
    padding-left: 100px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    :deep(.el-tabs__header){
      padding-left: 0;
    }
    :deep(.el-tabs--card>.el-tabs__header){
      border-bottom: 1px solid #CCCCCC;
    }
    :deep(.el-tabs__item){
      height: 30px;
      line-height: 30px;
    }
    :deep(.el-tabs__nav-wrap){
      margin-bottom: 0;
    }
    :deep(.el-tabs__item.is-active){
      color: #333;
      font-weight: bold;
      background: #fff;
    }
}
.select-btn{
  display: flex;
  align-items: center;
  flex-shrink: 0;
  width: 120px;
  height: 30px;
  background: #DFE2E3;
  border-radius: 6px;
  justify-content: center;
  font-size: 14px;
  color: #2957FF;
  gap: 5px;
  img{
    width: 16px;
    height: 16px;
  }
}
.mt-8{
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  height: 100px;
}
.form-table{
  margin-top: 10px;
  .btnBox{
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  :deep(.el-table .el-table__header){
    padding: 0;
    height: 30px;
    .el-table__cell{
      background: #F1F4FF;
    }
  }
  :deep(.el-table .el-table__cell){
    padding: 0;
    text-align: center;
  }
  :deep(.el-table__row) {
    height: 30px;
    padding: 0;
    &:nth-child(even) {
      background: #F1F4FF;
    }
    &:nth-child(odd) {
      background: #FFFFFF;
    }
  }
  .primary-btn{
    width: 80px;
    height: 30px;
    background: linear-gradient( 135deg, #2FB0FF 0%, #B863FB 100%);
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
    line-height: 30px;
    margin-right: 10px;
  }
  .normal-btn{
    width: 80px;
    height: 30px;
    background: #fff;
    border: 1px solid #CCCCCC;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
  .cursor-pointer{
    cursor: pointer;
  }
}
.editDialog{
  .el-dialog__body{
    padding: 0 !important;
  }
  .btn-row{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    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;
  }
}
  .config-type{
    font-size: 14px;
    color: #333333;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 10px 0;
    .el-checkbox{
      margin-left: 10px;
    }
  }
.editForm{
  display: grid;
  grid-template-columns: repeat(2, 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 */
        }
      }
    }
}
</style>
