<template>
  <div class="app-container">
    <div class="btn-condition">
      <div class="condition-left" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="二维码状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="dict in dict.type.qrcode_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="primary-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
        </div>
        <div class="cancel-btn">
          <el-button
            type="cancel"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div class="primary-btn" v-hasPermi="['device:qr:create']">
          <el-button
            type="primary"
            icon="el-icon-folder-add"
            size="mini"
            @click="handleAdd"
            >批量生成二维码</el-button
          >
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="success-btn" v-hasPermi="['device:qr:edit']">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            >修改</el-button
          >
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="delete-btn" v-hasPermi="['device:qr:remove']">
          <el-button
            type="delete"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </div>
      </el-col>
      <!-- <el-col :span="1.5">
        <div class="warning-btn" v-hasPermi="['system:post:export']">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </div>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="二维码序列号" align="center" prop="serialNum" />
      <el-table-column label="二维码图片" align="center" prop="picContent">
        <template slot-scope="scope">
          <div
            @click="goPreView(scope.row.picContent)"
            style="
              width: 100%;
              height: 30px;
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: center;
              cursor: pointer;
            "
          >
            <img
              style="height: 100%"
              v-if="scope.row.picContent"
              :src="imgUrl + scope.row.picContent"
              alt="Base64 Image"
            />
            <span v-else></span>
          </div>
          <!-- <div class="success-btn">
            <el-button
              type="success"
              size="mini"
              @click="goPreView(scope.row.picContent)"
              >预览</el-button
            >
          </div> -->
        </template>
      </el-table-column>
      <el-table-column
        label="关联设备ID"
        align="center"
        prop="deviceLedgerId"
      />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="绑定时间" align="center" prop="bindTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bindTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="二维码状态" align="center" prop="status">
        <template slot-scope="scope">
          <!-- 包裹 dict-tag 组件，根据状态绑定不同的类名 -->
          <span :class="getStatusClass(scope.row.status)">
            <dict-tag
              :options="dict.type.qrcode_status"
              :value="scope.row.status"
            />
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:qr:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:qr: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" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row type="flex" justify="center">
          <el-col :span="24">
            <el-form-item label="二维码序列号" prop="serialNum">
              <el-input v-model="form.serialNum" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="绑定时间" prop="bindTime">
              <el-date-picker
                v-model="form.bindTime"
                type="date"
                disabled
                value-format="yyyy-MM-dd"
                placeholder=""
              >
              </el-date-picker>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceLedgerId">
              <el-select
                v-model="form.deviceLedgerId"
                placeholder="请选择设备名称"
                clearable
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="item in devices"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                /> </el-select></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="二维码状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.qrcode_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 二维码预览弹框 -->
    <el-dialog
      title="二维码预览"
      :visible.sync="isCodePreview"
      append-to-body
    >
      <div class="dialog-img">
        <img class="qrCodeImg" :src="codePreViewUrl" alt="Base64 Image" />
      </div>
    </el-dialog>
    <!-- 批量生成二维码弹框 -->
    <el-dialog
      title="批量生成二维码"
      :visible.sync="isMoreqrCode"
      append-to-body
    >
      <el-form
        ref="qrCodeForm"
        :model="qrCodeForm"
        :rules="qrCodeForms"
      >
        <el-row type="flex" justify="center">
          <el-col :span="24">
            <el-form-item label="二维码个数" prop="qrNum">
              <el-input
                v-model="qrCodeForm.qrNum"
                placeholder="请输入小于50的正整数"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isMoreqrCode = false">取 消</el-button>
        <el-button type="primary" @click="submitqrCodeForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCode,
  codeList,
  delCode,
  createCode,
  updateCode,
} from "@/api/device/qrCode";
import { ledgerList } from "@/api/device/ledger";
import { imgUrl } from "@/utils/global";
export default {
  name: "qrCode",
  dicts: ["qrcode_status", "sys_device_type"],
  data() {
    return {
      timeArr: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网关表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "请选择二维码状态", trigger: "blur" },
        ],
      },
      isCodePreview: false, //预览
      imgUrl: "",
      codePreViewUrl: "",
      isMoreqrCode: false, //批量生成二维码
      qrCodeForm: {},
      qrCodeForms: {
        qrNum: [
          { required: true, message: "二维码个数不能为空", trigger: "blur" },
        ],
      },
      devices: [], //设备列表
    };
  },
  created() {
    this.getDevices();
    this.getList();
  },
  methods: {
    // 查询设备列表
    getDevices() {
      let data = {
        pageNum: 1,
        pageSize: 1000000,
      };
      ledgerList(data).then((response) => {
        this.devices = response.rows;
      });
    },
    /** 查询二维码列表 */
    getList() {
      this.imgUrl = imgUrl;
      this.loading = true;
      codeList(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表格字典时候动态类
    getStatusClass(status) {
      switch (status) {
        case 0:
          return "status-green";
        case 1:
          return "status-red";
        default:
          return "";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.form.id = "";
    },
    handleDeviceChange(selectedValue) {
      // 通过选中的 value 找到对应的 label
      const selectedItem = this.devices.find(
        (item) => item.id === selectedValue
      );
      if (selectedItem) {
        const selectedLabel = selectedItem.deviceName;
        console.log("选中的 value:", selectedValue);
        console.log("选中的 label:", selectedLabel);
        // 在这里可以进行其他操作，比如发送请求等
        this.form.deviceLedgerId = selectedValue;
        this.form.deviceName = selectedLabel;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        serialNum: "",
        picContent: "",
        deviceLedgerId: "",
        deviceName: "",
        bindTime: "",
        status: "",
        remark: "",
      };
      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.isMoreqrCode = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.id = "";
      const ledgerId = row.id || this.ids;
      console.log("");
      getCode(ledgerId).then((response) => {
        // this.form = response.data;
        this.form = {
          id: response.data.id,
          serialNum: response.data.serialNum,
          picContent: response.data.picContent,
          deviceLedgerId: response.data.deviceLedgerId,
          deviceName: response.data.deviceName,
          bindTime: response.data.bindTime,
          status:
            response.data.status !== null
              ? response.data.status.toString()
              : null,
          remark: response.data.remark,
        };
        this.open = true;
        this.title = "修改二维码信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCode(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
          }
        }
      });
    },
    // 批量生成二维码
    submitqrCodeForm: function () {
      this.$refs["qrCodeForm"].validate((valid) => {
        if (valid) {
          console.log("新增参数", this.qrCodeForm);
          createCode(this.qrCodeForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.isMoreqrCode = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const qrIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除二维码编号为"' + qrIds + '"的数据项？')
        .then(function () {
          return delCode(qrIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/gateway/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
    // 预览二维码
    goPreView(item) {
      this.codePreViewUrl = "";
      console.log("二维码url", item);
      this.isCodePreview = true;
      this.codePreViewUrl = this.imgUrl + item;
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-img {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .qrCodeImg {
    width: 150px;
    height: 150px;
  }
}
.status-green {
  color: rgb(7, 214, 110);
}
.status-red {
  color: red;
}
</style>
<style scoped lang="scss">
/* 媒体查询，适配大于2000px分辨率的大屏样式 - element样式 */
@media (max-width: 2000px) {
  ::v-deep .el-dialog {
    width: 500px !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 150px !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
@media (min-width: 2000px) {
  ::v-deep .el-dialog {
    width: 5rem !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 1.5rem !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
</style>
