<template>
  <BasicTable @register="registerTable">
    <template #toolbar>
      <!-- <a-button type="primary" @click="openFeedbackDrawer">设备定损与反馈</a-button> -->
      <a-button type="primary" @click="openDeviceBindingModal">设备绑定码</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 == 'first_power_on'">
        {{ record.first_power_on? dayjs(record.first_power_on).format('YYYY-MM-DD HH:mm:ss'): '' }}
      </template>
      <template v-if="column.key == 'compatible_status'">
        {{ record.compatible_status? record.compatible_status == 0? "不需要一致性升级": "需要一致性升级": "" }}
      </template>
      <template v-if="column.key == 'flighttask_step_code'">
        {{ workStatus(record)}}
      </template>
      <template v-if="column.key === 'action'">
        <TableAction
        v-if="!record.pId"
          :actions="[
            {
              icon: 'ant-design:file-search-outlined',
              onClick: () => {
                console.log('deviceInfoList',deviceInfoList)
                deviceWarningDrawer = true
              },
            },
            {
              icon: 'carbon:calendar-tools',
              onClick: () => {
                openDeviceControl(record)
              },
            },
            {
              icon: 'jam:write',
              onClick: () => {
                editDevice(record)
              },
            },
            {
              icon: 'material-symbols:delete-outline',
              onClick: () => {
                delDevice(record)
              },
            },
          ]"
        />
      </template>
    </template>
  </BasicTable>
  <a-drawer class="feedback-drawer" v-model:open="feedbackDrawer" width="80%" :closable="false">
    <FeedbackDrawer />
  </a-drawer>
  <a-drawer class="device-warning" v-model:open="deviceWarningDrawer"  title="告警信息" width="70%" :closable="false">
    <DeviceWarning />
  </a-drawer>
  <a-drawer class="feedback-drawer"  title="设备运维" v-model:open="deviceControl" width="45%" :closable="false">
    <DeviceControl :deviceInfoList="deviceInfoList" :controlSN="controlSN"/>
  </a-drawer>
  <a-modal v-model:open="deviceBindingModal" title="设备绑定码" @ok="handleOk">
    <DeviceBindModal />
  </a-modal>
  <a-modal v-model:open="editDeviceModal" title="机场编辑" :footer="null">
    <DeviceEdit :editDeviceDate="editDeviceDate" :projectList="projectList" @changeEditDeviceModal="changeEditDeviceModal" @reload="reload"/>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted, watch, nextTick } from "vue"
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { columns, searchFormSchema, servicesReplyMessage } from './utils'
import FeedbackDrawer from './FeedbackDrawer/index.vue'
import DeviceBindModal from './DeviceBindModal/index.vue'
import DeviceControl from './DeviceControl/index.vue'
import DeviceEdit from './DeviceEdit/index.vue'
import DeviceWarning from './DeviceWarning/index.vue'
import { GetDataList, DeleteDronePort } from '@/api/demo/device'
import { getClient, clientSubscribe } from '@/utils/mqtt'
import dayjs from "dayjs";
import { message, Modal } from "ant-design-vue";
import { cloneDeep } from 'lodash-es';

const props = defineProps(['projectList','connected'])
watch(() => props.projectList, () => {
  const targetField = searchFormSchema.find(item => item.field === 'project');
  if (targetField) {
    targetField.componentProps = {
      ...(targetField.componentProps || {}),
      options: props.projectList,
    };
  }
})
watch(() => props.connected, () => {
  getClient().on('message', (topic, msg) => {
    console.log('topic',topic)
    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].sn == sn){
          list[i] = {...list[i],...rs.data}
        }
      }
      setTableData(list)
      const origin = deviceInfoList.value[sn] || {}
      const patch = rs.data || {}
      for (const key in patch) {
        origin[key] = patch[key]
      }
      deviceInfoList.value[sn] = origin
    }else if(topic.endsWith("services_reply")){
      const rs = JSON.parse(msg)
      console.log('services_reply','rs',rs)
      if(rs.data?.output?.status){
        message.info(servicesReplyMessage[rs.data.output.status])
      }
    }
  });
})

const feedbackDrawer = ref(false)
const deviceWarningDrawer = ref(false)
const deviceBindingModal = ref(false)
const afterFetch = ref(false)
const deviceControl = ref(false)
const deviceInfoList = ref({})
const controlSN = ref()
const editDeviceModal = ref(false)
const editDeviceDate = ref({})
watch(() => [afterFetch.value, props.connected], ([newAfterFetch, newConnected], [oldAfterFetch, oldConnected]) => {
  console.log(newAfterFetch,newConnected)
  console.log(getDataSource())
  if(newConnected && newAfterFetch){
    nextTick(() => {
      console.log(getDataSource())
      getDataSource().forEach(item => {
        let topicUrl = `thing/product/${item.sn}/osd`;
        let servicesReplyUrl = `thing/product/${item.sn}/services_reply`
        clientSubscribe(topicUrl);
        clientSubscribe(servicesReplyUrl);
      })
    })
  }
})
const [registerTable, { reload, expandAll, getForm,getDataSource,setTableData }] = useTable({
  title: '机场',
  api: GetDataList,
  columns,
  rowKey: 'id',
  formConfig: {
    labelWidth: 100,
    schemas: searchFormSchema,
  },
  striped: false,
  // 序号列
  showIndexColumn: false,
  // 使用搜索表单
  useSearchForm: true,
  // 显示表格设置工具
  showTableSetting: true,
  bordered: false,
  beforeFetch(data) {
    return data
  },
  afterFetch(data) {
    afterFetch.value = true
    return data.map(item => {
      return {...item, children: item.uavList}
    })
  },
  actionColumn: {
    width: 160,
    title: '操作',
    dataIndex: 'action',
  },
  handleSearchInfoFn(info) {
    return info;
  },
});
const openFeedbackDrawer = () => {
  feedbackDrawer.value = true
}
const openDeviceBindingModal = () => {
  deviceBindingModal.value = true
}
const workStatus = (record) => {
  if(record.flighttask_step_code){
    switch(record.flighttask_step_code){
      case 0:
        return '作业准备中'
      case 1:
        return '飞行作业中'
      case 2:
        return '作业后状态恢复'
      case 3:
        return '自定义飞行区更新中'
      case 4:
        return '地形障碍物更新中'
      case 5:
        return '任务空闲'
      case 255:
        return '飞行器异常'
      case 256:
        return '未知状态'
    }
  }else{
    return ''
  }
}
const openDeviceControl = (record) => {
  controlSN.value = record.sn
  let check = Object.keys(deviceInfoList.value).includes(controlSN.value) && Object.keys(deviceInfoList.value[controlSN.value]).includes('mode_code')
  if(!check){
    return message.warning('未获取到机场信息')
  }
  deviceControl.value = true
}
const editDevice = (record) => {
  editDeviceDate.value = cloneDeep(record)
  editDeviceModal.value = true
}
const changeEditDeviceModal = (value: boolean) => {
  editDeviceModal.value = value
}
const delDevice = (record) => {
  Modal.confirm({
    title: '是否删除该机场?',
    onCancel() {},
    onOk() {
      return DeleteDronePort(record.id).then(res => {
        message.success('删除成功')
        reload()
      })
    },
  });
}
</script>

<style lang="scss" scoped>
// .feedback-drawer{
//   :deep(.ant-drawer-body){
//     padding: 0px;
//   }
// }
// </style>
// <style lang="scss">
// .feedback-drawer{
//   .ant-drawer-body{
//     padding: 0px;
//   }
// }
</style>
