<template>
  <headerBar
  >
    <template  #title><div @click="handleSettingClick" v-log="{ describe: { action: '点击设置标题' } }">设置</div></template>
  </headerBar>
  <div class="container setting-wrap">
    <nav class="settings-nav">
      <div class="nav-item" :class="{'active': activeIndex === 0}" @click="toggleTab(0)" v-log="{ describe: { action: '点击切换设置Tab', tab: '基础配置' } }">
        <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" v-if="configInfoStore.appModel === 1" :class="{'active': activeIndex === 3}" @click="toggleTab(3)" v-log="{ describe: { action: '点击切换设置Tab', tab: '相机配置' } }">
        <img src="@/assets/images/setting/icon2.png" class="nav-icon" v-if="activeIndex !== 3"/>
        <img src="@/assets/images/setting/icon2a.png" class="nav-icon" v-else/>
        <span>相机配置</span>
      </div>
      <div class="nav-item" :class="{'active': activeIndex === 2}" @click="toggleTab(2)" v-log="{ describe: { action: '点击切换设置Tab', tab: '其他设置' } }">
        <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" v-if="configInfoStore.appModel === 1"  :class="{'active': activeIndex === 4}"  @click="toggleTab(4)" v-log="{ describe: { action: '点击切换设置Tab', tab: '左右脚程序设置' } }">
        <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="selectBox" v-if="activeIndex === 0">
                <div class="form-item">
                  <label>主图尺寸：</label>
                  <div class="select-wrapper">
                    <el-select multiple
                               collapse-tags
                               multiple-limit="3"
                               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" v-if="formData.basic_configs.main_image_size.includes('custom')">
                  <label>自定义尺寸：</label>
                  <div class="select-wrapper">
                    <el-input
                        type="text"
                        v-model.number="customInput"
                        maxlength="4"
                        placeholder="请输入1-2000的尺寸值"
                        class="w-full px-3 py-2 border rounded-md"
                        @keypress="handleKeyPress"
                        @input="handleInput"
                    />
                  </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>

               <DebugPanel ref="debugPanel" />
        </div>
      <!--基础配置-->
      <!--相机配置-->
      <template v-if="activeIndex === 3">
      <CameraConfig ref="cameraConfigRef" :camera_configs="formData.camera_configs" @update:camera_configs="updateCameraConfigs"/>

      </template>
      <!--相机配置-->
      <!--其他设置-->
      <template v-if="activeIndex === 2">

        <div class="selectBox" style="padding-top: 0px" >
          <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>

          <other-config/>
          <!--                <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>

      </template>
      <!--其他设置-->
          <div class="selectBox" style="padding-top: 0px;padding-left: 0;" v-if="activeIndex === 4">
            <actionConfig/>

          </div>
    </div>
      <div class="text-center mt-8">
        <button class="bg-gradient-to-r from-primary" @click="onSava(activeIndex)" v-if="activeIndex !== 4" v-log="{ describe: { action: '点击保存设置', tabIndex: activeIndex } }">
          保存
        </button>
      </div>

  </div>
</template>

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

// 引入Vue相关功能和第三方库
import { ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { onMounted, watch } from 'vue';
import  { getAllUserConfigs,  setAllUserConfigs } from '@/apis/setting'
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';
import { digiCamControlWEB } from  '@/utils/appconfig'
import { useCheckInfo } from '@/composables/userCheck';
import { preview } from '@planckdev/element-plus/utils'
import actionConfig from './components/action_config.vue'
import otherConfig from './components/otherConfig'
import CameraConfig from './components/CameraConfig';
useCheckInfo();

//点击三次  打开资源目录

import DebugPanel from './components/DebugPanel.vue';
// 在setup函数中创建调试面板实例
const debugPanel = ref(null);
const cameraConfigRef = ref(null);
// 添加设置点击计数器
const settingClickCount = ref(0);

// 修改headerBar的点击处理函数
function handleSettingClick() {
  console.log('handleSettingClickhandleSettingClick')
  settingClickCount.value++;

  if (settingClickCount.value >= 3) {
    if (debugPanel.value) {
      debugPanel.value.showDebugPanel();
    }
    settingClickCount.value = 0;
  }

  setTimeout(() => {
    settingClickCount.value = 0;
  }, 3000); // 3秒内未再次点击则重置计数器
}




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

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


import  configInfo  from '@/stores/modules/config';
const configInfoStore = configInfo();

/**
 * 表单数据对象，用于存储设备配置信息。
 */
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: '320*320', value: 320 },
  { label: '512*512', value: 512 },
  { label: '768*768', value: 768 },
  { label: '800*800', value: 800 },
  { label: '1024*1024', value: 1024 },
  { label: '1200*1200', value: 1200 },
  { label: '1400*1400', value: 1400 },
  { label: '1600*1600', value: 1600 },
  { label: '自定义', value: 'custom' } // 新增自定义选项
]);

const customInput = ref(null); // 新增自定义输入值

const imageFormatList = ref([
  { label: 'jpg', value: 'jpg' },
  { label: 'png', value: 'png' },
  { label: 'jpeg', value: 'jpeg' },
  { label: 'webp', value: 'webp' },
  { label: 'avif', value: 'avif' },
]);
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: '精细化抠图' },
]);
const deviceSpeedList = ref([
  { label: '一档', value: '一档' },
  { label: '二档', value: '二档' },
  { label: '三档', value: '三档' },
]);
/*
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 indexKey  ={
  0:"basic_configs",
  1:"take_photo_configs",
  2:"other_configs",
}


/**
 * 监听路由参数变化，更新activeIndex和activeTab。
 */
