<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <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="inspectorId">
        <el-input
          v-model="queryParams.inspectorId"
          placeholder="请输入巡检人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 新增：巡检类型字典选择 -->
      <el-form-item label="巡检类型" prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择巡检类型" clearable style="width: 240px">
          <el-option v-for="dict in inspection_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="巡检时间" prop="inspectionTime" 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:abnormal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inspection:abnormal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inspection:abnormal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['inspection:abnormal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="abnormalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="巡检点地址" align="center" prop="inspectionPoint" />
      <el-table-column label="巡检人" align="center" prop="inspectorId" />
      <!-- 修改：巡检类型显示字典标签 -->
      <el-table-column label="巡检类型" align="center" prop="inspectionType">
        <template #default="scope">
          <dict-tag :options="inspection_type" :value="scope.row.inspectionType" />
        </template>
      </el-table-column>
      <el-table-column label="巡检时间" align="center" prop="inspectionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="巡检图片" align="center" prop="inspectionImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.inspectionImg" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Search" @click="handleUpdate(scope.row)"
            v-hasPermi="['inspection:abnormal:query']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['inspection:abnormal:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['inspection:abnormal: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="abnormalRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="巡检点地址" prop="inspectionPoint">
          <el-input v-model="form.inspectionPoint" placeholder="请输入巡检点地址" disabled="true"/>
        </el-form-item>
        <el-form-item label="巡检人" prop="inspectorId">
          <el-input v-model="form.inspectorId" placeholder="请输入巡检人" disabled="true"/>
        </el-form-item>
        <!-- 新增：表单中的巡检类型字典选择 -->
        <el-form-item label="巡检类型" prop="inspectionType">
          <el-select v-model="form.inspectionType" placeholder="请选择巡检类型" disabled="true">
            <el-option v-for="dict in inspection_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检时间" prop="inspectionTime">
          <el-date-picker clearable
            v-model="form.inspectionTime"
            type="date" disabled="true"
            value-format="YYYY-MM-DD"
            placeholder="请选择巡检时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="巡检图片" prop="inspectionImg">
          <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleImageUpload">
          <template #tip>
          <div class="el-upload__tip">
          <!-- 展示已上传的图片 -->
          <div v-if="form.inspectionImg && typeof form.inspectionImg === 'string'" style="display: flex; flex-wrap: wrap;">
            <img
              v-for="(url, index) in getFullImageUrls(form.inspectionImg)"
              :key="index"
              :src="url"
              style="max-width: 200px; max-height: 200px; margin: 4px;"
              :alt="'巡检图片' + index"
            />
          </div>
          <!-- 没有图片时显示提示 -->
          <span v-else>暂无图片</span>
        </div>
        </template>
        </el-upload>
      </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled="true"/>
        </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="Abnormal">
import { listAbnormal, getAbnormal, delAbnormal, addAbnormal, updateAbnormal } from "@/api/inspection/abnormal";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import { parseTime } from '@/utils/ruoyi';
import { addWatermarkToImage } from '@/utils/watermark';
import request from '@/utils/request'

const { proxy } = getCurrentInstance();
// 使用全局字典获取方式，保持与其它页面一致
const { inspection_type } = proxy.useDict('inspection_type');

const abnormalList = 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("");
// 基础路径，用于拼接图片完整URL
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inspectionPoint: null,
    inspectorId: null,
    inspectionType: null,
    inspectionTime: null,
    inspectionImg: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
// 获取图片的完整URL（与巡检记录一致）
function getFullImageUrls(relativePaths) {
  if (!relativePaths) return [];
  const paths = typeof relativePaths === 'string' ? relativePaths.split(',') : relativePaths;
  return paths.map(path => `${baseUrl}${path.trim()}`);
}
// 处理图片上传，加水印并生成预览（与巡检记录一致）
async function handleImageUpload(file) {
  try {
    if (!file || !file.raw) {
      throw new Error('无效的文件对象');
    }
    const watermarkText = `${form.value.inspectionPoint || '未命名地点'} ${form.value.inspectionTime || '未设置时间'}`;
    const watermarkedFile = await addWatermarkToImage(file.raw, watermarkText, {
      font: 'bold 48px Arial',
      color: 'rgba(0, 0, 0, 0.7)'
    });
    const previewUrl = URL.createObjectURL(watermarkedFile);
    form.value.inspectionImg = { raw: watermarkedFile, name: watermarkedFile.name, url: previewUrl };
  } catch (error) {
    console.error('水印处理失败:', error);
    proxy.$modal.msgError('图片处理失败: ' + error.message);
  }
}

/** 查询巡检异常列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  proxy.addDateRange(queryParams.value, dateRange.value);
  listAbnormal(queryParams.value).then(response => {
    abnormalList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    inspectionPoint: null,
    inspectorId: null,
    inspectionType: null,
    inspectionTime: null,
    inspectionImg: null,
    remark: null
  };
  proxy.resetForm("abnormalRef");
}

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

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

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

/** 提交按钮 */
async function submitForm() {
  proxy.$refs["abnormalRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 克隆数据以避免直接修改响应式对象
        const dataToSubmit = { ...form.value };

        // 如果是新选择的图片对象，先上传到服务器换取字符串路径
        if (dataToSubmit.inspectionImg && typeof dataToSubmit.inspectionImg === 'object' && dataToSubmit.inspectionImg.raw) {
          const formData = new FormData();
          formData.append('file', dataToSubmit.inspectionImg.raw);
          const res = await request({
            url: '/common/upload',
            method: 'post',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
          });
          if (res.code !== 200) {
            throw new Error(res.msg || '图片上传失败');
          }
          // RuoYi 通用上传返回 fileName（相对路径），后端字段期望 String
          dataToSubmit.inspectionImg = res.fileName;
        }

        if (dataToSubmit.id != null) {
          await updateAbnormal(dataToSubmit);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addAbnormal(dataToSubmit);
          proxy.$modal.msgSuccess("新增成功");
        }

        open.value = false;
        getList();
      } catch (error) {
        console.error('提交失败:', error);
        proxy.$modal.msgError('操作失败: ' + (error.message || '未知错误'));
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除巡检异常编号为"' + _ids + '"的数据项？').then(function() {
    return delAbnormal(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('inspection/abnormal/export', {
    ...queryParams.value
  }, `abnormal_${new Date().getTime()}.xlsx`)
}

getList();
</script>
