<!--
 * @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 09:26:24
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-10-15 13:39:02
 * @FilePath: \znxjxt-ui\src\views\xj\route\index.vue
 * @Description: 路线管理-道路线
-->

<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="routeCode">
        <el-input
          v-model="queryParams.routeCode"
          placeholder="请输入路线编码，唯一"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="路线名称" prop="routeName">
        <el-input
          v-model="queryParams.routeName"
          placeholder="请输入路线名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="路线全称" prop="fullName">
        <el-input
          v-model="queryParams.fullName"
          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="routeCode" />
      <el-table-column label="路线名称" align="center" prop="routeName" />
      <el-table-column label="路线全称" align="center" prop="fullName" />
      <el-table-column label="方向" align="center" prop="direction" />
      <el-table-column label="起点" align="center" prop="startPoint" />
      <el-table-column label="终点" align="center" prop="endPoint" />
      <el-table-column label="起点桩号" align="center" prop="startMilepost" />
      <el-table-column label="止点桩号" align="center" prop="endMilepost" />
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updatedBy" />
      <el-table-column
        label="修改时间"
        align="center"
        prop="updatedAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, "{y}-{m}-{d}") }}</span>
        </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="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: 40px">
          <el-form ref="form" :model="form" :rules="rules" label-width="70px">
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="路线编码">
                    <el-input v-model="form.routeCode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="路线名称">
                    <el-input v-model="form.routeName"></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-select
                      v-model="form.routeType"
                      placeholder="请选择路线类型"
                    >
                      <el-option
                        v-for="dict in dict.type.bas_road_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"> </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="5">
                <el-col :span="12">
                  <el-form-item label="路线全称">
                    <el-input v-model="form.fullName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="方向">
                    <el-select
                      v-model="queryParams.direction"
                      placeholder="请选择方向"
                      clearable
                    >
                      <el-option
                        v-for="dict in dict.type.bas_direction"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </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.startPoint"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="终点">
                    <el-input v-model="form.endPoint"></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.startMilepost"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="止点桩号">
                    <el-input v-model="form.endMilepost"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="坐标点">
                    <el-input
                      type="textarea"
                      :disabled="true"
                      v-model="form.coordinates"
                      rows="4"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input v-model="form.remarks"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </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",
  dicts: ["bas_road_type", "bas_direction"],
  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() {
      // 如果有保存的坐标点数据
      // console.log(this.form.coordinates, "this.form.coordinates");

      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>
