<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="placeName">
        <el-input v-model="queryParams.placeName" 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">批量下载二维码</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="placeList" @selection-change="handleSelectionChange">
      <el-table-column label="地点名称" align="center" prop="placeName" />
      <el-table-column label="地点位置" align="center" prop="location" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="巡检人" align="center" prop="userName" />
      <el-table-column label="信息" align="center" prop="information" />
      <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)">下载二维码</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)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</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="110px">
        <el-form-item label="地点名称" prop="placeName">
          <el-input v-model="form.placeName" placeholder="请输入地点名称" />
        </el-form-item>
        <el-form-item label="巡检位置描述" prop="location">
          <el-input v-model="form.location" placeholder="请输入巡检位置描述" />
        </el-form-item>
        <el-form-item label="部门名称" prop="inspectionDeptId">
          <treeselect
            v-model="form.inspectionDeptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择部门名称"
            @select="deptSelect"
          />
        </el-form-item>
        <el-form-item label="巡检人" prop="inspectionUserId">
          <el-select v-model="form.inspectionUserId" multiple placeholder="请选择巡检人">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信息" prop="information">
          <el-input v-model="form.information" placeholder="请输入信息" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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 { listLog, getLog, delLog, addLog, updateLog } from '@/api/patrol/patrolLocation'
import { listDept } from '@/api/system/dept'
import { listUser } from '@/api/system/user'
import request from '@/utils/request'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Device',
  components: {
    Treeselect,
  },
  data() {
    return {
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备类型表格数据
      deviceList: [],
      placeList: [],
      deviceTypeList: [],
      // 用户列表
      userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        placeName: null,
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      // 查询用户参数
      queryParamsUser: {
        pageNum: 1,
        pageSize: 100,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        placeName: [
          // 地点名称必填校验
          { required: true, message: '地点名称不能为空', trigger: 'blur' },
        ],
        location: [
          // 巡检位置描述必填校验
          { required: true, message: '巡检位置描述不能为空', trigger: 'blur' },
        ],
        information: [
          // 信息必填校验
          { required: true, message: '信息不能为空', trigger: 'blur' },
        ],
        inspectionDeptId: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        inspectionUserId: [{ required: true, message: '巡检人不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList()
    this.getDeptList()
    this.getUserList()
  },
  methods: {
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      }
    },
    /** 获取所有部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 部门选择事件 */
    deptSelect(val) {
      this.queryParamsUser.deptId = val.deptId
      this.form.inspectionUserId = null
      this.getUserList()
    },
    /** 查询用户列表 */
    getUserList() {
      listUser(this.addDateRange(this.queryParamsUser)).then(response => {
        this.userList = response.rows
      })
    },
    // 下载在线图片的函数
    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
      listLog(this.queryParams)
        .then(response => {
          this.placeList = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        placeName: null,
        location: null,
        information: null,
        inspectionUserId: null,
        inspectionDeptId: null,
        remark: null,
      }
      this.userList = []
      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()
      this.open = true
      this.title = '修改巡检点'
      this.form = JSON.parse(JSON.stringify(row))
      // 如果有部门ID，则加载对应的用户列表
      if (this.form.inspectionDeptId) {
        this.queryParamsUser.deptId = this.form.inspectionDeptId
        this.getUserList()
      }
      this.form.inspectionUserId = this.form.inspectionUserId
        ? this.form.inspectionUserId.split(',').map(id => Number(id))
        : []
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 处理多选的巡检人 ID
          const formData = { ...this.form }
          if (Array.isArray(formData.inspectionUserId)) {
            formData.inspectionUserId = formData.inspectionUserId.join(',')
          }

          if (formData.id != null) {
            updateLog(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addLog(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delLog(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleExport() {
      request({
        url: `/gemho/place/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>