watch(() => route.query.type, async (newType,oldType) => {
  const typeValue = parseInt(newType) || 0;
  getConfig()
});



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

const getConfig =  async (typeValue)=>{

  const resultPHP = await getAllUserConfigs();
  if(resultPHP.code == 0 &&  resultPHP.data.configs ){
      Object.keys(resultPHP.data.configs).map(item=>{
        formData[item] =  resultPHP.data.configs[item]
      })

    console.log(formData);
    const presetSizes = mainImageSizeList.value.map(item => item.value);
    const receivedSizes = formData.basic_configs.main_image_size ? [...formData.basic_configs.main_image_size] : [];

    // 分离自定义值
    const customValues = receivedSizes.filter(v => !presetSizes.includes(v));
    if (customValues.length > 0) {
      customInput.value = customValues[0]; // 保留第一个自定义值
      // 更新选中状态
      formData.basic_configs.main_image_size = receivedSizes
          .filter(v => presetSizes.includes(v))
          .concat('custom');
    } else {
      formData.basic_configs.main_image_size = receivedSizes;
    }
  }

}
/**
 * 组件挂载时初始化activeIndex。
 */
onMounted(async () => {
  getConfig()

  let  type = 0 ;
  if (route.query.type) {
    const typeValue = parseInt(route.query.type);
    type  = typeValue
    if (!isNaN(typeValue) && typeValue >= 0 && typeValue <= 3) {
      activeIndex.value = typeValue;
    }
  }


});


const handleKeyPress = (event) => {
  const char = event.key;
  // 只允许输入数字字符
  if (!/^\d+$/.test(char)) {
    event.preventDefault(); // 阻止非数字输入
  }
};
const handleInput = (value) => {
  if (value > 2000) {
    customInput.value = 2000;
  } else if (value < 1) {
    customInput.value = 1;
  }
};

// 添加更新camera_configs的方法
const updateCameraConfigs = (configs) => {
  formData.camera_configs = configs;
};

const toggleTab = async (item) => {
  const oldType = activeIndex.value;
  // 切换前保存当前 Tab 配置（包含相机配置 3）
  if ([0,1,2,3].includes(oldType)) {
    const next = await saveSetting(oldType);
    if (next === false) return false;
  }
  activeIndex.value = item;
  return true;
};

const onSava = async (index)=>{
  const next =  await  saveSetting(index)

  if(next !== false){
    ElMessage.success('保存成功')
  }

}

/**
 * 保存当前表单配置。
 */
const saveSetting = async (index) => {
  // 构建临时提交数据
  if(index === 3) {
    if (cameraConfigRef.value && typeof cameraConfigRef.value.save === 'function') {
      if(! cameraConfigRef.value.save()) return false;
    }
  }
  const submitData = {
    ...formData
  };
  if(index === 0) {
    if (formData.basic_configs.main_image_size.length === 0) {
      ElMessage.error('请选择主图尺寸！');
      return false;
    }

    // 处理自定义尺寸逻辑
    const selectedSizes = [...formData.basic_configs.main_image_size]; // 创建副本避免修改原始数据

    if (selectedSizes.includes('custom')) {
      if (!customInput.value || isNaN(customInput.value) ||
          customInput.value < 1 || customInput.value > 2000) {
        ElMessage.error('请输入1-2000之间的有效数值');
        return false;
      }

      // 创建新数组用于提交
      const submitSizes = selectedSizes
          .filter(v => v !== 'custom')
          .concat(parseInt(customInput.value));

      submitData.main_image_size = submitSizes
    }

  }
  const params = JSON.parse(JSON.stringify({
    configs:submitData
  }))
  const result = await setAllUserConfigs(params)
  if(result.code != 0)  return  false;
  return  true;

};



</script>

<style lang="scss">
.el-image-viewer__wrapper{
  z-index: 9999 !important;
}
.setting-wrap {

  .selectBox{
    padding-top: 30px;
    padding-left: 100px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    ::v-deep(.el-tabs__header){
      padding-left: 0;
    }
    ::v-deep(.el-tabs--card>.el-tabs__header){
      border-bottom: 1px solid #CCCCCC;
    }
    ::v-deep(.el-tabs__item){
      height: 30px;
      line-height: 30px;
    }
    ::v-deep(.el-tabs__nav-wrap){
      margin-bottom: 0;
    }
    ::v-deep(.el-tabs__item.is-active){
      color: #333;
      font-weight: bold;
      background: #fff;
    }
  }

  .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;
  }

  .select-wrapper {
    position: relative;
    width: 200px;
    ::v-deep(.el-input__inner){
      border-radius: 6px;
    }
  }
}
</style>
<style lang="scss" scoped>
body {
  background: #EAECED;
}
.container {
  margin: 0 auto;
  min-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;
}
.input-group {
  display: flex;
  gap: 12px;
}
.input-group input {
  flex: 1;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
}
.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);
}
.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;
}
  .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;
    ::v-deep(.el-radio){
      margin-right: 6px !important;
    }
    ::v-deep(.el-radio__label){
      padding-left: 4px;
    }
  }
  ::v-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: textfield; /* Firefox */
        }
      }
    }
}
</style>
