<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型">
          <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.typeName" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:device:add']">新增</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:device:export']">批量下载二维码</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="deviceNo" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备类型" align="center" prop="deviceTypeName" />
      <el-table-column label="设备位置描述" align="center" prop="location" />
      <el-table-column label="设备二维码" align="center" class-name="small-padding">
        <template #default="scope">
          <el-button type="text" icon="el-icon-download" @click="handleDownloadQrCode(scope.row)" v-hasPermi="['device:device:downloadQr']"
            >下载二维码</el-button
          >
        </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="['device:device:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:device:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" :disabled="isEdit" placeholder="请选择设备类型" @change="deviceTypeChange">
            <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.typeName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-if="isEdit" v-model="form.deviceName"></el-input>
          <el-select v-else v-model="form.deviceName" value-key="deviceNo" placeholder="请选择设备类型名称" @change="deviceNameChange">
            <el-option v-for="item in deviceList" :key="item.deviceNo" :label="item.deviceName" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="form.deviceNo" disabled placeholder="自动获取" />
        </el-form-item>
        <el-form-item label="设备位置描述" prop="location">
          <el-input v-model="form.location" 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>
import { listDevice, deviceTypeList, delDevice, addDevice, updateDevice } from '@/api/device/device';
import { listDevice as listDeviceType } from '@/api/device/deviceType';
import request from '@/utils/request';

export default {
  name: 'Device',
  data() {
    return {
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备类型表格数据
      deviceList: [],
      dataList: [],
      deviceTypeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        deviceType: null,
        location: null,
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceName: [
          // 设备名称必填校验
          { required: true, message: '设备名称不能为空', trigger: 'blur' },
        ],
        deviceType: [
          // 设备类型必填校验
          { required: true, message: '设备类型不能为空', trigger: 'change' },
        ],
      },
    };
  },
  created() {
    this.getList();
    listDeviceType().then(response => {
      this.deviceTypeList = response.rows;
    });
  },
  computed: {
    // 是否是编辑状态
    isEdit() {
      return this.form.id != null;
    },
  },
  methods: {
    // 设备类型change事件
    deviceTypeChange(value) {
      // 设备类型变更时，清空设备名称
      this.form.deviceName = null;
      // 根据设备类型获取对应的设备列表
      deviceTypeList(value).then(res => {
        if (res.code === 200) {
          this.deviceList = res.data;
        }
      });
    },
    // 设备名称change事件
    deviceNameChange(value) {
      // 设备名称变更时，清空设备编号和位置描述
      this.form.deviceNo = null;
      this.form.location = null;
      // 如果选择了设备名称，则填充对应的设备编号和位置描述
      if (value) {
        this.form.deviceName = value.deviceName;
        this.form.deviceNo = value.deviceNo;
        this.form.location = value.location;
      }
    },
    // 下载在线图片的函数
    downloadOnlineImage(imageUrl, fileName) {
      fetch(imageUrl)
        .then(response => response.blob())
        .then(blob => {
          const tempUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = tempUrl;
          link.download = fileName || 'downloaded_image.png';
          document.body.appendChild(link);
          link.click();

          // 清理资源
          setTimeout(() => {
            URL.revokeObjectURL(tempUrl);
            document.body.removeChild(link);
          }, 100);
        })
        .catch(error => console.error('下载失败:', error));
    },

    // 新增下载二维码方法
    async handleDownloadQrCode(row) {
      // 使用示例
      const fileurl = this.baseUrl + row.qrCode;
      this.downloadOnlineImage(fileurl, 'qr_code.png');
    },
    /** 查询设备类型列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceName: null,
        deviceType: null,
        location: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加设备类型';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids
      // getDevice(id).then(response => {
      //   this.form = response.data
      this.open = true;
      this.title = '修改设备类型';
      this.form = JSON.parse(JSON.stringify(row));
      // })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除设备类型编号为"' + row.deviceNo + '"的数据项？')
        .then(function () {
          return delDevice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download('/gemho/device/downloadQrZip', {
      //   ...this.queryParams
      // }, `device_${new Date().getTime()}.xlsx`)
      // 调用接口获取图片流（需确保已配置axios的baseURL）

      request({
        url: `/gemho/device/downloadQrZip`,
        params: this.queryParams,
        method: 'get',
        responseType: 'blob', // 关键：指定接收二进制流
      }).then(response => {
        // 创建Blob对象并生成临时URL
        const blob = new Blob([response], { type: 'application/zip' }); // 根据实际图片类型调整
        const url = window.URL.createObjectURL(blob);

        // 创建并触发下载链接
        const a = document.createElement('a');
        a.href = url;
        a.download = `二维码.zip`; // 文件名使用设备编号+二维码
        document.body.appendChild(a);
        a.click();

        // 清理资源
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.$message.success('二维码下载成功');
      });
    },
  },
};
</script>
