<template>
  <a-card>
      <div class="subtitle" >
        呈现通过网关方式接入到IoT的设备（传感器）。子设备的状态表示子设备接入网关的状态，由网关上报到IoT平台进行状态的刷新；如果网关不能正常上报子设备的状态信息到IoT平台，则展示的子设备状态不会刷新。
      </div>
      <a-row justify="space-between" style="margin: 20px 0;" >
        <a-col>
          <a-space>
            <a-select allowClear style="width: 170px;"  v-model:value="state.queryParams.deviceStatus" >
              <a-select-option
                v-for="item in deviceStatusList"
                :key="item.key"
                :value="item.key"
              >{{item.name}}</a-select-option>
            </a-select>

            <a-select allowClear style="width: 120px;"  v-model:value="state.queryParams.searchKey" >
              <a-select-option
                v-for="item in DeviceContriller.searchKeyList"
                :key="item.key"
                :value="item.key"
              >{{item.name}}</a-select-option>
            </a-select>

            <a-input-search
            allowClear
              v-model:value="state.queryParams.searchValue"
              enter-button
              @search="getSubDevicePage"
              placeholder="请输入查询值"
            />
          </a-space>
        </a-col>
        <a-col>
          <a-button type="primary" @click="state.visible = true">添加子设备</a-button>
        </a-col>
      </a-row>

      <a-table
        :columns="columns"
        :loading="state.loading"
        :dataSource="state.dataSource"
        :pagination="state.queryParams"
        @change="changePage"
      >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'deviceStatus'">
          <a-tag :color="DeviceContriller.deviceStatusMap.get(record.deviceStatus)?.color" >{{ DeviceContriller.deviceStatusMap.get(record.deviceStatus)?.name }}</a-tag>
        </template>
          <template v-if="column.key === 'action'">
            <a-space>
                <a @click="goDeviceDetailPage(record.id)" >详情</a>
                <a-popconfirm
                  title="确实要删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delSubDevice(record.id)"
                >
                  <a>删除</a>
                </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
  </a-card>

  <modal-pro
    label="添加子设备"
    style="width: 700px;"
    :open="state.visible"
    @close="state.visible = false"
    @ok="ok"
  >
      <form-pro
        ref="formProo"
        validate
        :columnsProps="columns"
      />
  </modal-pro>
</template>
<script lang='ts' setup >
import { DeviceContriller, ModelCmdController, ModelController } from '@/controller'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Form } from 'ant-design-vue'
import type { ColumnsProps } from '@/components/FormPro/index.vue'

const useForm = Form.useForm

const route = useRoute()
const router = useRouter()
const emit = defineEmits(['goDetail'])

const formProo = ref('')

const deviceId = route.query.id as string

const columns: ColumnsProps[] = [
  {
    title: '所属产品',
    dataIndex: 'modelLabel',
    formProps: {
      rules: true,
      type: 'select',
      value: '',
      label: '所属产品',
      key: 'modelId',
      request: async () => {
        const { data } = await ModelController.list()
        return data.map(item => {
          return {
            name: item.modelLabel,
            value: item.id,
            key: item.id
          }
        })
      }
    }
  },
  {
    title: '状态',
    dataIndex: 'deviceStatus',
    key: 'deviceStatus'
  },
  {
    title: '设备名称',
    dataIndex: 'deviceLabel',
    formProps: {
      rules: false,
      type: 'input',
      value: '',
      label: '设备名称',
      key: 'deviceLabel'
    }
  },
  {
    title: '设备标识码',
    dataIndex: 'deviceCode',
    formProps: {
      rules: true,
      type: 'input',
      value: null,
      label: '设备标识码',
      key: 'deviceCode'
    }
  },
  {
    title: '设备ID',
    dataIndex: 'deviceId'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const deviceStatusList = [...DeviceContriller.deviceStatus, { name: '所有状态', key: '' }]

const state = reactive({
  loading: false,
  visible: false,
  dataSource: [],
  queryParams: {
    id: deviceId,
    page: 1,
    pageSize: 10,
    total: 0,
    deviceStatus: '',
    searchValue: '',
    searchKey: 'deviceId'
  }
})

const subDeviceState = reactive({
  gatewayId: '',
  deviceLabel: '',
  modelId: '',
  deviceCode: ''
})

const ok = async () => {
  const submitState = await formProo.value.onSubmit()
  await DeviceContriller.postSub({ ...submitState, gatewayId: deviceId })
  state.visible = false
  getSubDevicePage()
}

const changePage = ({ current }) => {
  state.queryParams.page = current
  getSubDevicePage()
}

const goDeviceDetailPage = (id: string) => {
  emit('goDetail', { id })
  router.replace({ path: '/device/detail', query: { id } })
}

const delSubDevice = async (id: string) => {
  await DeviceContriller.delSub(id)
  getSubDevicePage()
}
const getSubDevicePage = async () => {
  state.loading = true
  const { data, sum } = await DeviceContriller.pageSub(deviceId, state.queryParams)
  state.loading = false
  state.dataSource = data
  state.queryParams.total = sum
}

onMounted(() => {
  getSubDevicePage()
})

</script>

<style lang='less' scoped >
@import '~@/styles/theme.less';
.subtitle {
  color: @sublabel-color;
  font-size: 14px;
}
</style>
