<template>
  <div class="demo-collapse">
    <el-collapse accordion class="collapse2">
      <el-collapse-item v-for="item in protocolNames">
        <template #title>
          <div style="display: flex;width: 100%;justify-content: space-between">
            <div style="padding-left: 40px"> {{ item }} </div>
            <div >
              <el-button  text type="danger" icon="delete" @click="removeProtocol(item)">删除协议</el-button>
            </div>
          </div>

        </template>
        <div style="margin: auto; width: 90%">
          <collapse-table
            v-if="props.protocolCmd !== undefined && props.deviceProtocol !== undefined" 
            class="mt-4" 
            :info="props.deviceProtocol!" 
            :name="item" 
            :protocol-cmd="props.protocolCmd!" />
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import CollapseTable from "./CollapseTable.vue";
import type { DeviceProtocolResponse, ProtocolCmdResponse } from './types';
import { removeProtocolDao } from '@/dao/protocol';

type propsType = {
  deviceProtocol: DeviceProtocolResponse,
  protocolCmd: ProtocolCmdResponse
}
const props = defineProps<propsType>()

onMounted(() => {
  let { fields } = props.deviceProtocol 
  protocolNames.value = fields
})

const protocolNames = ref<string[]>([]);
watch(() => props.deviceProtocol, (val) => {
  let { fields } = val
  protocolNames.value = fields
})

const removeProtocol = (protocolName: string) => {
  removeProtocolDao(protocolName)
  .then(() =>{
    protocolNames.value = protocolNames.value.filter(item => item !== protocolName)
  })
  .catch(err => {
    console.log(err)
  })
}
</script>

<style>
.collapse2 .el-collapse-item__wrap {
  /*background-color: #f9f9f9; !* 设置展开区域的背景颜色 *!*/
}
</style>
