<template>
  <BasicTable class="w-4/4 xl:w-5/5" @register="registerTable">
    <template #toolbar>
      <a-button type="primary" @click="exportDevice">导出飞行器信息</a-button>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key == 'workSpaceId'">
        {{ props.projectList.find(item => item.value == record.workSpaceId)?.label }}
      </template>
      <template v-if="column.key === 'action'">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:edit-outlined',
              onClick: () => {
                edit(record)
              },
            },
            {
              color: 'error',
              icon: 'ant-design:delete-outlined',
              onClick: () => {
                delDate(record)
              },
            },
          ]"
        />
      </template>
    </template>
  </BasicTable>
  <a-modal v-model:open="editDeviceModal" title="飞行器编辑" :footer="null">
    <EditDevice :editDeviceDate="editDeviceDate" :projectList="projectList" @changeEditDeviceModal="changeEditDeviceModal" @reload="reload"/>
  </a-modal>
</template>

<script setup lang="ts">
import { h, watch, onMounted, ref, nextTick } from "vue"
import { EditOutlined } from '@ant-design/icons-vue'
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { columns, searchFormSchema } from './utils'
import { GetUavPageList, DeleteUav, ExportDevice } from '@/api/demo/device'
import { getClient, clientSubscribe } from '@/utils/mqtt'
import dayjs from "dayjs";
import { message, Modal } from "ant-design-vue";
import EditDevice from './EditDevice/index.vue'

const props = defineProps(['projectList','connected'])
const editDeviceDate = ref({})
const editDeviceModal = ref(false)
onMounted(() => {
  const targetField = searchFormSchema.find(item => item.field === 'workspaceid');
  if (targetField) {
    targetField.componentProps = {
      ...(targetField.componentProps || {}),
      options: props.projectList,
    };
  }
  getClient().on('message', (topic, msg) => {
    if (topic.endsWith("osd")) {
      const rs = JSON.parse(msg)
      let list = getDataSource()
      let sn = rs.gateway
      for(let i = 0; i < list.length; i++){
        if(list[i].psn == sn){
          if(rs.data.sub_device){
            list[i]['online_status'] = rs.data.sub_device.device_online_status == 0? '关机': '开机'
            list[i]['online_time'] = rs.data.first_power_on? dayjs(rs.data.first_power_on).format('YYYY-MM-DD HH:mm:ss'): ''
          }
        }
      }
    }
  })
})
const afterFetch = ref(false)
watch(() => afterFetch.value, () => {
    nextTick(() => {
      getDataSource().forEach(item => {
        let topicUrl = `thing/product/${item.psn}/osd`;
        clientSubscribe(topicUrl);
      })
    })
})
const [registerTable, { reload, expandAll, getForm,getDataSource}] = useTable({
  title: '飞行器',
  api: GetUavPageList,
  columns,
  rowKey: 'id',
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
  },
  striped: false,
  // 序号列
  showIndexColumn: false,
  // 使用搜索表单
  useSearchForm: true,
  // 显示表格设置工具
  showTableSetting: true,
  bordered: true,
  beforeFetch(data) {
    return data
  },
  afterFetch(data) {
    afterFetch.value = true
  },
  actionColumn: {
    width: 100,
    title: '操作',
    dataIndex: 'action',
  },
  handleSearchInfoFn(info) {
    return info;
  },
});
const changeEditDeviceModal = (value: boolean) => {
  editDeviceModal.value = value
}
const edit = (record) => {
  editDeviceDate.value = record
  editDeviceModal.value = true
}
const delDate = (record) => {
  Modal.confirm({
    title: '是否删除该飞行器?',
    onCancel() {},
    onOk() {
      return DeleteUav(record.id).then(res => {
        message.success('删除成功')
        reload()
      })
    },
  });
}
const exportDevice = () => {
  ExportDevice().then(res => {
    const elink = document.createElement('a');
    elink.download = '飞行器信息.txt';
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(res);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  })
}
</script>

<style lang="scss" scoped></style>
