<template>
  <div class="app-container">
    <el-header style="display: flex;align-items: center;justify-content: space-between;background-color: #9ebee5;">
      <div>当前设备信息</div>
      <el-button type="primary" plain @click="boundDevice">{{ deviceStatus ? '更换设备' : '绑定设备' }}</el-button>
    </el-header>


    <div style="display: flex;">
      <div style="width: 300px;display: flex;flex-direction: column;align-items: center;padding: 30px 0;">
        <el-avatar :size="100" :src="avatar" />
      </div>
      <div style="width: 300px;font-size: 18px;padding: 30px 0;">
        <div>
          设备IP：{{ deviceInfo.ipAddress || "暂无" }}
        </div>
        <div style="margin-top: 20px;">
          设备端口：{{ deviceInfo.port || "暂无" }}
        </div>
      </div>
      <div style="width: 300px;font-size: 18px;padding: 30px 0;">
        <div>
          所属仓库：{{ deviceInfo.warehouseName || "暂无" }}
        </div>
        <div style="margin-top: 20px;">
          所属场景：{{ sceneData.filter(x=>x.sceneCode==deviceInfo.sceneId).length ? sceneData.filter(x=>x.sceneCode==deviceInfo.sceneId)[0].sceneName : "暂无" }}
        </div>
      </div>
    </div>

    <el-form :model="queryParams" ref="queryRef"  v-show="showSearch" label-width="68px">
      <el-row :gutter="40">
        <el-col :span="6">
          <el-form-item label="设备IP" prop="ipAddress">
            <el-input
              v-model="queryParams.ipAddress"
              placeholder="请输入设备IP地址"
              clearable
              
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备端口" prop="port">
            <el-input 
              v-model="queryParams.port"
              placeholder="请输入设备端口"
              clearable
              
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属仓库" prop="warehouseCode">
            <el-cascader :options="warehouseData" v-model="queryParams.warehouseCode" :props="{children: 'children', label: 'warehouseName', value: 'warehouseCode'}" clearable />
            <!-- <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable >
              <el-option v-for="dict in warehouseData" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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>

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

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="设备ID" align="center" prop="deviceId" /> -->
      <el-table-column label="设备IP地址" align="center" prop="ipAddress" />
      <el-table-column label="设备端口" align="center" prop="port" />
      <el-table-column label="所属仓库" align="center" prop="warehouseId">
        <template #default="scope">
          {{ scope.row.parentWarehouseName + '-' + scope.row.warehouseName }}
          <!-- {{ warehouseData.filter(x=>x.warehouseCode==scope.row.warehouseId).length>0 ? warehouseData.filter(x=>x.warehouseCode==scope.row.warehouseId)[0].warehouseName:""}} -->
        </template>
      </el-table-column>
      <el-table-column label="场景" align="center" >
        <template #default="scope">
          {{ sceneData.filter(x=>x.sceneCode==scope.row.sceneId).length>0 ? sceneData.filter(x=>x.sceneCode==scope.row.sceneId)[0].sceneName : ""}}
        </template>
      </el-table-column>
      <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="['information:device:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['information:device: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"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备IP" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入设备IP地址" />
        </el-form-item>
        <el-form-item label="设备端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入设备端口" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="warehouseCode">
          <el-cascader :options="warehouseData" style="width: 100%;" v-model="form.warehouseCode" :props="{children: 'children', label: 'warehouseName', value: 'warehouseCode'}" />
          <!-- <el-select v-model="form.warehouseId" placeholder="请选择仓库" clearable >
            <el-option v-for="dict in warehouseData" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="场景" prop="sceneId">
          <el-select v-model="form.sceneId" placeholder="请选择场景" clearable >
            <el-option v-for="dict in sceneData" :key="dict.id" :label="dict.sceneName" :value="dict.sceneCode" />
          </el-select>
        </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 setup name="Device">
