<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="巡检点" prop="inspectionPoint">
        <el-input
          v-model="queryParams.inspectionPoint"
          placeholder="请输入巡检点"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员类型" prop="inspectionPointType">
        <el-select
          v-model="queryParams.inspectionPointType"
          placeholder="请选择人员类型"
          clearable
        >
          <el-option
            v-for="dict in inspection_point_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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-form-item>
    </el-form>

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

    <el-table
      v-loading="loading"
      :data="manageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="巡检点" align="center" prop="inspectionPoint" />
      <el-table-column
        label="巡检要求"
        align="center"
        prop="inspectionRequirements"
      />
      <!-- 新增：人员类型展示 -->
      <el-table-column
        label="人员类型"
        align="center"
        prop="inspectionPointType"
      >
        <template #default="scope">
          <dict-tag
            :options="inspection_point_type"
            :value="scope.row.inspectionPointType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="巡检点状态"
        align="center"
        prop="inspectionStatus"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.inspectionStatus"
            :active-value="'1'"
            :inactive-value="'0'"
            active-text="开"
            inactive-text="关"
            class="ml-2"
            @change="switchChange(scope.row)"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </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="['inspection:manage:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inspection:manage:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            icon="FullScreen"
            @click="getQRCode(scope.row)"
            v-hasPermi="['inspection:manage:code']"
            >生成二维码</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="manageRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="巡检点" prop="inspectionPoint">
          <el-input v-model="form.inspectionPoint" placeholder="请输入巡检点" />
        </el-form-item>
        <el-form-item label="巡检要求" prop="inspectionRequirements">
          <el-input
            v-model="form.inspectionRequirements"
            placeholder="请输入巡检要求"
            type="textarea"
          />
        </el-form-item>
        <!-- 新增：人员类型选择 -->
        <el-form-item label="人员类型" prop="inspectionPointType">
          <el-select
            v-model="form.inspectionPointType"
            placeholder="请选择人员类型"
          >
            <el-option
              v-for="dict in inspection_point_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检点状态" prop="inspectionStatus">
          <el-select
            v-model="form.inspectionStatus"
            placeholder="请选择巡检点状态"
          >
            <el-option
              v-for="dict in inspection_point_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </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>
    <QRCodeDownloader
      ref="qrCodeDownloaderRef"
      @qrCodeGenerated="handleQRCodeGenerated"
    ></QRCodeDownloader>
  </div>
</template>

<script setup name="Manage">
import {
  listManage,
  getManage,
  delManage,
  addManage,
  updateManage,
} from "@/api/inspection/manage";

import QRCodeDownloader from "@/components/QRCode/QRCodeDownloader.vue";
import { ref, onMounted, onUnmounted, nextTick } from "vue";

const { proxy } = getCurrentInstance();
const { inspection_point_status } = proxy.useDict("inspection_point_status");
// 新增：人员类型字典
const { inspection_point_type } = proxy.useDict("inspection_point_type");
// 子组件
const qrCodeDownloaderRef = ref(null);

const manageList = 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 dateRange = ref([]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址

// 多选导出的数组
const inspectionPoint = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inspectionPoint: null,
    inspectionPointType: null,
  },
  rules: {
    inspectionPoint: [
      { required: true, message: "巡检点不能为空", trigger: "blur" },
    ],
    inspectionRequirements: [
      { required: true, message: "巡检要求不能为空", trigger: "blur" },
    ],
    // 新增：类型为必填
    inspectionPointType: [
      { required: true, message: "人员类型不能为空", trigger: "change" },
    ],
    inspectionStatus: [
      { required: true, message: "巡检点状态不能为空", trigger: "change" },
    ],
  },
});

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

// 开关
function switchChange(data) {
  console.log(data);
  updateManage(data).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
    getList();
  });
}

/** 查询巡检点管理列表 */
function getList() {
  loading.value = true;
  listManage(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      manageList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    },
  );
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    inspectionPoint: null,
    inspectionRequirements: null,
    // 新增：重置类型字段
    inspectionPointType: null,
    inspectionStatus: null,
    inspectionQrCode: null,
  };
  proxy.resetForm("manageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

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

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log(selection);
  ids.value = selection.map((item) => item.id);
  inspectionPoint.value = selection.map((item) => item.inspectionPoint);
  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;
  getManage(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改巡检点管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["manageRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateManage(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addManage(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 delManage(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 生成二维码 */
function getQRCode(row) {
  if (
    qrCodeDownloaderRef.value &&
    qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent
  ) {
    qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent(
      row.id + "",
      row.inspectionPoint,
    );
    //qrCodeDownloaderRef.value.Download(row.inspectionPoint);
  }
}
/** 生成二维码 */
// function getQRCode(row) {
//   if (
//     qrCodeDownloaderRef.value &&
//     qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent
//   ) {
//     qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent(row.id + "", row.inspectionPoint).then(() => {
//     qrCodeDownloaderRef.value.Download(row.inspectionPoint);
//   });
//   }
// }

// 多选二维码
function getQRCodes() {
  // 防呆：未选择任何项时提示
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgWarning("请先选择需要生成二维码的巡检点");
    return;
  }
  // 逐个生成二维码：文本内容使用巡检点ID字符串，下方文字使用巡检点名称
  ids.value.forEach((id, index) => {
    if (
      qrCodeDownloaderRef.value &&
      qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent
    ) {
      qrCodeDownloaderRef.value.generateQRCodeWithTextAndNotifyParent(
        String(id),
        inspectionPoint.value[index],
      );
    }
  });
}

// 获取二维码
function handleQRCodeGenerated(img) {
  console.log("绘制二维码成功");
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "inspection/manage/export",
    {
      ...proxy.addDateRange(queryParams.value, dateRange.value),
    },
    `manage_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
