<template>
  <a-card
    style="width: 100%"
    :tab-list="tabListNoTitle"
    :active-tab-key="state.tasActive"
    @tabChange="onTabChange"
  >
    <template v-if="state.tasActive == 'msg'" >
      <a-alert :message="tipMessage" type="info" show-icon />
      <div class="subtitle" >注意：平台为每个设备默认最多保存20条消息，超过20条后，后续的消息会替换下发最早的消息。</div>
      <a-row>
        <a-col> <a-button type="primary" @click="state.visible = true">下发消息</a-button>  </a-col>
      </a-row>
      <a-table
        style="margin-top: 20px;"
        :columns="columns"
        :dataSource="state.msgDataSource"
        :loading="state.loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <span>{{ DeviceContriller.deviceMag.get(record.status)?.name }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <a @click="openDetailModal(record)" >详情</a>
          </template>
        </template>
      </a-table>
    </template>
    <template v-if="state.tasActive == 'cmd'" >

    </template>
  </a-card>

  <modal-pro
    :title="modalTitle"
    :visible="state.visible"
    @cancel="state.visible = false"
    @ok="ok"
  >
  <a-form
    :labelCol="{span: 4}"
    :wrapperCol="{span: 14}"
  >
    <a-form-item
      label="消息名称"
      v-bind="validateInfos.msgLabel"
    >
      <a-input v-model:value="msgState.msgLabel" > </a-input>
    </a-form-item>
    <a-form-item
      label="Topic"
    >
      <a-input v-model:value="msgState.topic" > </a-input>
    </a-form-item>
    <a-form-item
      label="消息内容"
      v-bind="validateInfos.msgPayload"
    >
      <a-textarea v-model:value="msgState.msgPayload" > </a-textarea>
    </a-form-item>
  </a-form>

  </modal-pro>
</template>

<script lang="ts" setup >

import { DeviceContriller } from '@/controller'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { Form } from 'ant-design-vue'

const msg = '消息下发不依赖产品模型，平台会以异步方式（消息下发后无需等待设备侧回复响应）下发消息给设备。当前仅MQTT设备支持消息下发。'
const cmdMsg = '如果设备所属产品定义了命令功能，则您可以通过应用调用平台接口或者操作下面的“下发命令”按钮下发命令。当前MQTT设备仅支持同步命令下发，NB设备仅支持异步命令下发 。'
const modalTitle = '新增下发消息'
const tabListNoTitle = [
  {
    key: 'msg',
    tab: '消息下发'
  },
  {
    key: 'cmd',
    tab: '命令下发'
  }
]

const columns = [
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '消息名称',
    dataIndex: 'msgLabel'
  },
  {
    title: '消息id',
    dataIndex: 'msgId'
  },
  {
    title: '消息内容',
    dataIndex: 'msgPayload'
  },
  {
    title: '消息创建时间',
    dataIndex: 'createAt'
  },
  {
    title: '操纵',
    key: 'action'
  }
]

const useForm = Form.useForm
const route = useRoute()
const deviceId = route.query.id as string

const tipMessage = computed(() => state.tasActive === 'msg' ? msg : cmdMsg)

const state = reactive<{
  tasActive: 'msg' | 'cmd',
  msgDataSource: IOT.API.DEVICE.Msg[],
  visible: boolean,
  loading: boolean,
  detailVisible: boolean,
  msgDetail: IOT.API.DEVICE.Msg | {}
}>({
  tasActive: 'msg',
  msgDataSource: [],
  visible: false,
  loading: false,
  detailVisible: false,
  msgDetail: {}
})

const msgState = reactive({
  deviceId: deviceId,
  msgPayload: '',
  msgLabel: '',
  topic: ''
})

const { resetFields, validate, validateInfos } = useForm(msgState, reactive({
  msgPayload: [{ required: true, message: '请填写消息内容' }],
  msgLabel: [{ required: true, message: '请填写消息标题' }]
}))

const ok = () => {
  validate().then(async () => {
    await DeviceContriller.addDeviceMsg(msgState)
    state.visible = false
    getDeviceMsgList()
  })
}

const openDetailModal = (record: IOT.API.DEVICE.Msg) => {
  state.detailVisible = true
  state.msgDetail = record
}

const getDeviceMsgList = async () => {
  state.loading = true
  state.msgDataSource = await DeviceContriller.listDeviceMsg({ deviceId })
  state.loading = false
}

const onTabChange = (value: 'msg' | 'cmd') => state.tasActive = value

onMounted(() => {
  getDeviceMsgList()
})
</script>

<style lang="less" scoped >
@import '~@/styles/theme.less';
.subtitle {
  color: @sublabel-color;
  margin: 20px 0px;
}
</style>
