<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="路段名称" prop="routeName">
        <el-input
          v-model="queryParams.segname"
          placeholder="请输入路线名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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"
          v-hasPermi="['xj:route:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['xj:route:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['xj:route:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xj:route:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="路段名称" align="center" prop="segname"/>
      <el-table-column label="路段编码" align="center" prop="segcode"/>
      <el-table-column label="起始桩" align="center" prop="stakestart"/>
      <el-table-column label="终止桩" align="center" prop="stakeend"/>
      <el-table-column label="道路类型" align="center" prop="roadtype"/>
      <el-table-column label="里程" align="center" prop="mileage"/>
      <el-table-column label="车道数量" align="center" prop="lanecount"/>
      <el-table-column label="城市" align="center" prop="city"/>
      <el-table-column label="区县" align="center" prop="district"/>
      <el-table-column label="最大限速" align="center" prop="maxspeedlimit"/>


      <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="handleUpdate(scope.row)"
            v-hasPermi="['xj:route:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xj:route:remove']"
          >删除
          </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="title" :visible.sync="dialogVisible" width="80%" append-to-body>
      <div style="display: flex;">
        <!-- 左侧表单部分 -->
        <div style="flex: 1; padding-right: 20px;">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">

            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="路段编码">
                    <el-input v-model="form.segcode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="路段名称">
                    <el-input v-model="form.segname"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="道路类型">
              <el-input v-model="form.roadtype"></el-input>
            </el-form-item>

            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="里程">
                    <el-input v-model="form.mileage"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="车道数量">
                    <el-input v-model="form.lanecount"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="城市">
                    <el-input v-model="form.city"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="区县">
                    <el-input v-model="form.district"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="养护级别">
                    <el-input v-model="form.curinglevel"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大限速">
                    <el-input v-model="form.maxspeedlimit"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="备注">
              <el-input v-model="form.mark"></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧地图部分 -->
        <div style="flex: 1; position: relative;">
          <div id="add_map" ref="mapContainer" class="no-hand-cursor"></div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRoute, getRoute, delRoute, addRoute, updateRoute} from "@/api/xj/route";

