<!--
 * @Author: SunTao 328867980@qq.com
 * @Date: 2024-11-04 10:54:59
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2025-01-06 13:18:09
 * @FilePath: \znxjxt-ui\src\views\xj\inspection\disease-management\components\merge-dialog.vue
 * @Description: 病害管理-合并病害弹窗
-->

<template>
  <div class="content">
    <div class="merge-form">
      <el-form
        :model="mergeForm"
        ref="mergeForm"
        size="small"
        :inline="true"
        label-width="5rem"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="道路名称" prop="segmentName">
              <el-select
                v-model="mergeForm.segmentName"
                placeholder="请选择路段"
                clearable
              >
                <el-option
                  v-for="item in segmentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采集时间" prop="dateTime">
              <el-date-picker
                :style="{ width: '16rem' }"
                v-model="dateTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病害类型" prop="defectType">
              <el-cascader
                v-model="paramsDefectType"
                :options="tableDefect"
                :props="{
                  checkStrictly: true,
                  emitPath: true,
                  children: 'subTypes',
                }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="公里桩" prop="stakeRange">
              <el-input
                v-model="mergeForm.stakeStart"
                placeholder="起始公里桩"
                style="width: 7rem"
                clearable
              />
              <span style="margin: 0 5px">-</span>
              <el-input
                v-model="mergeForm.stakeEnd"
                placeholder="终止公里桩"
                style="width: 7rem"
                clearable
              />
              <el-tooltip
                class="item"
                effect="dark"
                content="格式为K0000+000"
                placement="top"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="快照id" prop="snapshotId">
              <el-input
                v-model="mergeForm.snapshotId"
                placeholder="请填写快照id"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病害id" prop="id">
              <el-input
                v-model="mergeForm.id"
                placeholder="请填写病害id"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8" style="padding-left: 2rem">
            <el-form-item label="" label-width="2rem">
              <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-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="merge-table">
      <el-table
        ref="defectTable"
        v-loading="loading"
        :data="defectMergeList"
        @select="handleSelectionChange"
        @select-all="handleSelectAll"
        style="width: 100%"
        height="30rem"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="路段名称" align="center" prop="segmentName" />
        <el-table-column label="采集时间" align="center" prop="createdTime">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.createdTime).toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column label="病害类型" align="center" prop="defectTypeName">
        </el-table-column>
        <el-table-column label="病害状态" align="center" prop="state">
          <template slot-scope="scope">
            <span>{{ filterState(scope.row.state) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="校验状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <span>{{
              scope.row.dataStatus
                ? scope.row.dataStatus === 1
                  ? "未校验"
                  : "已校验"
                : ""
            }}</span>
          </template>
        </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" />
        <el-table-column label="病害面积" align="center" prop="targetArea" />
        <el-table-column label="预警标识" align="center" prop="warningFlag">
          <template slot-scope="scope">
            <el-tag :type="scope.row.warningFlag === 1 ? 'danger' : 'success'">
              {{ scope.row.warningFlag === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
      </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>
    </div>
    <div class="merge-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </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 { listDefect, mergeDefect } from "@/api/xj/disease";
export default {
  name: "MergeDialog",
  props: {
    segmentList: {
      type: Array,
      default: () => [],
    },
    tableDefect: {
      type: Array,
      default: () => [],
    },
    defectStatus: {
      type: Array,
      default: () => [],
    },
    mergeItem: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      // 表单绑定
      mergeForm: {
        // 道路名称绑定
        segmentName: "",
        // 病害类型绑定
        classType: "",
        defectType: "",
        // 公里桩绑定
        stakeStart: "",
        stakeEnd: "",
        // 快照id
        snapshotId: "",
        // 病害id
        id: "",
      },
      // 查询表单绑定
      searchForm: {},
      // 病害类型绑定
      paramsDefectType: [],
      // 采集时间绑定
      dateTime: [],
      // 列表数据绑定
      defectMergeList: [],
      // 表格加载状态
      loading: false,
      // 列表选中数据
      checkIds: [],
      // 分页绑定
      pagination: {
        page: 1,
        size: 10,
      },
      // 数据总数
      tableTotal: 0,
      // 查看图片大图弹窗显隐控制
      showImageDialog: false,
      // 查看大图片路径
      currentImageItem: "",
      // 图片病害位置信息
      rects: [],
      // 合并病害弹窗显隐控制
      mergeVisibleDialog: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /* 过滤列表病害类型 */
    filterDefect(value) {
      let a = null;
      [a] = this.tableDefect.filter((item) => {
        return item.value === value;
      });
      if (a) {
        return a.label;
      }
    },

    /* 过滤列表病害状态 */
    filterState(value) {
      let a = null;
      [a] = this.defectStatus.filter((item) => {
        return item.value === value;
      });
      if (a) {
        return a.label;
      }
    },

    /* 搜索事件 */
    handleQuery() {
      const data = {
        ...this.mergeForm,
        classType: this.paramsDefectType ? this.paramsDefectType[0] : "",
        defectType: this.paramsDefectType
          ? this.paramsDefectType.length > 1
            ? this.paramsDefectType[1]
            : ""
          : "",
      };
      this.searchForm = JSON.parse(JSON.stringify(data));
      this.getList();
    },

    /* 重置事件 */
    resetQuery() {
      this.searchForm = {};
      this.mergeForm = {
        // 道路名称绑定
        segmentName: "",
        // 病害类型绑定
        defectType: "",
        classType: "",
        type: "",
        // 公里桩绑定
        stakeStart: "",
        stakeEnd: "",
        // 快照id
        snapshotId: "",
        // 病害id
        id: "",
      };
      this.dateTime = [];
      this.getList();
    },

    /** 查询缺陷列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.searchForm,
        ...this.pagination,
        startTime: this.dateTime ? this.dateTime[0] : "",
        endTime: this.dateTime ? this.dateTime[1] : "",
      };
      listDefect(params)
        .then((response) => {
          this.defectMergeList = response.rows;
          this.tableTotal = response.total;
          this.loading = false;
          this.$nextTick(() => {
            this.handleListSelect();
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /* 列表选中事件 */
    handleSelectionChange(selection, row) {
      if (selection.length > 1) {
        this.$refs.defectTable.clearSelection();
        this.$refs.defectTable.toggleRowSelection(selection.pop());
        this.checkIds = [row.id];
      } else if (selection.length === 0) {
        this.checkIds = [];
      } else {
        this.checkIds = [row.id];
      }
    },

    /* 列表全选事件 */
    handleSelectAll() {
      this.$refs.defectTable.clearSelection();
    },

    /* 列表框回显勾选 */
    handleListSelect() {
      const { defectTable } = this.$refs;
      if (defectTable) {
        this.defectMergeList.forEach((temp) => {
          defectTable.toggleRowSelection(temp, this.checkIds.includes(temp.id));
        });
      }
    },

    /* 点击取消事件 */
    cancel() {
      this.$emit("mergeCancel");
    },

    /* 点击确认事件 */
    submitForm() {
      const data = {
        aimSnapshotId: this.checkIds[0],
        snapshotId: this.mergeItem.snapshotId,
      };
      mergeDefect(data).then(({ code, msg }) => {
        if (code === 200) {
          this.cancel();
          this.$modal.msgSuccess(msg);
        } else {
          this.$modal.msgWarning(msg);
        }
      });
    },

    /* 切换分页 */
    handleCurrentChange(arg) {
      this.pagination.page = arg;
      this.getList();
    },

    /* 切换每条/页 */
    handleSizeChange(arg) {
      this.pagination.size = arg;
      this.getList();
    },

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

    /* 图片位置信息获取 */
    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],
        },
      ];
    },

    /* 图片红框位置 */
    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",
      };
    },

    /* 关闭查看图片弹窗 */
    imgCancel() {
      this.showImageDialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 45rem;

  .merge-form {
    width: 100%;
    height: 20%;
  }

  .merge-table {
    width: 100%;
    height: 75%;

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

  .merge-footer {
    width: 100%;
    height: 5%;
    display: flex;
    justify-content: flex-end;
  }
}

/* 查看大图弹窗 */
.image-container {
  position: relative;
  width: 100%;
  height: 80%;
  display: flex;
  flex-direction: column;
  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>
