<template>
  <a-card>
      <a-row justify="end" >
        <a-col><a-button type="primary" @click="state.visible = true" >绑定标签</a-button></a-col>
      </a-row>
      <a-table
        style="margin-top: 20px;"
        :columns="columns"
        :data-source="state.dataSource"
        :loading="state.loading"
        :pagination="false"
      >
      <template #bodyCell="{column, record}">
        <template v-if="column.key === 'action'" >
                <a-popconfirm
                  title="确实要解绑吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmDel(record.id)"
                >
                  <a >解绑</a>
                </a-popconfirm>
        </template>
      </template>
      </a-table>
  </a-card>

  <modal-pro
    style="width: 700px;"
    title="绑定标签"
    :open="state.visible"
    @cancel="state.visible = false"
    @ok="ok"
  >
    <div class="subtitle">可根据需要定义设备标签，用于检索设备</div>
    <div  >
      <a-space style="margin: 10px 0px;" v-for="(item, index) in state.tags" :key="index" >
        <a-input allowClear style="width: 250px;" placeholder="请输入标签名" v-model:value="item.tagLabel" ></a-input>
        <a-input allowClear style="width: 250px;" placeholder="请输入标签值" v-model:value="item.tagValue"></a-input>
        <a-button type="text" danger @click="deltag(index)" >删除</a-button>
      </a-space>
    </div>
    <a @click="addTag" >添加标签</a>
  </modal-pro>
</template>
<script lang='ts' setup >
import { DeviceContriller } from '@/controller'
import { message } from 'ant-design-vue'
import { onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const deviceId = route.query.id as string

const columns = [
  {
    title: '标签名',
    dataIndex: 'tagLabel'
  },
  {
    title: '标签值',
    dataIndex: 'tagValue'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const tag = {
  deviceId,
  tagLabel: '',
  tagValue: ''
}

const state = reactive({
  visible: false,
  loading: false,
  tags: [{ ...tag }],
  dataSource: []
})

const deltag = (index: number) => {
  state.tags.splice(index, 1)
}

const addTag = () => {
  state.tags.push({ ...tag })
}

const confirmDel = async (id: string) => {
  await DeviceContriller.delTag(id)
  getDeviceTagPage()
}

const getDeviceTagPage = async () => {
  state.loading = true
  const { data } = await DeviceContriller.ListTag({ deviceId })
  state.dataSource = data
  state.loading = false
}

const validate = () => {
  state.tags.forEach(item => {
    if (!item.tagLabel || !item.tagValue) {
      message.warn('存在未填写的标签名或者标签值')
      return false
    }
  })

  return true
}

const ok = async () => {
  if (validate()) {
    await DeviceContriller.postTag(state.tags)
    state.visible = false
    getDeviceTagPage()
  }
}

onMounted(() => {
  getDeviceTagPage()
})

</script>
<style lang='less' scoped >

@import '~@/styles/theme.less';
.subtitle {
  color: @sublabel-color;
}
</style>
