<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-input
          v-model="queryParams.segmentName"
          placeholder="请输入道路名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采集时间" prop="dateTime">
        <el-date-picker
          v-model="queryParams.dateTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病害类型" prop="defectType">
        <el-select v-model="queryParams.defectType" placeholder="请选择" clearable multiple>
          <el-option v-for="item in defectTypes" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="任务ID" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入任务ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病害状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable multiple>
          <el-option v-for="item in states" :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 multiple>
          <el-option label="上行" value="upstream"/>
          <el-option label="下行" value="downstream"/>
        </el-select>
      </el-form-item>
      <el-form-item label="公里桩" prop="stakeRange">
        <el-input
          v-model="queryParams.stakeStart"
          placeholder="起始公里桩"
          style="width: 100px;"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.stakeEnd"
          placeholder="终止公里桩"
          style="width: 100px;"
          clearable
        />
      </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
          v-model="queryParams.minLen"
          placeholder="最小长度"
          style="width: 100px;"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.maxLen"
          placeholder="最大长度"
          style="width: 100px;"
          clearable
        />
      </el-form-item>
      <el-form-item label="病害面积" prop="areaRange">
        <el-input
          v-model="queryParams.minArea"
          placeholder="最小面积"
          style="width: 100px;"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.maxArea"
          placeholder="最大面积"
          style="width: 100px;"
          clearable
        />
      </el-form-item>
      <el-form-item label="距离车顶天线" prop="distanceRange">
        <el-input
          v-model="queryParams.minDistance"
          placeholder="最小距离"
          style="width: 100px;"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.maxDistance"
          placeholder="最大距离"
          style="width: 100px;"
          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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table 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"/>
      <el-table-column label="病害类型" align="center" prop="defectType"/>
      <el-table-column label="病害状态" align="center" prop="state"/>
      <el-table-column label="开始桩号" align="center" prop="stakeStart"/>
      <el-table-column label="结束桩号" align="center" prop="stakeEnd"/>
      <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-column label="操作" align="center" 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>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改缺陷对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" append-to-body>
      <el-form ref="defectForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="道路名称" prop="segmentName">
          <el-input v-model="form.segmentName" placeholder="请输入道路名称"/>
        </el-form-item>
        <el-form-item label="病害类型" prop="defectType">
          <el-select v-model="form.defectType" placeholder="请选择病害类型" clearable>
            <el-option v-for="item in defectTypes" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="病害状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择病害状态" clearable>
            <el-option v-for="item in states" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="采集时间" prop="createdTime">
          <el-date-picker
            v-model="form.createdTime"
            type="datetime"
            placeholder="选择采集时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="开始桩号" prop="stakeStart">
          <el-input v-model="form.stakeStart" placeholder="请输入开始桩号"/>
        </el-form-item>
        <el-form-item label="结束桩号" prop="stakeEnd">
          <el-input v-model="form.stakeEnd" placeholder="请输入结束桩号"/>
        </el-form-item>
        <el-form-item label="病害长度" prop="targetLen">
          <el-input-number v-model="form.targetLen" :min="0" placeholder="请输入病害长度" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="病害面积" prop="targetArea">
          <el-input-number v-model="form.targetArea" :min="0" placeholder="请输入病害面积" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="预警标识" prop="warningFlag">
          <el-switch v-model="form.warningFlag" active-value="1" inactive-value="0" active-text="是"
                     inactive-text="否"/>
        </el-form-item>
        <el-form-item label="病害位置" prop="geometry">
          <el-input v-model="form.geometry.coordinates" placeholder="请输入坐标 (e.g., [lng, lat])"/>
        </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>
    </el-dialog>


    <!-- 查看病害详细信息对话框 -->
    <el-dialog title="查看病害详细信息" :visible.sync="openViewDialog" width="800px" append-to-body>
      <div>
        <!-- 上半部分 -->
        <div style="display: flex; height: 50%;">
          <!-- 左侧病害信息 -->
          <div style="flex: 1; padding: 10px;">
            <p>上报日期：{{ form.createdTime }}</p>
            <p>路段名称：{{ form.segmentName }}</p>
            <p>病害坐标：{{ form.geometry.coordinates }}</p>
            <p>病害类型：{{ form.defectType }}</p>
            <p>病害长度：{{ form.targetLen }} 米</p>
          </div>

          <!-- 右侧图片展示 -->
          <div style="flex: 1; padding: 10px;">
            <el-carousel height="150px">
              <el-carousel-item v-for="(img, index) in form.media" :key="index">
                <img :src="img.img" alt="病害图片" style="width: 100%;"/>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>

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

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