import { ElMessage } from 'element-plus';
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/information/device";
import {warehouseDict, warehouseAll} from "@/api/information/warehouseinfo";
import {listScene} from "@/api/information/scene";
import avatar from "@/assets/images/avatar.jpg"
const { proxy } = getCurrentInstance();


const deviceObj = ref({
  deviceId: 0,
  ipAddress: 0,
  port: 0,
  warehouseCode: 0,
});
const deviceStatus = ref(false)
// 获取缓存数据
const deviceInfo = ref({})
if (localStorage.getItem("deviceInfo")) {
  deviceStatus.value = true
  deviceInfo.value = JSON.parse(localStorage.getItem("deviceInfo"))
} else {
  deviceStatus.value = false
}
// 选择设备
const boundDevice = () => {
  if (ids.value.length > 1) {
    ElMessage({ message: '只能选择一个设备信息', type: 'error' })
  } else if (ids.value.length == 1) {
    let sceneName = sceneData.value.filter(x=>x.sceneCode== deviceObj.value.sceneId)[0].sceneName
    let obj = JSON.parse(JSON.stringify(deviceObj.value))
    obj.sceneName = sceneName
    deviceInfo.value = JSON.parse(JSON.stringify(obj))
    localStorage.setItem("deviceInfo", JSON.stringify(obj))
    deviceStatus.value = true
  } else {
    ElMessage({ message: '请选择一个设备信息', type: 'error' })
  }
}

const deviceList = 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 warehouseData = ref([])   //仓库下拉列表
const sceneData = ref([])   //场景下拉列表
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ipAddress: null,
    port: null,
    warehouseCode: [],
    isDelete: null
  },
  rules: {
    ipAddress: [
      { required: true, message: "设备IP不能为空", trigger: "blur" }
    ],
    port: [
      { required: true, message: "设备端口不能为空", trigger: "blur" }
    ],
    warehouseCode: [
      { required: true, message: "所属仓库不能为空", trigger: "blur" }
    ],
    sceneId:[
      { required: true, message: "场景不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询设备信息列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


//所属仓库
function warehouseFun(){
  //所属仓库下拉数据
  warehouseAll().then(response=>{
    warehouseData.value = response.data
  })
}

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

// 表单重置
function reset() {
  form.value = {
    deviceId: null,
    ipAddress: null,
    port: null,
    warehouseCode: null,
    parentWarehouseCode: null,
    sceneId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isDelete: null
  };
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  if (queryParams.value.warehouseCode.length == 0) {
    queryParams.value.parentWarehouseCode = null
    queryParams.value.warehouseCode = null
  } else {
    queryParams.value.parentWarehouseCode = queryParams.value.warehouseCode[0]
    queryParams.value.warehouseCode = queryParams.value.warehouseCode[1]
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.warehouseCode = []
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  deviceObj.value = JSON.parse(JSON.stringify(selection[0]))
}

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

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _deviceId = row.deviceId || ids.value
  getDevice(_deviceId).then(response => {
    form.value = response.data;
    form.value.warehouseCode = [form.value.parentWarehouseCode, form.value.warehouseCode]
    open.value = true;
    title.value = "修改设备信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.warehouseCode.length) {
        form.value.parentWarehouseCode = form.value.warehouseCode[0]
        form.value.warehouseCode = form.value.warehouseCode[1]
      } else {
        form.value.parentWarehouseCode = null
        form.value.warehouseCode = null
      }
      if (form.value.deviceId != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _deviceIds = row.deviceId || ids.value;
  proxy.$modal.confirm('是否确认删除？').then(function() {
    return delDevice(_deviceIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('information/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}
//获取仓库下拉列表
function warehouseList(){
  warehouseDict().then(response=>{
    warehouseData.value = response.data
  })
}
//场景下拉列表
function sceneList(){
  let params = {pageNum:1,pageSize:50}
  listScene(params).then(response=>{
    sceneData.value = response.rows
  })
}

getList();
// warehouseList();  //库房
sceneList();    //场景
warehouseFun();
</script>