export default {
  name: "Route",
  data() {
    return {
      menuOpen: false,
      markers: [],
      dialogVisible: false,  // 控制dialog显示
      routeForm: {
        routeCode: '',
        routeName: '',
        routeFullName: '',
        direction: '',
        startPoint: '',
        endPoint: '',
        startStake: '',
        endStake: '',
        coordinates: '',
        remark: ''
      },
      lines: [],    // 保存所有添加的连线
      map: null,
      markerLayer: null,
      previousPoint: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 道路线表格数据
      routeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        routeCode: null,
        routeName: null,
        fullName: null,
        routeType: null,
      },
      // 表单参数
      form: {
        coordinates: '',

      },
      // 表单校验
      rules: {
        routeCode: [
          {required: true, message: "路线编码，唯一不能为空", trigger: "blur"}
        ],
        routeName: [
          {required: true, message: "路线名称不能为空", trigger: "blur"}
        ],
        routeType: [
          {required: true, message: "路线类型不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.dialogVisible = true;
    this.dialogVisible = false;
  },
  methods: {
    undoLastAction() {
      // 撤销最后一次添加的点和连线
      if (this.lines.length > 0) {
        const lastLine = this.lines.pop();
        this.map.removeOverLay(lastLine);// 从地图中移除最后一条线
      }

      if (this.lines.length == 0) {
        this.resetMap();
        return;
      }
      this.markers.pop();
      // 更新上一个点为撤销后的点
      this.previousPoint = this.markers.length > 0 ? this.markers[this.markers.length - 1].getLngLat() : null;

      // 更新坐标点 textarea
      const coordArr = this.form.coordinates.split(';');
      coordArr.pop(); // 移除最后一个坐标
      this.form.coordinates = coordArr.join(';');
    },

    resetMap() {
      // 清空坐标点、地图上的所有覆盖物
      this.form.coordinates = '';
      this.previousPoint = null;
      this.map.clearOverLays();
      this.markers = [];
      this.lines = [];
    },
    initMap() {
      if (!this.map){
        // 初始化天地图

        this.map = new T.Map('add_map');
        this.map.centerAndZoom(new T.LngLat(116.40769, 39.89945), 12); // 设置中心点和缩放级别

        // 添加双击事件
        this.map.on("click", this.onMapClick);

        // 添加右键菜单
        this.map.on("contextmenu", this.onMapRightClick);
      }else{
        this.resetMap()
      }


    },
    onMapClick(e) {
      if (this.menuOpen) {
        this.menuOpen = false;
        return;
      }
      const latLng = e.lnglat;
      const point = `${latLng.lng},${latLng.lat}`;

      // 追加经纬度到textarea
      if(this.form.coordinates == null){
        this.form.coordinates = '';
      }
      this.form.coordinates += this.form.coordinates ? `;${point}` : point;

      // 绘制点和连线

      const marker = new T.Marker(latLng);


      this.markers.push(marker); // 保存点
      // 连线
      if (this.previousPoint) {
        const line = new T.Polyline([this.previousPoint, latLng], {
          strokeColor: "blue",
          strokeWeight: 3,
          strokeOpacity: 0.7
        });
        this.map.addOverLay(line);
        this.lines.push(line)
      }
      if (this.lines.length == 0 ){
        this.map.addOverLay(marker)
      }
      this.previousPoint = latLng;  // 记录上一个点
    },
    drawExistingCoordinates() {
      // 如果有保存的坐标点数据
      if (this.form.coordinates) {
        const coordArr = this.form.coordinates.split(';');
        let previousLatLng = null;

        coordArr.forEach((coord, index) => {
          const [lng, lat] = coord.split(',').map(Number);
          const latLng = new T.LngLat(lng, lat);

          // 绘制点
          const marker = new T.Marker(latLng);
          this.markers.push(marker);

          // 如果有上一个点，绘制连线
          if (previousLatLng) {
            const line = new T.Polyline([previousLatLng, latLng], {
              strokeColor: "blue",
              strokeWeight: 3,
              strokeOpacity: 0.7
            });
            this.map.addOverLay(line);
            this.lines.push(line);
          }

          // 将当前点设置为 previousPoint，最后一个点会被设置为最后的 previousPoint
          previousLatLng = latLng;
        });

        // 设置最后一个点为当前的 previousPoint，方便继续绘制
        this.previousPoint = previousLatLng;
      }
    },
    onMapRightClick(e) {
      this.menuOpen = true;
      var menu = new T.ContextMenu({
        width: 50
      });
      var _MenuItem1 = new T.MenuItem("撤销", this.undoLastAction);

      var _MenuItem2 = new T.MenuItem("重绘", this.resetMap);

      menu.addItem(_MenuItem1);

      menu.addItem(_MenuItem2);
      this.map.addContextMenu(menu);
    },

    /** 查询道路线列表 */
    getList() {
      this.loading = true;
      listRoute(this.queryParams).then(response => {
        this.routeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.dialogVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        routeCode: null,
        routeName: null,
        fullName: null,
        routeType: null,
        direction: null,
        startPoint: null,
        endPoint: null,
        coordinates: null,
        startMilepost: null,
        endMilepost: null,
        remarks: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null,
        deletedBy: null,
        deletedAt: null,
        isDeleted: null,
        companyId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogVisible = true;

      this.title = "添加道路线";
      let that = this;
      setTimeout(function () {
        that.initMap();
      }, 100)

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRoute(id).then(response => {
        this.form = response.data;
        this.dialogVisible = true;
        this.title = "修改道路线";
        let that = this;

        setTimeout(function () {
          that.initMap();
          that.drawExistingCoordinates()
        },200)

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRoute(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getList();
            });
          } else {
            addRoute(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除道路线编号为"' + ids + '"的数据项？').then(function () {
        return delRoute(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xj/route/export', {
        ...this.queryParams
      }, `route_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>


.no-hand-cursor {
  cursor: default !important;
  width: 100%;
  height: 500px;
}
</style>