<script>
import {
  listDefect,
  getDefect,
  delDefect,
  addDefect,
  updateDefect,
} from "@/api/xj/defect";

import {listMetadata} from "@/api/xj/metadata"

export default {
  name: "Defect",
  data() {
    return {

      typeInfo: [],
      openViewDialog: false,

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缺陷表格数据
      defectList: [],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        segmentName: "",
        dateTime: [],
        defectType: [],
        taskId: "",
        state: [],
        inspectDirection: [],
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: null,
        maxLen: null,
        minArea: null,
        maxArea: null,
        minDistance: null,
        maxDistance: null
      },
      // 表单参数
      form: {
        id: null,
        segmentName: "",
        defectType: "",
        equipmentType: "",
        createdTime: "",
        updatedTime: "",
        state: "",
        stakeStart: "",
        stakeEnd: "",
        geometry: {
          type: "Point",
          coordinates: []
        },
        targetArea: null,
        targetLen: null,
        snapshotId: "",
        taskId: "",
        segmentId: "",
        inspectDirection: "",
        dataFrom: "",
        warningFlag: 0,
        equipmentId: "",
        transformation: 0,
        dataStatus: 0,
        objDistance: null,
        isCalibrated: 0,
        count: 0,
        media: []
      },
      // 表单校验规则
      rules: {
        segmentName: [
          {required: true, message: "请输入道路名称", trigger: "blur"}
        ],
        defectType: [
          {required: true, message: "请选择病害类型", trigger: "change"}
        ],
        state: [
          {required: true, message: "请选择病害状态", trigger: "change"}
        ],
        createdTime: [
          {type: "array", required: false, message: "请选择采集时间", trigger: "change"}
        ],
        stakeStart: [
          {required: false, message: "请输入开始桩号", trigger: "blur"}
        ],
        stakeEnd: [
          {required: false, message: "请输入结束桩号", trigger: "blur"}
        ],
        targetLen: [
          {type: "number", min: 0, message: "病害长度必须为正数", trigger: "change"}
        ],
        targetArea: [
          {type: "number", min: 0, message: "病害面积必须为正数", trigger: "change"}
        ]
        // 可以根据需要添加更多校验规则
      },
      // 下拉选项
      defectTypes: [
        {label: "裂缝", value: "crack"},
        {label: "坑槽", value: "pothole"},
        {label: "脱皮", value: "peeling"}
        // 添加更多病害类型
      ],
      states: [
        {label: "未处理", value: "untreated"},
        {label: "处理中", value: "in_process"},
        {label: "已处理", value: "processed"}
        // 添加更多病害状态
      ]
    };
  },
  created() {
    this.getList();
    this.getTypeInfo();
  },
  methods: {
    // 转换为按分类、子分类的label和value格式
    transformToDeepCategorizedLabelValue(data) {
      const result = {};

      data.items.forEach(item => {
        Object.entries(item).forEach(([categoryKey, categoryValue]) => {
          if (!result[categoryKey]) {
            result[categoryKey] = {};
          }
          categoryValue.forEach(subCategory => {
            Object.entries(subCategory).forEach(([subCategoryKey, subCategoryValue]) => {
              if (!result[categoryKey][subCategoryKey]) {
                result[categoryKey][subCategoryKey] = [];
              }
              // 处理嵌套的对象，将其转换为 label 和 value
              if (typeof subCategoryValue === 'object') {
                Object.entries(subCategoryValue).forEach(([key, value]) => {
                  result[categoryKey][subCategoryKey].push({
                    label: value,
                    value: key
                  });
                });
              } else {
                result[categoryKey][subCategoryKey].push({
                  label: subCategoryValue,
                  value: subCategoryKey
                });
              }
            });
          });
        });
      });

      return result;
    },
    getTypeInfo() {
      listMetadata().then(response => {
        // console.log(response)
        // console.log(this.transformToDeepCategorizedLabelValue(JSON.parse(response.data)));
      })

    },
    /** 查询缺陷列表 */
    getList() {

      let list = {
        rows: [
          {
            "state": "1",
            "media": [],
            "segmentId": "7064484787674677248",
            "segmentName": "testroad",
            "createdTime": "2023-05-17T06:34:12.000Z",
            "updatedTime": "2023-05-17T06:34:12.000Z",
            "defectType": "0",
            "stakeStart": "K000+000",
            "stakeEnd": "K000+123",
            "targetArea": 1,
            "targetLen": 1,
            "warningFlag": "0",
            "inspectDirection": "0",
            "geometry": {
              "type": "Point",
              "coordinates": [
                120,
                30
              ]
            },
            "id": "7064488256724795392",
            "snapshotId": "7064488256724795392",
            "equipmentId": "123",
            "transformation": "0",
            "taskid": "123456"
          }
        ],
        total: 1420,
      }

      this.defectList = list.rows;
      this.total = list.total;
      this.loading = false;
      return;
      this.loading = true;
      // 处理日期范围
      const params = {...this.queryParams};
      if (params.dateTime && params.dateTime.length === 2) {
        params.startDate = params.dateTime[0];
        params.endDate = params.dateTime[1];
      }
      delete params.dateTime;
      delete params.lengthRange;
      delete params.areaRange;
      delete params.distanceRange;

      listDefect(params)
        .then(response => {
          this.defectList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false;
      this.resetFormData();
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        segmentName: "",
        dateTime: [],
        defectType: [],
        taskId: "",
        state: [],
        inspectDirection: [],
        stakeStart: "",
        stakeEnd: "",
        warningFlag: null,
        minLen: null,
        maxLen: null,
        minArea: null,
        maxArea: null,
        minDistance: null,
        maxDistance: null
      };
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetFormData();
      this.dialogVisible = true;
      this.dialogTitle = "添加缺陷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row) {
        // 通过行数据修改
        this.loadDefect(row.id);
      } else if (this.ids.length === 1) {
        // 通过选中项修改
        this.loadDefect(this.ids[0]);
      } else {
        this.$modal.msgWarning("请选择一条记录进行修改");
      }
    },
    /** 加载缺陷数据 */
    loadDefect(id) {
      getDefect(id)
        .then(response => {
          this.form = {...response.data};
          // 处理日期格式
          if (this.form.createdTime) {
            this.form.createdTime = new Date(this.form.createdTime);
          }
          this.dialogVisible = true;
          this.dialogTitle = "修改缺陷";
        })
        .catch(() => {
          this.$modal.msgError("加载缺陷数据失败");
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["defectForm"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            // 更新缺陷
            updateDefect(this.form)
              .then(() => {
                this.$modal.msgSuccess("修改成功");
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.$modal.msgError("修改失败");
              });
          } else {
            // 添加缺陷
            addDefect(this.form)
              .then(() => {
                this.$modal.msgSuccess("新增成功");
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.$modal.msgError("新增失败");
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    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(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xj/defect/export', {
        ...this.queryParams
      }, `defect_${new Date().getTime()}.xlsx`)
    },
    /** 重置表单数据 */
    resetFormData() {
      this.form = {
        id: null,
        segmentName: "",
        defectType: "",
        equipmentType: "",
        createdTime: "",
        updatedTime: "",
        state: "",
        stakeStart: "",
        stakeEnd: "",
        geometry: {
          type: "Point",
          coordinates: []
        },
        targetArea: null,
        targetLen: null,
        snapshotId: "",
        taskId: "",
        segmentId: "",
        inspectDirection: "",
        dataFrom: "",
        warningFlag: 0,
        equipmentId: "",
        transformation: 0,
        dataStatus: 0,
        objDistance: null,
        isCalibrated: 0,
        count: 0,
        media: []
      };
      this.resetForm("defectForm");
    },

    // 打开查看详情弹出框
    viewDefect(defect) {
      this.form = defect;
      this.openViewDialog = true;
      this.$nextTick(() => {
        this.initMap();
      });
    },

    // 初始化天地图并标注病害位置
    initMap() {
      if (this.map) {
        this.map.remove(); // 如果已经有地图实例，先移除再重新加载
      }

      // 初始化天地图
      this.map = new T.Map("mapContainer");

      // 设置中心点为病害的坐标
      const coordinates = this.form.geometry.coordinates;
      if (coordinates && coordinates.length === 2) {
        const lon = coordinates[0];
        const lat = coordinates[1];

        // 设置地图中心点
        const center = new T.LngLat(lon, lat);
        this.map.centerAndZoom(center, 15);

        // 添加病害位置标注
        const marker = new T.Marker(center);
        this.map.addOverLay(marker);
      } else {
        console.error("无效的病害坐标");
      }
    },

    // 关闭对话框
    closeDialog() {
      this.openViewDialog = false;
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

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

.fixed-width {
  width: 120px;
}
</style>
