<!--
 * @Author: SunTao 328867980@qq.com
 * @Date: 2024-12-02 11:20:55
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-12-27 14:15:53
 * @FilePath: \znxjxt-ui\src\views\xj\inspection\task-management\components\task-view.vue
 * @Description: 巡检信息-巡检任务-查看新增病害
-->
<template>
  <div class="task-view">
    <el-form
      class="viewForm"
      ref="viewForm"
      :model="viewForm"
      :rules="viewFormRules"
      label-width="5rem"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="病害类型">
            <el-cascader
              v-model="viewForm.defectType"
              :options="defectCascaderList"
              :props="{
                checkStrictly: false,
                emitPath: false,
                children: 'subTypes',
              }"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始桩号" prop="stakeStart">
            <el-input
              v-model="viewForm.stakeStart"
              placeholder="K00000+000"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束桩号" prop="stakeEnd">
            <el-input
              v-model="viewForm.stakeEnd"
              placeholder="K00000+000"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <!-- 数据表格 -->
    <el-table
      ref="defectTable"
      v-loading="loading"
      :data="defectList"
      style="width: 100%"
      height="35rem"
    >
      <el-table-column label="病害类型" align="center" prop="defectTypeName">
      </el-table-column>
      <el-table-column label="开始桩号" align="center" prop="stakeStart" />
      <el-table-column label="结束桩号" align="center" prop="stakeEnd" />
      <el-table-column label="病害图片" align="center" prop="media">
        <template slot-scope="scope">
          <img
            @click="showScreenImg(scope.row)"
            height="50"
            :src="scope.row.mediaUrl"
          />
        </template>
      </el-table-column>
      <el-table-column label="病害长度" align="center" prop="targetLen">
        <template slot-scope="scope">
          {{ scope.row.targetLen * 1 <= 0 ? "" : `${scope.row.targetLen}米` }}
        </template>
      </el-table-column>
      <el-table-column label="病害面积" align="center" prop="targetArea" />
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-part">
      <el-pagination
        background
        :current-page.sync="pagination.page"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size.sync="pagination.size"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
      >
      </el-pagination>
    </div>

    <!-- 查看图片大图 -->
    <el-dialog
      title="查看图片"
      :visible.sync="showImageDialog"
      width="85rem"
      append-to-body
      destroy-on-close
      @close="imgCancel"
    >
      <div class="image-container" ref="imageContainer">
        <img
          :src="currentImageItem.mediaUrl"
          alt="Main Image"
          ref="mainImage"
          @load="updateRects"
        />
        <div
          v-for="(rect, index) in rects"
          :key="index"
          class="rect-overlay"
          :style="getRectStyle(rect)"
        ></div>
        <div class="rect-image">
          采集时间:
          {{
            new Date(currentImageItem.createdTime).toLocaleString()
          }}
          起始桩号： {{ currentImageItem.stakeStart || "暂无数据" }} 终止桩号：
          {{ currentImageItem.stakeEnd || "暂无数据" }}
          病害类型：
          {{ currentImageItem.defectTypeName || "暂无数据" }}
          病害面积：{{ currentImageItem.targetArea }}平方米 病害长度：{{
            currentImageItem.targetLen * 1 <= 0
              ? "暂无数据"
              : `${currentImageItem.targetLen}米`
          }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTaskDefectDetail } from "@/api/xj/task";
