<template>
  <div class="app-container-page">
    <el-form class="table-form-search" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
      label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="设备唯一标识" prop="devEui">
            <el-input v-model="queryParams.devEui" placeholder="请输入设备唯一标识" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属部门" prop="deptId">
            <DepartmentCascaDer v-model="queryParams.deptId" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="24" class="searchBtn">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <div class="table-list">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['worn:mqttDevice:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['worn:mqttDevice:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['worn:mqttDevice:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['worn:mqttDevice:export']">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="mqttDeviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" />
        <el-table-column label="设备唯一标识" align="center" prop="devEui" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备类型" align="center" prop="deviceType" />
        <el-table-column label="上报周期(分钟)" align="center" prop="reportIntervalMinute" />
        <el-table-column label="所属部门" align="center" prop="deptId">
          <template #default="scope">
            {{ getDictLabel(scope.row.deptId, departmentList, { name: 'deptName', value: 'deptId' }) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '0'" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status === '1'" type="danger">不可用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['worn:mqttDevice:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['worn:mqttDevice:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
    <!-- 添加或修改MQTT设备对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="mqttDeviceRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备唯一标识" prop="devEui">
              <el-input v-model="form.devEui" placeholder="请输入设备唯一标识" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-input v-model="form.deviceType" placeholder="请输入设备类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <DepartmentCascaDer v-model="form.deptId" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上报周期(分钟)" prop="reportIntervalMinute">
              <el-input-number
                v-model="form.reportIntervalMinute"
                :min="1"
                :max="1440"
                controls-position="right"
                placeholder="请输入上报周期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MqttDevice">
import { listDept } from '@/api/system/dept'
import { getDictLabel, getDeptIdPath } from '@/utils/until'
import DepartmentCascaDer from '../../../components/DepartmentCascaDer/index.vue'
import { listMqttDevice, getMqttDevice, delMqttDevice, addMqttDevice, updateMqttDevice } from "@/api/worn/mqttDevice";

const { proxy } = getCurrentInstance()

const total = ref(0)
const title = ref("")

const ids = ref([])
const mqttDeviceList = ref([])

const open = ref(false)
const isEdit = ref(false)
const single = ref(true)
const loading = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const departmentList = ref([]);// 所属部门

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    devEui: null,
    deviceName: null,
    deviceType: null,
    reportIntervalMinute: null,
    deptId: null,
    status: null
  },
  rules: {
    devEui: [
      { required: true, message: "设备唯一标识不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 所属部门
function getDepartmentListFun() {
  listDept().then((response) => {
    departmentList.value = response.data

  });
}
getDepartmentListFun()


/** 查询MQTT设备列表 */
function getList() {
  loading.value = true
  listMqttDevice(queryParams.value).then(response => {
    mqttDeviceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    devEui: null,
    deviceName: null,
    deviceType: null,
    reportIntervalMinute: null,
    deptId: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("mqttDeviceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  console.log(queryParams.value.deptId, 'queryParams.value.deptId');

  if (queryParams.value.deptId) {
    queryParams.value.deptId = queryParams.value.deptId.at(-1)
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  isEdit.value = false
  open.value = true
  title.value = "添加MQTT设备"
}

/** 修改按钮操作 */
function handleUpdate(row) {

  reset()
  isEdit.value = true
  const _id = row.id || ids.value
  getMqttDevice(_id).then(response => {
    const department = proxy.handleTree(departmentList.value, "deptId")
    const deptId = getDeptIdPath(department, response.data.deptId)
    form.value = { ...response.data, deptId }
    open.value = true
    title.value = "修改MQTT设备"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["mqttDeviceRef"].validate(valid => {
    if (valid) {
      form.value = { ...form.value, deptId: form.value.deptId.at(-1) }
      if (form.value.id != null) {
        updateMqttDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMqttDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除MQTT设备编号为"' + _ids + '"的数据项？').then(function () {
    return delMqttDevice(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('worn/mqttDevice/export', {
    ...queryParams.value
  }, `mqttDevice_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
:deep(.el-form-item__label) {
  white-space: nowrap;
}
</style>
