<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="巡检时间" style="width: 308px">
        <el-date-picker v-model="daterangeInspectionTime" 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" disabled="true"
          v-hasPermi="['inspection:record:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['inspection:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['inspection:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['inspection:record:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="id" width="80" />
      <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} {h}:{i}:{s}') }}</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" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Search" @click="handleUpdate(scope.row)"
            v-hasPermi="['inspection:record:query']">查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['inspection:record: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="recordRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="巡检点地址" prop="inspectionPoint">
          <el-input v-model="form.inspectionPoint" 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" value-format="YYYY-MM-DD"
            placeholder="请选择巡检时间" disabled="true"></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" v-if="form.remark != null">
          <span>{{ form.remark }}</span>
        </el-form-item>
        <el-form-item label="创建者：" v-if="form.createBy">
          <span>{{ form.createBy }}</span>
        </el-form-item>
        <el-form-item label="创建时间：" v-if="form.createTime">
          <span>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
        <el-form-item label="更新时间：" v-if="form.updateTime">
          <span>{{ parseTime(form.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </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="Record">
//引入新添加方法 --知无涯
import {
  addRecord,
  delRecord,
  getRecord,
  listRecord,
  updateRecord
} from "@/api/inspection/record";
import { addWatermarkToImage } from '@/utils/watermark';
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
//时间处理格式
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance();
const { inspection_type } = proxy.useDict("inspection_type");

const recordList = 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 daterangeInspectionTime = ref([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API; // 基础路径(/dev-api)

// 获取图片的完整URL
function getFullImageUrls(relativePaths) {
  if (!relativePaths) return [];

  // 如果是字符串，按逗号分割成数组
  const paths = typeof relativePaths === 'string' ? relativePaths.split(',') : relativePaths;

  return paths.map(path => {
    // 去除空格并拼接 baseUrl
    return `${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)' // 黑色,70%不透明度
    });

    console.log('原始文件:', watermarkedFile);
    // 创建预览URL
    const previewUrl = URL.createObjectURL(watermarkedFile);
    console.log('水印处理成功，预览URL:', previewUrl);
    // 更新表单数据
    form.value.inspectionImg = {
      raw: watermarkedFile,
      name: watermarkedFile.name,
      url: previewUrl
    };
    console.log('form.value.inspectionImg:', form.value.inspectionImg);
  } catch (error) {
    console.error("水印处理失败:", error);
    proxy.$modal.msgError("图片处理失败: " + error.message);
  }
}


/** 提交按钮    --知无涯 */
async function submitForm() {
  proxy.$refs["recordRef"].validate(async (valid) => {
    if (valid) {
      try {
        let fileToUpload = null;

        // 处理图片数据
        if (form.value.inspectionImg) {
          if (typeof form.value.inspectionImg === 'string') {
            // 上传图片的URL
            fileToUpload = form.value.inspectionImg;
          } else if (form.value.inspectionImg.raw instanceof File) {
            // 新上传的带水印图片
            fileToUpload = form.value.inspectionImg.raw;
          }
        }

        // 准备表单数据
        const formData = new FormData();
        formData.append('inspectionPoint', form.value.inspectionPoint);
        formData.append('inspectionType', form.value.inspectionType);
        formData.append('inspectionTime', form.value.inspectionTime);
        if (fileToUpload) {
          formData.append('file', fileToUpload);
        }

        // 提交数据
        if (form.value.id != null) {
          await updateRecord(formData);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addRecord(formData);
          proxy.$modal.msgSuccess("新增成功");
        }

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


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inspectionPoint: null,
    inspectorId: null,
    inspectorId: null,
    inspectionTime: null
  },
  // rules: {
  //   inspectionPoint: [
  //     { required: true, message: "巡检点地址不能为空", trigger: "blur" }
  //   ],
  //   inspectorId: [
  //     { required: true, message: "巡检人不能为空", trigger: "change" }
  //   ],
  //   inspectionType: [
  //     { required: true, message: "巡检类型不能为空", trigger: "change" }
  //   ],
  //   inspectionTime: [
  //     { required: true, message: "巡检时间不能为空", trigger: "blur" }
  //   ],
  //   inspectionImg: [
  //     {
  //       required: true,
  //       message: "请上传巡检图片",
  //       trigger: "change"
  //     },
  //     {
  //       validator: (rule, value, callback) => {
  //         // 如果是字符串URL(修改时原有图片)
  //         if (typeof value === 'string') {
  //           callback();
  //           return;
  //         }
  //         // 如果是文件对象
  //         const file = value?.raw || value;
  //         if (file && file.size > 5 * 1024 * 1024) {
  //           callback(new Error('图片大小不能超过5MB'));
  //         } else {
  //           callback();
  //         }
  //       },
  //       trigger: 'change'
  //     }
  //   ]
  // }
}
);

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

/** 查询巡检记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeInspectionTime.value && daterangeInspectionTime.value.length > 0) {
    queryParams.value.params["beginInspectionTime"] = daterangeInspectionTime.value[0];
    queryParams.value.params["endInspectionTime"] = daterangeInspectionTime.value[1];
  }
  listRecord(queryParams.value).then(response => {
    recordList.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: 1,
    inspectionType: null,
    inspectionTime: null,
    inspectionImg: null,
    remark: null
  };
  proxy.resetForm("recordRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  daterangeInspectionTime.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;
//   getRecord(_id).then(response => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改巡检记录";
//   });
// }

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id;
  getRecord(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看巡检记录";
  });
}



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

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

getList();
</script>
