<template>
  <div class="app-container">
  <div ref="topContainerRef">
    <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        label-width="80px"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
    >
      <template #one>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input
                v-model="queryParams.deviceCode"
                clearable
                placeholder="请输入设备编号"
                style="width:100%"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
                v-model="queryParams.deviceName"
                clearable
                placeholder="请输入设备名称"
                style="width:100%"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="设备类型" prop="deviceModel">
            <el-select
                v-model="queryParams.deviceModel"
                placeholder="请输入设备类型"
            >
              <el-option
                  v-for="item in controlModuleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
    </TableSearch>

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

  <div :style="containerHeight">
    <el-table height="100%" v-loading="loading" :data="registerList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="id" prop="id" show-overflow-tooltip/>
      <el-table-column align="center" label="设备终端配置id" prop="idDeDeviceTerminalConfig" show-overflow-tooltip
                       width="120"/>
      <el-table-column align="center" label="设备编号" prop="deviceCode" show-overflow-tooltip/>
      <el-table-column align="center" label="设备名称" prop="deviceName" show-overflow-tooltip/>
      <!--      <el-table-column label="设备规格" align="center" prop="deviceSpec"/>-->
      <el-table-column align="center" label="设备类型" prop="deviceModel">
        <template #default="scope">
          {{ controlModuleList.find(item => item.value === scope.row.deviceModel)?.label }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="设备厂家" align="center" prop="factory"/>-->
      <!--      <el-table-column label="设备图片" align="center" prop="images"/>-->
      <!--      <el-table-column show-overflow-tooltip label="备注" align="center" prop="remake"/>-->
      <el-table-column align="center" label="设备状态" prop="status">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              active-text="启用"
              active-value="0"
              inactive-text="停用"
              inactive-value="1"
              inline-prompt
              @change="handleChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200">
        <template #default="scope">
          <el-button v-hasPermi="['device:register:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['device:register:deploy']" icon="Cpu" link type="primary"
                     @click="handleControl(scope.row)">示教
          </el-button>
          <el-button v-hasPermi="['device:register:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />
    </div>

    <!-- 添加或修改设备注册对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="registerRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="设备终端配置id" prop="idDeDeviceTerminalConfig">
          <el-input v-model="form.idDeDeviceTerminalConfig" 
                    placeholder="请输入设备终端配置id"/>
          <!-- <el-input v-model="form.idDeDeviceTerminalConfig" :disabled="form.idDeDeviceTerminalConfig!== ''"
                    placeholder="请输入设备终端配置id"/> -->
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode"  placeholder="请输入设备编号"/>
          <!-- <el-input v-model="form.deviceCode" :disabled="form.deviceCode!== ''" placeholder="请输入设备编号"/> -->
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
        </el-form-item>
        <!--        <el-form-item label="设备规格" prop="deviceSpec">-->
        <!--          <el-input v-model="form.deviceSpec" placeholder="请输入设备规格"/>-->
        <!--        </el-form-item>-->

        <el-form-item label="设备类型" prop="deviceModel">
          <el-select
              v-model="form.deviceModel"
              placeholder="请输入设备类型"
          >
            <el-option
                v-for="item in controlModuleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属分组">
          <el-select v-model="form.groupId" placeholder="请选择所属分组">
            <el-option v-for="group in groupList" :key="group.value" :label="group.label"
                       :value="group.value"></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="设备厂家" prop="factory">-->
        <!--          <el-input v-model="form.factory" placeholder="请输入设备厂家"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="设备图片" prop="images">-->
        <!--          <el-input v-model="form.images" placeholder="请输入设备图片"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="remake">-->
        <!--          <el-input :rows="2"-->
        <!--                    type="textarea" v-model="form.remake" placeholder="请输入备注"/>-->
        <!--        </el-form-item>-->
      </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 name="Register" setup>
import {addRegister, delRegister, getRegister, listRegister, updateRegister} from "@/api/device/register"
import TableSearch from "@/components/TableSearch/index.vue"
import {useRouter} from "vue-router"
import {intoControlPage} from "@/views/device/register/components/index.js";
import {controlModuleList} from "@/enum/index.js";
import {listGroup} from "@/api/system/group.js";
import useTagsViewStore from '@/store/modules/tagsView'

import { useContainerHeight } from "@/hooks/tableHeight";

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const router = useRouter()


const {proxy} = getCurrentInstance()

const registerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceCode: null,
    deviceName: null,
    deviceSpec: null,
    deviceModel: null,
    factory: null,
    status: null
  },
  rules: {}
})

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

/** 查询设备注册列表 */
function getList() {
  loading.value = true
  listRegister(queryParams.value).then(response => {
    registerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    // id: null,
    // createBy: null,
    // createTime: null,
    // updateBy: null,
    // updateTime: null,
    // remake: null,
    // idDeDeviceTerminalConfig: null,
    // deviceCode: null,
    // deviceName: null,
    // deviceSpec: null,
    // deviceModel: null,
    // factory: null,
    // images: null,
    // status: null
  }
  proxy.resetForm("registerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 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()
  open.value = true
  title.value = "添加设备注册"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRegister(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设备注册"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registerRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRegister(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRegister(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

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

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


/** 控制按钮操作 */
function handleControl(row) {
  const fullPath = `${row.deviceModel}/${row.id}`; // 构造路由路径
  router.push({
    path: fullPath,
    query: {
      terminalId: row.idDeDeviceTerminalConfig,
      deviceId: row.deviceCode
    }
  }); // 使用路由跳转
  // intoControlPage(`/${row.deviceModel}`, `${row.id}`)
}

function handleChange(row) {
  updateRegister({status: row.status, id: row.id}).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    getList()
  })
}

getList()


const groupList = ref([])

/** 获取系统分组列表(默认传1查询检测项列表) */
function handleGetSystemGroup(row) {
  listGroup({type: 3}).then(response => {
    groupList.value = response.rows?.map((item) => {
      return {
        label: item.groupName,
        value: String(item.groupId)
      }
    })
  })
}

handleGetSystemGroup()
</script>
