<template>
  <div class="AddBuildingBox">
    <PageHeader></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="巡检路线名称" prop="routeName">
            <el-input v-model.trim="form.routeName" placeholder="请输入巡检路线名称" />
          </el-form-item>
          <el-form-item label="巡检点">
            <div class="itembox">
              <div
                class="item"
                :class="{
                  active: checkoutPointlist.includes(item.id)
                }"
                v-for="(item, index) in pointslist"
                @click="checkoutItemPoint(item)"
                :key="index"
              >
                <el-icon v-show="checkoutPointlist.includes(item.id)"><Check /></el-icon>
                <div>{{ item.pointName }}</div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="绘制巡检路线">
            <GD :small-scroll="true" ref="GDef" :click-or-draw="false"></GD>
            <div class="tips flex flex-items-center justify-between">
              <div>点击地图，绘制巡检路线；再次点击可继续绘制下一条（但只能保留一条）</div>
              <div>
                <span
                  class="deleteMarker"
                  @click="
                    () => {
                      GDef.clearAll();
                    }
                  "
                  >清空所有路线</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PageHeader from '@/components/Pageheader/index.vue';
import { listPoint } from '@/api/system/InspectionPoint';
import { onMounted, onUnmounted } from 'vue';
import { addRoute, getRoute, updateRoute } from '@/api/system/InspectionRoute';
import { Check } from '@element-plus/icons-vue';

import GD from '@/components/Map/GD.vue';

const router = useRouter();
const route = useRoute();

const formRef = ref();
const form = ref({
  id: null,
  startLat: '',
  startLng: '',
  endLat: '',
  endLng: '',
  routeName: '', // 巡检路线名称
  description: '', // 巡检路线描述
  routeStatus: '0', // 巡检路线状态
  estimatedTime: null, // 预计巡检时长
  pathPoints: '', // 巡检路线经纬度
  totalPoints: '' // 巡检点
});

const rules = ref({
  routeName: [{ required: true, message: '请输入巡检路线名称', trigger: 'blur' }],
  estimatedTime: [{ required: true, message: '请输入预计巡检时长', trigger: 'blur' }]
});

const GDef = ref();
const routeid = ref(null);
// 巡检点 列表
const pointslist = ref([]);
// 选择巡检点列表
const checkoutPointlist = ref([]);

// ! 初始化 =========================================================================
function init() {
  if (route.query.id) {
    routeid.value = route.query.id;
    // 获取巡检点详情
    getRoute(routeid.value).then((res) => {
      form.value = {
        id: res.data.id,
        startLat: res.data.startLat,
        startLng: res.data.startLng,
        endLat: res.data.endLat,
        endLng: res.data.endLng,
        routeName: res.data.routeName, // 巡检路线名称
        description: res.data.description, // 巡检路线描述
        routeStatus: res.data.routeStatus, // 巡检路线状态
        estimatedTime: res.data.estimatedTime, // 预计巡检时长
        pathPoints: res.data.pathPoints, // 巡检路线经纬度
        totalPoints: res.data.totalPoints // 巡检点
      };
      nextTick(() => {
        if (routeid.value) {
          checkoutPointlist.value = res.data.totalPoints ? res.data.totalPoints.split(',') : [];
          if (checkoutPointlist.value.length > 0) {
            // 回显 marker
            checkoutPointlist.value.forEach((id) => {
              const find = res.data.points.find((item) => item.id === id);
              if (find && find.location) {
                // addPointMarker(id, find.location, find.pointName);
                const location = find.location
                  .split(',')
                  .map((item) => Number(item))
                  .filter((item) => !Number.isNaN(item));
                if (location.length >= 2) {
                  GDef.value.addMarker_more(location, find.pointName, find.id);
                }
              }
            });
          }
          // 回显路线
          if (res.data.pathPoints) {
            // renderSavedPath(res.data.pathPoints);
            setTimeout(() => {
              GDef.value.renderSavedPath(res.data.pathPoints);
            }, 800);
          }
        }
      });
    });
  }
}
const map = ref<any>(null);

onMounted(async () => {
  // 获取巡检点列表
  if (!routeid.value) {
    listPoint({}).then((res) => {
      pointslist.value = res.rows;
    });
  }
  await nextTick(() => init());
});

// !== 提交 =============================================================================
const submitForm = () => {
  if (form.value.routeName.trim() === '') {
    ElMessage.warning('请输入巡检路线名称');
    return;
  }
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 获取路线经纬度
      const path = GDef.value.getAllDrawLines() as [number, number][];
      console.log(path);
      if (path.length === 0) {
        ElMessage.warning('请绘制巡检路线');
        return;
      }
      // 转成字符串传给后端
      const [start_lng, start_lat] = path.at(0) as [number, number];
      const [end_lng, end_lat] = path.at(-1) as [number, number];

      form.value.startLng = `${start_lng}`;
      form.value.startLat = `${start_lat}`;
      form.value.endLng = `${end_lng}`;
      form.value.endLat = `${end_lat}`;

      form.value.pathPoints = JSON.stringify(path);
      form.value.totalPoints = checkoutPointlist.value.join(',');
      if (routeid.value) {
        updateRoute(form.value).then(() => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        addRoute(form.value).then(() => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
// 返回
const cancelForm = () => {
  router.back();
};

// 点击展现 巡检点
function checkoutItemPoint(pop) {
  const find = pointslist.value.find((item) => item.id === pop.id);
  if (find && find.location) {
    const locations =
      find.location
        .split(',')
        .map((item: string) => Number(item))
        .filter(Boolean) ?? [];
    if (locations.length >= 2) {
      GDef.value.addMarker_more(locations, find.pointName, find.id);
      if (checkoutPointlist.value.includes(pop.id)) {
        checkoutPointlist.value = checkoutPointlist.value.filter((item) => item !== pop.id);
      } else {
        checkoutPointlist.value.push(pop.id);
      }
    } else {
      ElMessage.error(find.pointName + ' - 巡检点经纬度定位有误');
    }
  }
}
onUnmounted(() => {
  map.value?.destroy();
});
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .formBody {
    width: 800px;
    margin: 0 auto;

    .itembox {
      display: flex;
      flex-wrap: wrap;
      .item {
        display: flex;
        align-items: center;
        margin-right: 15px;
        margin-bottom: 10px;
        font-size: 14px;
        color: #606266;
        border: 1px solid #ccc;
        padding: 5px 10px;
        border-radius: 4px;
        cursor: pointer;
        &:hover {
          border-color: #409eff;
          color: #409eff;
        }
        div {
          margin-left: 10px;
        }
        &.active {
          border-color: #409eff;
          color: #409eff;
          background-color: #f0f9ff;
        }
      }
    }

    .map {
      width: 100%;
      min-height: 500px;
      background-color: #f0f0f0;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-top: 10px;
    }
    .tips {
      width: 100%;
      margin-top: 10px;
      font-size: 12px;
      color: #ccc;
      .deleteMarker {
        margin-left: 20px;
        cursor: pointer;
        color: #f00;
      }
    }
    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
