<template>
  <div class="tab-content h-full">
    <div class="subtitle"><span></span> <el-button type="primary" v-auth="'add'" size="small" @click="addDevice()">添加设备</el-button></div>
    <el-table :data="tableData" style="width: 100%" v-loading="loading" max-height="calc(100vh - 280px)">
      <el-table-column label="标识" prop="key" min-width="150" show-overflow-tooltip v-col="'key'">
        <template #default="{ row }">
          <copy :text="row.key"></copy>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" prop="name" min-width="160" show-overflow-tooltip v-col="'name'" />
      <el-table-column label="设备类型" prop="product.deviceType" min-width="100" align="center" show-overflow-tooltip v-col="'deviceType'" />
      <el-table-column label="所属产品" prop="productName" min-width="120" align="center" show-overflow-tooltip v-col="'productName'" />
      <el-table-column prop="status" label="状态" min-width="80" align="center" v-col="'status'">
        <template #default="scope">
          <el-tag type="info" size="small" v-if="scope.row.status == 1">离线</el-tag>
          <el-tag type="success" size="small" v-if="scope.row.status == 2">在线</el-tag>
          <el-tag type="info" size="small" v-if="scope.row.status == 0">未启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastOnlineTime" label="最后上线时间" align="center" width="160" v-col="'lastOnlineTime'"></el-table-column>
      <el-table-column prop="desc" label="说明" show-overflow-tooltip v-col="'desc'"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button size="small" text type="primary" v-auth="'detail'" @click="$router.push('/iotmanager/device/instance/' + scope.row.key)">设备详情</el-button>
          <el-button size="small" text type="warning" v-auth="'del'" @click="onDel(scope.row)">解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
    <el-dialog title="添加设备" v-model="isShowDialog" width="400">
      <el-form v-if="isShowDialog">
        <el-form-item label="产品">
          <el-select v-model="form.productKey" @change="getDivices" filterable placeholder="选择产品" :clearable="false" style="width: 100%">
            <el-option v-for="item in productList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备" style="margin-bottom: 0;">
          <el-select v-model="form.resourcesKey" filterable placeholder="选择设备" :clearable="false" style="width: 100%">
            <el-option v-for="item in deviceList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import deviceApi from '/@/api/device';
import api from '/@/api/projects';
import { useSearch } from '/@/hooks/useCommon';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
const route = useRoute();

const props = defineProps({ resourcesTypes: Number })
const isShowDialog = ref(false)
const productList = ref<any[]>([])
const deviceList = ref<any[]>([])
const resourcesTypes = props.resourcesTypes
const projectsCode = route.params.id

const baseForm = {
  productKey: '',
  resourcesKey: '',
  projectsCode,
  resourcesTypes
}

const form = reactive({
  ...baseForm
})

const { params, tableData, getList, loading } = useSearch<any[]>(deviceApi.instance.getList, 'device', { keys: [], status: undefined });

getProducts();
getSourceList();

function getSourceList() {
  api.getProjectResourcesByCode({ projectsCode }).then((res: any) => {
    params.keys = (res || []).filter((item: any) => item.resourcesTypes === resourcesTypes).map((item: any) => item.resourcesKey)
    if (!params.keys.length) {
      params.pageNum = 1
      tableData.value = []
    } else {
      getList();
    }
  })
}

function getProducts() {
  deviceApi.product.getList({ pageSize: 500, status: 1 }).then((res: any) => {
    productList.value = (res?.product || []).map((item: any) => ({ label: item.name, value: item.key }))
  })
}

function onCancel() {
  Object.assign(form, baseForm)
  deviceList.value = []
  isShowDialog.value = false
}

function onSubmit() {
  if (!form.resourcesKey) return ElMessage('请先选择设备')
  api.bindResources(form).then((res: any) => {
    onCancel()
    getSourceList()
    ElMessage.success('添加成功')
  })
}

function addDevice() {
  isShowDialog.value = true
}

function onDel(row: any) {
  ElMessageBox.confirm(`确定要删除？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.unbindResources({
      projectsCode,
      resourcesTypes,
      resourcesKey: row.key
    }).then(() => {
      getSourceList()
      ElMessage.success('解绑成功')
    })
  });
}

function getDivices(productKey: string) {
  form.resourcesKey = ''
  deviceList.value = []
  deviceApi.device.allList({ productKey }).then((res: any) => {
    deviceList.value = (res?.device || []).map((item: any) => ({ label: item.name, value: item.key }))
  })
}

</script>
