<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-10-08 10:58:25
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-12-24 15:57:52
 * @FilePath: \znxjxt-ui\src\views\xj\inspection\disease-management\index.vue
 * @Description: 巡检信息管理-病害管理
-->
<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="道路名称" prop="segmentName">
        <el-select
          v-model="queryParams.segmentName"
          placeholder="请选择路段"
          filterable
          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="paramsDefectType">
        <el-cascader
          v-model="paramsDefectType"
          :options="tableDefect"
          :props="{
            checkStrictly: true,
            emitPath: true,
            children: 'subTypes',
          }"
          clearable
        ></el-cascader>
      </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="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="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="病害id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请填写病害id"
          clearable
        />
      </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="快照id" prop="snapshotId">
        <el-input
          v-model="queryParams.snapshotId"
          placeholder="请填写快照id"
          clearable
        />
      </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="巡检任务" prop="taskId">
        <el-select
          v-model="queryParams.taskId"
          placeholder="请选择巡检任务"
          filterable
          clearable
        >
          <el-option
            v-for="item in taskList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete('')"
          >删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit-outline"
          size="mini"
          :disabled="multiple"
          @click="handleUpdateBatch"
          >批量确认
        </el-button>
      </el-col> -->
    </el-row>

    <!-- 数据表格 -->
    <el-table
      ref="defectTable"
      v-loading="loading"
      :data="defectList"
      @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="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">
        <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-column label="道路方向" align="center" prop="inspectDirection">
        <template slot-scope="scope">
          <span>{{
            scope.row.inspectDirection === "0" ? "上行" : "下行"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="viewDefect(scope.row)"
            >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-bangzhu"
            @click="mergeDefect(scope.row)"
            >合并
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            v-if="scope.row.id !== scope.row.snapshotId"
            @click="splitDefect(scope.row)"
            >拆分
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改缺陷对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60rem"
      append-to-body
      :close-on-click-modal="false"
      destroy-on-close
      @close="cancel"
    >
      <template v-if="dialogVisible">
        <el-form
          class="addForm"
          ref="defectForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-row :gutter="24">
            <el-col :span="dialogTitle === '添加缺陷' ? 12 : 24">
              <el-form-item label="路段" prop="segmentId">
                <el-select
                  v-model="form.segmentId"
                  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="12" v-if="dialogTitle === '添加缺陷'">
              <el-form-item label="病害类型" prop="defectType">
                <el-cascader
                  v-model="form.defectType"
                  :options="tableDefect"
                  :props="{
                    checkStrictly: false,
                    emitPath: false,
                    children: 'subTypes',
                  }"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12" v-if="dialogTitle != '添加缺陷'">
              <el-form-item label="校验状态" prop="dataStatus">
                <el-select
                  v-model="form.dataStatus"
                  placeholder="请选择校验状态"
                  clearable
                >
                  <el-option
                    v-for="item in states"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="dialogTitle === '添加缺陷' ? 24 : 12">
              <el-form-item label="病害状态" prop="state">
                <el-select
                  v-model="form.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-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始桩号" prop="stakeStart">
                <el-input
                  v-model="form.stakeStart"
                  placeholder="请输入开始桩号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束桩号" prop="stakeEnd">
                <el-input
                  v-model="form.stakeEnd"
                  placeholder="请输入结束桩号"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="病害长度" prop="targetLen">
                <el-input-number
                  v-model="form.targetLen"
                  :min="0"
                  placeholder="请输入病害长度"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="病害面积" prop="targetArea">
                <el-input-number
                  v-model="form.targetArea"
                  :min="0"
                  placeholder="请输入病害面积"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="上下行" prop="inspectDirection">
                <el-select
                  v-model="form.inspectDirection"
                  placeholder="请选择上下行"
                  clearable
                >
                  <el-option label="上行" value="0" />
                  <el-option label="下行" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="病害位置">
            <fssm-map
              ref="diseaseMap"
              @map-click="getMapClick"
              class="no-hand-cursor"
            ></fssm-map>
          </el-form-item>
          <el-form-item label="上传病害图片">
            <el-upload
              ref="upload"
              accept=".jpg, .png"
              :action="upload.url"
              :headers="upload.headers"
              :file-list="upload.fileList"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              list-type="picture"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取文件</el-button
              >
              <el-button
                style="margin-left: 1rem"
                size="small"
                type="success"
                :loading="upload.isUploading"
                @click="submitUpload"
                >上传到服务器</el-button
              >
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看病害详细信息对话框 -->
    <el-dialog
      title="查看病害详细信息"
      :visible.sync="openViewDialog"
      width="55rem"
      append-to-body
      destroy-on-close
      @close="cancel"
    >
      <template v-if="openViewDialog">
        <div>
          <!-- 上半部分 -->
          <div style="display: flex; flex-direction: column; height: 50%">
            <!-- 下拉选择框 -->
            <div>
              <el-select
                v-model="viewCheck"
                @change="changeView"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in viewOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div style="display: flex">
              <!-- 左侧病害信息 -->
              <div style="width: 50%; padding: 10px">
                <p>
                  上报日期：{{
                    new Date(viewForm.createdTime).toLocaleString()
                  }}
                </p>
                <p>路段名称：{{ viewForm.segmentName }}</p>
                <!-- <p>病害坐标：{{ viewForm.geometry.coordinates }}</p> -->
                <p>病害类型：{{ viewForm.defectTypeName }}</p>
                <p>
                  病害长度：{{
                    viewForm.targetLen * 1 < 0 ? "" : `${viewForm.targetLen}米`
                  }}
                </p>
                <p>病害id：{{ viewForm.id }}</p>
                <p>快照id：{{ viewForm.snapshotId }}</p>
              </div>

              <!-- 右侧图片展示 -->
              <div style="width: 50%; padding: 10px">
                <el-carousel class="view-carousel" height="15rem">
                  <el-carousel-item
                    v-for="(img, index) in viewForm.media"
                    :key="index"
                  >
                    <img :src="img.img" alt="病害图片" />
                  </el-carousel-item>
                </el-carousel>
              </div>
            </div>
          </div>

          <!-- 下半部分显示天地图 -->
          <!-- <div id="viewMap" style="height: 300px; margin-top: 20px"></div> -->
          <fssm-map
            style="height: 300px; margin-top: 20px"
            ref="diseaseMap"
          ></fssm-map>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合并病害弹窗 -->
    <el-dialog
      title="合并病害"
      :visible.sync="mergeVisibleDialog"
      width="75rem"
      append-to-body
      destroy-on-close
      @close="mergeCancel"
    >
      <merge-dialog
        :segmentList="segmentList"
        :tableDefect="tableDefect"
        :defectStatus="defectStatus"
        :mergeItem="mergeItem"
        @mergeCancel="mergeCancel"
      ></merge-dialog>
    </el-dialog>

    <!-- 查看图片大图 -->
    <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,
  delDefect,
  addDefect,
  updateDefect,
  getSegment,
  getDefectList,
  getStatesList,
  getDefectStatus,
  changeDefectStatus,
  splitDefect,
  getDefectById,
  getDetailsBySnapShotId,
  getTaskList,
} from "@/api/xj/disease";
import { getToken } from "@/utils/auth";
import MergeDialog from "./components/merge-dialog.vue";
// 地图
import FssmMap from "@/components/map/fssm-map.vue";
import { Feature } from "ol";
import { Point } from "ol/geom";
import { Style } from "ol/style";
import * as styleExports from "ol/style";
import VectorLayer from "ol/layer/Vector";
import { Vector as VectorSource } from "ol/source";
export default {
  name: "Defect",
  components: {
    MergeDialog,
    FssmMap,
  },
  data() {
    return {
      typeInfo: [],
      // 查看弹窗显隐控制
      openViewDialog: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缺陷表格数据
      defectList: [],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 查询表单参数
      queryParams: {
        page: 1,
        size: 10,
        segmentName: "",
        defectType: "",
        classType: "",
        taskId: "",
        state: "",
        inspectDirection: "",
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: undefined,
        maxLen: undefined,
        minArea: undefined,
        maxArea: undefined,
        id: "",
        snapshotId: "",
        taskId: "",
      },
      // 日期范围
      dateTime: [],
      // 巡检任务下拉数据
      taskList: [],
      // 病害类型级联下拉绑定
      paramsDefectType: [],
      // 新增/编辑表单参数
      form: {
        id: null,
        segmentId: "",
        defectType: "",
        dataStatus: "",
        state: "",
        stakeStart: "",
        stakeEnd: "",
        targetLen: undefined,
        targetArea: undefined,
        inspectDirection: "",
        media: [],
      },
      // 上传参数设置
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      // 表单校验规则
      rules: {
        segmentId: [
          { required: true, message: "请选择路段", trigger: "change" },
        ],
        defectType: [
          { required: true, message: "请选择病害类型", trigger: "change" },
        ],
        state: [
          { required: true, message: "请选择病害状态", trigger: "change" },
        ],
        dataStatus: [
          { required: true, message: "请选择校验状态", trigger: "change" },
        ],
        stakeStart: [
          { required: true, message: "请输入开始桩号", trigger: "blur" },
          {
            pattern: /^K\d{4}\+\d{3}$/,
            message: "请按照K0000+000格式进行填写",
          },
        ],
        stakeEnd: [
          { required: true, message: "请输入结束桩号", trigger: "blur" },
          {
            pattern: /^K\d{4}\+\d{3}$/,
            message: "请按照K0000+000格式进行填写",
          },
        ],
        targetLen: [
          { required: true, message: "请填写病害长度", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "病害长度必须为正数",
            trigger: "change",
          },
        ],
        targetArea: [
          { required: true, message: "请填写病害面积", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "病害面积必须为正数",
            trigger: "change",
          },
        ],
        inspectDirection: [
          { required: true, message: "请选择上下行", trigger: "change" },
        ],
      },
      // 路段下拉选项
      segmentList: [],
      // 列表病害状态数据
      tableDefect: [],
      defectTypes: [],
      // 校验状态下拉选项
      states: [],
      // 病害状态下拉选项
      defectStatus: [],
      // 新增/编辑打点数组
      markers: [],
      // 查看弹窗选择绑定
      viewCheck: "",
      // 查看弹窗下拉数据绑定
      viewOptions: [],
      // 查看弹窗信息绑定
      viewForm: {},
      // 查看图片大图弹窗显隐控制
      showImageDialog: false,
      // 查看大图片路径
      currentImageItem: {},
      // 图片病害位置信息
      rects: [],
      // 合并病害弹窗显隐控制
      mergeVisibleDialog: false,
      // 传合并病害弹窗数据
      mergeItem: {},
    };
  },
  created() {
    this.getList();
    this.getSegmentList();
    this.getTableDefect();
    this.getStates();
    this.getDefectStatusList();
    this.getTaskSelectList();
  },
  methods: {
    /**
     * @description: 获取路段下拉数据
     * @param {*} val
     * @return {*}
     */
    getSegmentList() {
      getSegment().then(({ code, data }) => {
        if (code === 200) {
          this.segmentList = data;
        }
      });
    },

    /**
     * @description: 获取列表病害类型对应数据
     * @param {*} val
     * @return {*}
     */
    getTableDefect() {
      getDefectList().then(({ code, data }) => {
        if (code === 200) {
          this.tableDefect = data;
        }
      });
    },

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

    /**
     * @description: 查询校验状态下拉数据
     * @param {*} val
     * @return {*}
     */
    getStates() {
      getStatesList().then(({ code, data }) => {
        if (code === 200) {
          this.states = data;
        }
      });
    },

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

    /**
     * @description: 查询巡检任务下拉数据
     * @param {*} val
     * @return {*}
     */
    getTaskSelectList() {
      getTaskList().then(({ code, data }) => {
        if (code === 200) {
          this.taskList = data;
        }
      });
    },

    /**
     * @description: 查询缺陷列表
     * @param {*} val
     * @return {*}
     */
    getList() {
      // 处理日期范围
      this.loading = true;
      const params = {
        ...this.queryParams,
        startTime: this.dateTime ? this.dateTime[0] : "",
        endTime: this.dateTime ? this.dateTime[1] : "",
      };
      listDefect(params)
        .then((response) => {
          this.defectList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * @description: 新增/编辑弹窗取消按钮
     * @param {*} val
     * @return {*}
     */
    cancel() {
      this.dialogVisible = false;
      this.upload.fileList = [];
      this.markers = [];
      this.form = {
        id: null,
        segmentId: "",
        defectType: "",
        dataStatus: "",
        state: "",
        stakeStart: "",
        stakeEnd: "",
        targetLen: undefined,
        targetArea: undefined,
        inspectDirection: "",
        media: [],
      };
      // this.resetFormData();
    },

    /**
     * @description: 重置表单方法
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    /**
     * @description: 表单重置事件
     * @param {*} val
     * @return {*}
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        page: 1,
        size: 10,
        segmentName: "",
        defectType: "",
        classType: "",
        taskId: "",
        state: "",
        inspectDirection: "",
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: undefined,
        maxLen: undefined,
        minArea: undefined,
        maxArea: undefined,
        id: "",
        snapshotId: "",
        taskId: "",
      };
      this.paramsDefectType = [];
      this.dateTime = [];
      this.getList();
    },

    /**
     * @description: 点击搜索按钮操作
     * @param {*} val
     * @return {*}
     */
    handleQuery() {
      const phonereg = /^K\d{4}\+\d{3}$/;
      if (this.queryParams.stakeStart) {
        if (phonereg.test(this.queryParams.stakeStart)) {
          this.queryParams.classType = this.paramsDefectType
            ? this.paramsDefectType[0]
            : "";
          this.queryParams.defectType = this.paramsDefectType
            ? this.paramsDefectType.length > 1
              ? this.paramsDefectType[1]
              : ""
            : "";
          this.queryParams.page = 1;
          this.getList();
        } else {
          this.$modal.msgWarning("请按照格式填写公里桩进行修改");
        }
      } else if (this.queryParams.stakeEnd) {
        if (phonereg.test(this.queryParams.stakeEnd)) {
          this.queryParams.classType = this.paramsDefectType
            ? this.paramsDefectType[0]
            : "";
          this.queryParams.defectType = this.paramsDefectType
            ? this.paramsDefectType.length > 1
              ? this.paramsDefectType[1]
              : ""
            : "";
          this.queryParams.page = 1;
          this.getList();
        } else {
          this.$modal.msgWarning("请按照格式填写公里桩进行修改");
        }
      } else {
        this.queryParams.classType = this.paramsDefectType
          ? this.paramsDefectType[0]
          : "";
        this.queryParams.defectType = this.paramsDefectType
          ? this.paramsDefectType.length > 1
            ? this.paramsDefectType[1]
            : ""
          : "";
        this.queryParams.page = 1;
        this.getList();
      }
    },

    /**
     * @description: 多选框选中数据
     * @param {*} selection
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /**
     * @description: 新增按钮操作
     * @param {*} val
     * @return {*}
     */
    handleAdd() {
      this.dialogVisible = true;
      this.dialogTitle = "添加缺陷";
    },

    /**
     * @description: 修改按钮操作
     * @param {*} row
     * @return {*}
     */
    handleUpdate(row) {
      this.dialogVisible = true;
      this.dialogTitle = "修改缺陷";
      this.$nextTick(() => {
        const map = this.$refs.diseaseMap.instance.get("map");
        map.getView().setCenter(row.geometry.coordinates);
        this.markers = row.geometry.coordinates;
        this.drawMapPoint();
      });
      this.form = { ...row, dataStatus: row.dataStatus.toString() };
      this.upload.fileList = row.media.map((item) => {
        return {
          ...item,
          url: item.img,
        };
      });
    },

    /**
     * @description: 批量确认操作
     * @param {*} val
     * @return {*}
     */
    handleUpdateBatch() {
      if (this.ids.length > 0) {
        changeDefectStatus(this.ids).then(({ code, data }) => {
          if (code === 200) {
            this.$modal.msgSuccess(`修改${data}`);
            this.$refs.defectTable.clearSelection();
            this.ids = [];
          }
        });
      } else {
        this.$modal.msgWarning("请选择一条记录进行修改");
      }
    },

    /**
     * @description: 传回来的地图点击事件获取点位数据
     * @param {*} e
     * @return {*}
     */
    getMapClick(e) {
      const map = this.$refs.diseaseMap.instance.get("map");
      map.removeLayer(this.markLayerPoints);
      const { coordinate } = e;
      this.markers = coordinate;
      this.drawMapPoint();
    },

    /**
     * @description: 绘制地图点位
     * @param {*} val
     * @return {*}
     */
    drawMapPoint() {
      const features = [];
      const point = new Point(this.markers); // 修改坐标格式
      const feature = new Feature({
        geometry: point,
        type: "icon", //  自己设置一个标识
      });
      feature.setStyle([
        new Style({
          image: new styleExports.Circle({
            //点样式
            radius: 6,
            stroke: new styleExports.Stroke({
              color: "#9a9c9e",
              width: 4,
            }),
            fill: new styleExports.Fill({
              color: "blue",
            }),
          }),
        }),
      ]);
      features.push(feature);
      //设置地图的数据源
      const pointSource = new VectorSource({
        features,
      });
      this.markLayerPoints = new VectorLayer({
        source: pointSource,
        properties: {
          type: "point",
        },
      });
      this.$nextTick(() => {
        const map = this.$refs.diseaseMap.instance.get("map");
        map.addLayer(this.markLayerPoints);
      });
    },

    /**
     * @description: 文件提交处理
     * @param {*} val
     * @return {*}
     */
    submitUpload() {
      this.$refs.upload.submit();
    },

    /**
     * @description: 文件上传中处理
     * @param {*} event
     * @param {*} file
     * @param {*} fileList
     * @return {*}
     */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    /**
     * @description: 文件上传成功处理
     * @param {*} response
     * @param {*} file
     * @param {*} fileList
     * @return {*}
     */
    handleFileSuccess(response, file, fileList) {
      this.upload.fileList = fileList.map((item) => {
        if (item.response) {
          return { ...item, img: item.response.url };
        }
        return item;
      });
      this.upload.isUploading = false;
    },

    /**
     * @description: 提交按钮
     * @param {*} val
     * @return {*}
     */
    submitForm() {
      this.$refs["defectForm"].validate((valid) => {
        if (valid) {
          // 验证点位
          if (this.markers.length < 1) {
            this.$modal.msgWarning("请选择病害位置");
            return false;
          }
          // 验证文件上传列表
          if (this.upload.fileList.length < 1) {
            this.$modal.msgWarning("请上传图片");
            return false;
          }
          const data = {
            ...this.form,
            media: this.upload.fileList.map((item) => {
              return { ...item, img: item.img };
            }),
            geometry: {
              type: "Point",
              coordinates: this.markers,
              id: this.form?.geometry?.id,
            },
          };
          if (this.form.id) {
            // 更新缺陷
            updateDefect(data)
              .then(() => {
                this.$modal.msgSuccess("修改成功");
                this.$refs["defectForm"].resetFields();
                this.upload.fileList = [];
                this.markers = [];
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.$modal.msgError("修改失败");
              });
          } else {
            // 添加缺陷
            addDefect(data)
              .then(() => {
                this.$modal.msgSuccess("新增成功");
                this.$refs["defectForm"].resetFields();
                this.upload.fileList = [];
                this.markers = [];
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.$modal.msgError("新增失败");
              });
          }
        }
      });
    },

    /**
     * @description: 删除按钮操作
     * @param {*} row
     * @return {*}
     */
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      if (!ids.length) {
        this.$modal.msgWarning("请选择要删除的记录");
        return;
      }
      this.$modal
        .confirm(`是否确认删除选中的${ids.length}条记录？`)
        .then(() => {
          return delDefect(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /**
     * @description: 合并按钮事件
     * @param {*} row
     * @return {*}
     */
    mergeDefect(row) {
      this.mergeItem = row;
      this.mergeVisibleDialog = true;
    },

    /**
     * @description: 拆分按钮事件
     * @param {*} row
     * @return {*}
     */
    splitDefect(row) {
      const snapshotId = row.snapshotId;
      this.$modal
        .confirm(`是否确认拆分该条记录？`)
        .then(() => {
          return splitDefect({ snapshotId: snapshotId });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("拆分成功");
        })
        .catch(() => {});
    },

    /**
     * @description: 导出按钮操作
     * @param {*} val
     * @return {*}
     */
    handleExport() {
      this.download(
        "xj/defect/export",
        {
          ...this.queryParams,
        },
        `defect_${new Date().getTime()}.xlsx`
      );
    },

    /**
     * @description: 重置表单数据
     * @param {*} val
     * @return {*}
     */
    resetFormData() {
      this.form = {
        id: null,
        segmentId: "",
        defectType: "",
        dataStatus: "",
        state: "",
        stakeStart: "",
        stakeEnd: "",
        targetLen: undefined,
        targetArea: undefined,
        inspectDirection: "",
        media: [],
      };
      this.resetForm("defectForm");
    },

    /**
     * @description: 点击行列表查看事件
     * @param {*} defect
     * @return {*}
     */
    viewDefect(defect) {
      // this.loadDefect(defect.id);
      this.getSnapShotIdList(defect.id);
      this.viewCheck = defect.snapshotId;
      this.openViewDialog = true;
      this.viewForm = defect;
      this.$nextTick(() => {
        const map = this.$refs.diseaseMap.instance.get("map");
        map.getView().setCenter(defect.geometry.coordinates);
        this.markers = defect.geometry.coordinates;
        this.drawMapPoint();
      });
    },

    /**
     * @description: 根据病害id获取所有下拉快照数据
     * @param {*} id
     * @return {*}
     */
    getSnapShotIdList(id) {
      getDefectById(id).then(({ code, data }) => {
        if (code === 200) {
          this.viewOptions = data;
        }
      });
    },

    /**
     * @description: 查看弹窗选择改变触发事件
     * @param {*} val
     * @return {*}
     */
    changeView(val) {
      getDetailsBySnapShotId(val).then(({ code, data }) => {
        if (code === 200) {
          this.viewForm = data;
          console.log(data, "查看弹窗选择改变触发事件");
        }
      });
    },

    /**
     * @description: 关闭查看对话框
     * @param {*} val
     * @return {*}
     */
    closeDialog() {
      this.openViewDialog = false;
    },

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

      this.showImageDialog = true;
    },

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

    /**
     * @description: 图片红框位置
     * @param {*} left
     * @param {*} top
     * @param {*} width
     * @param {*} 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 {*} val
     * @return {*}
     */
    imgCancel() {
      this.showImageDialog = false;
      this.currentImageItem = {};
      this.rects = [];
    },

    /**
     * @description: 关闭合并病害弹窗
     * @param {*} val
     * @return {*}
     */
    mergeCancel() {
      this.mergeVisibleDialog = false;
      this.getList();
    },
  },
};
</script>

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

.mb8 {
  margin-bottom: 8px;
}

.small-padding {
  padding: 0 5px;
}

.fixed-width {
  width: 120px;
}
/* 新增弹窗/编辑弹窗 */
.addForm {
  .el-select,
  .el-cascader {
    width: 100%;
  }
}
/* 新增地图框样式 */
.no-hand-cursor {
  cursor: default !important;
  width: 100%;
  height: 20rem;
}

/* 上传文件列表样式 */
::v-deep .el-upload-list {
  img {
    width: auto;
  }
}

/* 查看弹窗-图片框样式 */
.view-carousel {
  height: 15rem;
  // .el-carousel__item{
  //   height: 12rem;

  img {
    max-height: 15rem;
    max-width: 25rem;
  }
}

/* 查看大图弹窗 */
.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>
