<!--
 * @Author: SunTao 328867980@qq.com
 * @Date: 2024-11-01 13:17:41
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-11-05 09:23:11
 * @FilePath: \znxjxt-ui\src\views\xj\inspection\confirmation-management\index.vue
 * @Description: 巡检信息-病害确认
-->

<template>
  <div class="confirmation-content">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="道路名称" prop="segmentName">
        <el-select
          v-model="queryParams.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-form-item label="采集时间" prop="dateTime">
        <el-date-picker
          v-model="dateTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="病害类型" prop="defectType">
        <el-select
          v-model="queryParams.defectType"
          placeholder="请选择病害类型"
          clearable
        >
          <el-option
            v-for="item in tableDefect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="病害状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择病害状态"
          clearable
        >
          <el-option
            v-for="item in defectStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上下行" prop="inspectDirection">
        <el-select
          v-model="queryParams.inspectDirection"
          placeholder="请选择"
          clearable
        >
          <el-option label="上行" value="0" />
          <el-option label="下行" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="公里桩" prop="stakeRange">
        <el-input
          v-model="queryParams.stakeStart"
          placeholder="起始公里桩"
          style="width: 10rem"
          clearable
        />
        <span style="margin: 0 5px">-</span>
        <el-input
          v-model="queryParams.stakeEnd"
          placeholder="终止公里桩"
          style="width: 10rem"
          clearable
        />
        <el-tooltip
          class="item"
          effect="dark"
          content="格式为K0000+000"
          placement="top"
        >
          <i class="el-icon-info"></i>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="预警标识" prop="warningFlag">
        <el-select
          v-model="queryParams.warningFlag"
          placeholder="请选择"
          clearable
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="病害长度" prop="lengthRange">
        <el-input-number
          v-model="queryParams.minLen"
          controls-position="right"
          placeholder="最小长度"
          :min="0"
        ></el-input-number>
        <span style="margin: 0 5px">-</span>
        <el-input-number
          v-model="queryParams.maxLen"
          controls-position="right"
          placeholder="最大长度"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="病害面积" prop="areaRange">
        <el-input-number
          v-model="queryParams.minArea"
          controls-position="right"
          placeholder="最小面积"
          :min="0"
        ></el-input-number>
        <span style="margin: 0 5px">-</span>
        <el-input-number
          v-model="queryParams.maxArea"
          controls-position="right"
          placeholder="最大面积"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="病害id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请填写病害id"
          style="width: 10rem"
          clearable
        />
      </el-form-item>
      <el-form-item label="快照id" prop="snapshotId">
        <el-input
          v-model="queryParams.snapshotId"
          placeholder="请填写快照id"
          style="width: 10rem"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <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-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleConfirm(1)"
          >是病害
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleConfirm(0)"
          >不是病害
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-picture-outline"
          size="mini"
          @click="handleBatch()"
          >影像模式
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      ref="defectTable"
      v-loading="loading"
      :data="confirmationtList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <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="defectType">
        <template slot-scope="scope">
          <span>{{ filterDefect(scope.row.defectType) }}</span>
        </template>
      </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>

    <!-- 查看图片大图 -->
    <el-dialog
      title="查看图片"
      :visible.sync="showImageDialog"
      width="75rem"
      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>
    </el-dialog>

    <!-- 影像模式弹窗 -->
    <el-dialog
      title="影像模式"
      :visible.sync="showCheckImg"
      width="85rem"
      append-to-body
      destroy-on-close
      @close="checkCancel"
    >
      <image-dialog></image-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDefectList,
  getSegment,
  getDefectStatus,
  listDefect,
  mergeDefect,
} from "@/api/xj/confirmation";
import imageDialog from "./components/image-dialog.vue";
export default {
  components: { imageDialog },
  name: "ConfirmationManagement",
  data() {
    return {
      // 搜索表单参数
      queryParams: {
        segmentName: "",
        defectType: "",
        state: "",
        inspectDirection: "",
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: undefined,
        maxLen: undefined,
        minArea: undefined,
        maxArea: undefined,
        id: "",
        snapshotId: "",
      },
      // 查询接收表单参数
      searchForm: {},
      // 采集时间绑定
      dateTime: [],
      // 列表病害状态数据
      tableDefect: [],
      // 路段下拉选项
      segmentList: [],
      // 病害状态下拉选项
      defectStatus: [],
      // 列表数据绑定
      confirmationtList: [],
      // 非多个禁用
      multiple: true,
      // 选择框选中数据
      checkIds: [],
      // 表格数据加载状态
      loading: false,
      // 分页-页数页码
      pagination: {
        page: 1,
        size: 10,
      },
      // 分页-列表总数据
      tableTotal: 0,
      // 查看图片大图弹窗显隐控制
      showImageDialog: false,
      // 查看大图片路径
      currentImageItem: "",
      // 图片病害位置信息
      rects: [],
      // 影像模式弹窗显影控制
      showCheckImg: false,
    };
  },
  created() {
    this.getTableDefect();
    this.getSegmentList();
    this.getDefectStatusList();
    this.getTableList();
    this.getTableDefect();
  },
  methods: {
    /* 获取列表病害类型对应数据 */
    getTableDefect() {
      getDefectList().then(({ code, data }) => {
        if (code === 200) {
          this.tableDefect = data;
        }
      });
    },

    /* 获取路段下拉数据 */
    getSegmentList() {
      getSegment().then(({ code, data }) => {
        if (code === 200) {
          this.segmentList = data;
        }
      });
    },

    /* 查询病害状态下拉数据 */
    getDefectStatusList() {
      getDefectStatus().then(({ data, code }) => {
        if (code === 200) {
          this.defectStatus = data;
        }
      });
    },

    /* 过滤列表病害类型 */
    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;
      }
    },

    /* 获取列表行数据 */
    getTableList() {
      // 处理日期范围
      const params = {
        ...this.searchForm,
        ...this.pagination,
        startTime: this.dateTime ? this.dateTime[0] : "",
        endTime: this.dateTime ? this.dateTime[1] : "",
      };
      listDefect(params)
        .then(({ code, rows, total }) => {
          if (code === 200) {
            this.confirmationtList = rows;
            this.tableTotal = total;
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /* 点击搜索事件 */
    handleQuery() {
      const phonereg = /^K\d{4}\+\d{3}$/;
      if (this.queryParams.stakeStart) {
        if (phonereg.test(this.queryParams.stakeStart)) {
          this.pagination.page = 1;
          this.searchForm = JSON.parse(JSON.stringify(this.queryParams));
          this.getTableList();
        } else {
          this.$modal.msgWarning("请按照格式填写公里桩进行修改");
        }
      } else if (this.queryParams.stakeEnd) {
        if (phonereg.test(this.queryParams.stakeEnd)) {
          this.pagination.page = 1;
          this.searchForm = JSON.parse(JSON.stringify(this.queryParams));
          this.getTableList();
        } else {
          this.$modal.msgWarning("请按照格式填写公里桩进行修改");
        }
      } else {
        this.pagination.page = 1;
        this.searchForm = JSON.parse(JSON.stringify(this.queryParams));
        this.getTableList();
      }
    },

    /* 点击重置事件 */
    resetQuery() {
      this.queryParams = {
        segmentName: "",
        defectType: "",
        state: "",
        inspectDirection: "",
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: undefined,
        maxLen: undefined,
        minArea: undefined,
        maxArea: undefined,
        id: "",
        snapshotId: "",
      };
      this.searchForm = {};
      this.dateTime = [];
      this.getTableList();
    },

    /* 多选框选中数据 */
    handleSelectionChange(selection) {
      this.checkIds = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    /* 是病害/不是病害 */
    handleConfirm(value) {
      mergeDefect({ status: value, snapShotIds: this.checkIds })
        .then(({ code, msg }) => {
          if (code === 200) {
            this.checkIds = [];
            this.$modal.msgSuccess("修改成功");
          } else {
            this.$modal.msgWarning(msg);
          }
        })
        .finally(() => {
          this.getTableList();
        });
    },

    /* 影像模式 */
    handleBatch() {
      this.showCheckImg = true;
    },

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

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

    /* 打开查看图片弹窗 */
    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],
        },
      ];
      // this.rectsItem = this.defectData[this.currentIndex];
    },

    /* 图片红框位置 */
    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;
      this.currentImageItem = {};
      this.rects = [];
    },

    /* 关闭影像模式弹窗 */
    checkCancel() {
      this.showCheckImg = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.confirmation-content {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 分页样式 */
.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;
}
</style>