<template>

  <el-tabs v-model="topsTab" type="card" class="top_tabs">
    <el-tab-pane label="执行左脚程序" name="left">
    </el-tab-pane>
    <el-tab-pane label="执行右脚程序" name="right"></el-tab-pane>
  </el-tabs>

  <div class="two_tabs">
      <div class="item"
           :class="item.id === activeTab.id ? 'active' : ''"
           v-for="item in tabs" :key="item.id"
           @click="toggleTab(item)"
      >{{item.mode_name}}</div>
  </div>
  <div class="form-table">
    <div class="btnBox">
      <div class="primary-btn" @click="addRow">新增一行</div>
      <div class="primary-btn" @click="resetConfig">重新初始化</div>
      <div class="primary-btn" @click="reName">重命名配置</div>
      <el-radio-group style="margin-left: 10px" v-model="selectID" @click="changeSelectId(activeTab.id)">
        <el-radio :label="activeTab.id">切换成执行配置</el-radio>
      </el-radio-group>
    </div>
    <el-table max-height="700" :data="tableData" style="width: 100%" border>
<!--      <el-table-column prop="id" label="id" />-->
      <el-table-column prop="action_name" label="步骤" >
        <template #default="scope">
          {{ scope.row.action_name }}
          <el-tag type="success" size="small" v-if="calibrationId === scope.row.id">校准位</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="take_picture" label="是否拍照" width="200px">
        <template #default="scope">
          <div v-if="!scope.row.is_system">
            {{ scope.row.take_picture ? '拍照' : '不拍照' }}
          </div>
          <span v-else></span>

        </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" v-if="!row.is_system" @click="deleteRow(row, $index)">删除</a>
        </template>
      </el-table-column>
    </el-table>
  </div>




  <EditDialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :id="editId"
      :addRowData="addRowData"
      @confirm="getList"
  />
</template>

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


// 表格数据和对话框状态
const tableData = ref([]); // 配置表格数据
const dialogVisible = ref(false); // 编辑对话框可见状态
const editTitle = ref(''); // 编辑对话框标题
const addRowData = ref({}); // 新增行
const topsTab = ref('left'); // 顶部tab
const activeTab = ref({}); // 当前激活的标签页
const tabs = ref([]); // 所有标签页
const editId = ref(0); // 当前编辑行的索引
const selectID = ref(0) //当前默认的ID

onMounted(()=>{
  topsTab.value = 'left';
  getTopList()
})

/**
 * 监听topsTab变化，获取对应标签页的设备配置列表。
 */
watch(() => topsTab.value, (newTab) => {
  getTopList();
});

const getTopList = ()=>{
      clientStore.ipc.removeAllListeners(icpList.setting.getDeviceTabs);
      clientStore.ipc.send(icpList.setting.getDeviceTabs, {
        type: topsTab.value == 'left' ? 0 :1
      })
      clientStore.ipc.on(icpList.setting.getDeviceTabs, (event, result) => {
        console.log('getDeviceTabs')
        console.log(topsTab.value)
        console.log(result)
        if(result.code == 0 && result.data){
          tabs.value = result.data.tabs
          tabs.value.some(item=>{
            console.log('=======' )
            console.log(item.id )
            console.log(result.data.select_configs[topsTab.value] )
            if(item.id === result.data.select_configs[topsTab.value]){
              selectID.value = item.id
              activeTab.value =  item
              return true;
            }
          })

          getList()
        }
        clientStore.ipc.removeAllListeners(icpList.setting.getDeviceTabs);
      });

}

//切换tab
const toggleTab = (item) => {
  activeTab.value = item
  getList()
};


const calibrationId = ref(null) //校准位
/**
 * 获取设备配置列表。
 */