export default {
  name: "TaskView",
  components: {},
  props: {
    defectCascaderList: {
      type: Array,
      default: () => [],
    },
    dialogItem: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      // 查看新增病害表单
      viewForm: {
        taskId: "",
        defectType: "",
        stakeStart: "",
        stakeEnd: "",
      },
      // 查看新增病害表单验证
      viewFormRules: {
        stakeStart: [
          {
            required: false,
            pattern: /^K\d{4}\+\d{3}$/,
            trigger: "blur",
            message: "请正确输入开始桩号",
          },
        ],
        stakeEnd: [
          {
            required: false,
            pattern: /^K\d{4}\+\d{3}$/,
            trigger: "blur",
            message: "请正确输入结束桩号",
          },
        ],
      },
      // 病害类型列表
      defectTypeList: [],
      // 列表加载状态
      loading: false,
      // 列表数据绑定
      defectList: [],
      // 分页-列表总数
      tableTotal: 0,
      // 分页-页数页码
      pagination: {
        page: 1,
        size: 10,
      },
      // 查看图片大图弹窗显隐控制
      showImageDialog: false,
      // 查看大图片路径
      currentImageItem: "",
      // 图片病害位置信息
      rects: [],
    };
  },
  watch: {
    dialogItem: {
      handler(val) {
        this.viewForm.taskId = val.extId;
        this.searchForm = JSON.parse(JSON.stringify(this.viewForm));
        this.getDefectList();
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    /**
     * @description: 获取列表数据
     * @return {*}
     */
    getDefectList() {
      const data = {
        ...this.searchForm,
        ...this.pagination,
      };
      getTaskDefectDetail(data).then(({ code, rows, total }) => {
        if (code === 200) {
          this.defectList = rows;
          this.tableTotal = total;
        }
      });
    },

    /**
     * @description: 点击搜索事件
     * @return {*}
     */
    handleQuery() {
      this.$refs.viewForm.validate((valid) => {
        if (valid) {
          this.searchForm = JSON.parse(JSON.stringify(this.viewForm));
          this.getDefectList();
        }
      });
    },

    /**
     * @description: 点击重置事件
     * @return {*}
     */
    resetQuery() {
      this.searchForm = {
        taskId: this.dialogItem.extId,
      };
      this.viewForm = {
        taskId: this.dialogItem.extId,
        defectType: "",
        stakeStart: "",
        stakeEnd: "",
      };
      this.getDefectList();
    },

    /**
     * @description: 打开查看图片弹窗
     * @param {*} item
     * @return {*}
     */
    showScreenImg(item) {
      this.currentImageItem = item;
      this.showImageDialog = true;
    },

    /**
     * @description: 图片位置信息获取
     * @param {*}
     * @return {*}
     */
    updateRects() {
      this.rects = [];
      this.rectsItem = {};
      const image = this.$refs.mainImage;
      const rects = this.currentImageItem?.rect?.split(",").map(Number) || [];
      this.rects = [
        {
          left: rects[0],
          top: rects[1],
          width: rects[2],
          height: rects[3],
        },
      ];
      // this.rectsItem = this.defectData[this.currentIndex];
    },

    /**
     * @description: 图片红框位置
     * @param {*} { left, top, width, height }
     * @return {*}
     */
    getRectStyle({ left, top, width, height }) {
      const image = this.$refs.mainImage;
      const container = this.$refs.imageContainer;
      if (!image || !container) return {};

      const scaleX = container.clientWidth / image.naturalWidth;
      const scaleY = container.clientHeight / image.naturalHeight;
      const scale = Math.min(scaleX, scaleY);

      const renderedWidth = image.naturalWidth * scale;
      const renderedHeight = image.naturalHeight * scale;

      const offsetX = (container.clientWidth - renderedWidth) / 2;
      const offsetY = (container.clientHeight - renderedHeight) / 2;

      return {
        position: "absolute",
        left: `${left * scale + offsetX}px`,
        top: `${top * scale + offsetY}px`,
        width: `${width * scale}px`,
        height: `${height * scale}px`,
        border: "2px solid #FF0000",
        boxSizing: "border-box",
      };
    },

    /**
     * @description: 关闭查看图片弹窗
     * @param {*}
     * @return {*}
     */
    imgCancel() {
      this.showImageDialog = false;
      this.currentImageItem = {};
      this.rects = [];
    },

    /**
     * @description: 切换分页
     * @param {*} arg
     * @return {*}
     */
    handleCurrentChange(arg) {
      this.pagination.page = arg;
      this.getDefectList();
    },

    /**
     * @description: 切换每条/页
     * @param {*} arg
     * @return {*}
     */
    handleSizeChange(arg) {
      this.pagination.size = arg;
      this.getDefectList();
    },
  },
};
</script>

<style lang="scss" scoped>
.task-view {
  width: 100%;
  height: 100%;
}

/* 分页样式 */
.pagination-part {
  width: 100%;
  display: flex;
  padding-top: 1rem;
  justify-content: flex-end;
}

/* 查看大图弹窗 */
.image-container {
  position: relative;
  width: 100%;
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.rect-overlay {
  position: absolute;
  pointer-events: none;
  border: 2px solid red;
}

// 图片信息
.rect-image {
  width: 90%;
  position: absolute;
  top: 0;
  font-size: 1.2rem;
  color: #ffffff;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