const getList = () => {
  clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
  let params = {
    tab_id: activeTab.value.id
  }
  clientStore.ipc.send(icpList.setting.getDeviceConfigList, params);
  clientStore.ipc.on(icpList.setting.getDeviceConfigList, (event, result) => {
    console.log('getDeviceConfigList')
    console.log(params)
    console.log(result)
    if (result.code == 0) {
      tableData.value = result.data.list;
      const calibration =  result.data.list.filter(item=>(item.action_name === '侧视'))
      if(calibration.length >= 1){
        calibrationId.value = calibration[0].id
      }else{

        calibrationId.value = tableData.value[0].id
      }
    } else {
      ElMessage.error('获取列表失败');
    }
    clientStore.ipc.removeAllListeners(icpList.setting.getDeviceConfigList);
  });
};


const changeSelectId = (id)=>{
  if(id === selectID.value) return;
  clientStore.ipc.removeAllListeners(icpList.setting.updateLeftRightConfig);
  let params = {
    type: topsTab.value,
    id,
  }
  clientStore.ipc.send(icpList.setting.updateLeftRightConfig, params);
  clientStore.ipc.on(icpList.setting.updateLeftRightConfig, (event, result) => {
    console.log('updateLeftRightConfig')
    console.log(params)
    console.log(result)
    if (result.code == 0) {
      selectID.value = id;
    } else if(result.mssg){
      ElMessage.error(result.mssg);
    }else{
      ElMessage.error('切换失败');
    }
    clientStore.ipc.removeAllListeners(icpList.setting.updateLeftRightConfig);
  });
}

/**
 * 编辑指定行的配置。
 * @param {Object} row - 当前行的数据
 * @param {number} index - 当前行的索引
 */
const editRow = (row, index) => {
  addRowData.value = {}
  dialogVisible.value = true;
  editId.value = row.id
};

/**
 * 删除指定行的配置。
 * @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 if(result.mssg){
        ElMessage.error(result.mssg);
      }else {
        ElMessage.error('删除失败');
      }
      clientStore.ipc.removeAllListeners(icpList.setting.removeDeviceConfig);
    });
  });
};

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

const reName = ()=>{
  ElMessageBox.prompt('', '重命名配置', {
    confirmButtonText: '保存',
    cancelButtonText: '取消',
    inputValue:  activeTab.value.mode_name,
    inputPlaceholder:'请输入配置名称',
    inputValidator: (value) => {
      if (value === '') {
        return '请输入配置名称';
      }
      return true;
    },
  })
      .then(({ value }) => {
        clientStore.ipc.removeAllListeners(icpList.setting.updateTabName);
        clientStore.ipc.send(icpList.setting.updateTabName, {
          id: activeTab.value.id,
          mode_name:value,
        });
        clientStore.ipc.on(icpList.setting.updateTabName, (event, result) => {
          if (result.code == 0) {
            activeTab.value.mode_name = value
            tabs.value.some(item=>{
              if(item.id ===  activeTab.value.id){
                item.mode_name   =  activeTab.value.mode_name
              }
            })
            ElMessage.success('重命名成功');
          }  else if(result.mssg){
            ElMessage.error(result.mssg);
          }else {
            ElMessage.error('重命名失败');
          }
          clientStore.ipc.removeAllListeners(icpList.setting.updateTabName);
        });
      })
}

/**
 * 新增一行配置。
 */
const addRow = () => {
  editId.value = -1
  let length = Number(tableData.value.length)+1
  addRowData.value =   {
    mode_type: topsTab.value === 'left' ? '执行左脚程序' : '执行右脚程序',
    tab_id: activeTab.value.id,
    action_name: '新增步骤'+length,
    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 = '新增步骤';
};

</script>

<style lang="scss" scoped>
.top_tabs {
  height: 30px;
  overflow: hidden;
  border: 1px solid #c8c8c8;
  border-bottom: none;
}
.two_tabs {
  width: 100%;
  height: 30px;
  background: #fff;
  border: 1px solid #c8c8c8;
  border-top: none;
  .item {
    float: left;
    padding: 0 15px;
    font-size: 14px;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
    &.active {
      color: #2957FF;
    }
  }
}
.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;
  }
}

</style>
