<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="pointName">
            <el-input v-model.trim="form.pointName" placeholder="请输入巡检点名称" />
          </el-form-item>
          <el-form-item label="巡检项目" prop="itemId">
            <div class="itembox">
              <div
                class="item"
                :class="{
                  disabled: item.status === '1',
                  active: checkoutPointItemlist.includes(item.id)
                }"
                @click="checkoutItem(item.id)"
                v-for="(item, index) in pointItemlist"
                :key="index"
              >
                <el-icon><Check /></el-icon>
                <div>{{ item.itemName }}</div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="打卡方式" prop="checkMode">
            <el-select v-model="form.checkMode" placeholder="请选择打卡方式" clearable>
              <el-option v-for="dict in com_inspection_point_checkmode" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="巡检点状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="item in com_inspection_point_status" :value="item.value" :key="item.value" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="巡检点位置" prop="location">
            <div class="map" id="containerMap"></div>
            <div class="tips">
              <span>点击地图选择位置</span>
              <span class="deleteMarker" v-show="Boolean(marker)" @click="clearLocation">清空选择地点</span>
            </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, toRefs } from 'vue';
import { getCurrentInstance, ComponentInternalInstance } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import PageHeader from '@/components/Pageheader/index.vue';
import { addPoint, getPoint, updatePoint } from '@/api/system/InspectionPoint';
import { listItem } from '@/api/system/InspectionItem';
import { onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { getVillageByIdAPI } from '@/api/system/community';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_inspection_point_checkmode } = toRefs<any>(proxy?.useDict('com_inspection_point_checkmode'));
const { com_inspection_point_status } = toRefs<any>(proxy?.useDict('com_inspection_point_status'));

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

const formRef = ref();
const form = ref({
  id: null,
  pointName: '',
  itemId: '',
  location: '',
  status: '0',
  checkMode: '9999'
});

const rules = ref({
  pointName: [{ required: true, message: '请输入巡检点名称', trigger: 'blur' }],
  itemId: [{ required: true, message: '请选择巡检项目', trigger: 'change' }],
  checkMode: [{ required: true, message: '请选择打卡方式', trigger: 'change' }],
  location: [{ required: true, message: '请选择巡检点位置', trigger: 'change' }]
});

// !== 初始化 =============================================================================

const pointId = ref(null);
const pointItemlist = ref([]);
const checkoutPointItemlist = ref([]);
function checkoutItem(id: string) {
  form.value.itemId = ''; // 每次点击都先清空 itemId
  if (checkoutPointItemlist.value.includes(id)) {
    checkoutPointItemlist.value = checkoutPointItemlist.value.filter((item) => item !== id);
  } else {
    checkoutPointItemlist.value.push(id);
  }
  form.value.itemId = checkoutPointItemlist.value.join(','); // 将选中的 id 数组转换为逗号分隔的字符串
}
function init() {
  // 获取巡检项目列表
  listItem().then((res) => {
    pointItemlist.value = res.rows;
  });

  if (route.query.id) {
    pointId.value = route.query.id;
    // 获取巡检点详情
    getPoint(pointId.value).then((res) => {
      form.value = {
        ...form.value,
        ...res.data
      };
      // 如果有 itemId，拆分到 checkoutPointItemlist
      if (res.data.itemId) {
        checkoutPointItemlist.value = res.data.itemId.split(',');
      }
    });
  }
}
init();

// !== 提交 =============================================================================
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 设置 itemId
      form.value.itemId = checkoutPointItemlist.value.join(',');
      if (pointId.value) {
        updatePoint(form.value).then((res) => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        addPoint(form.value).then((res) => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
// 返回
const cancelForm = () => {
  router.push({
    path: '/inspection/point'
  });
};

// ! map
const mapReady = ref(false);
const map = ref(null);
const marker = ref(null);
const villageid = localStorage.getItem('villageid');
onMounted(async () => {
  await nextTick();

  window._AMapSecurityConfig = { securityJsCode: '09534b3534d8da53968529a9ce164118' };

  AMapLoader.load({
    key: '8e302fe1be5f4db62bc734db23dca149',
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.Marker']
  }).then(async (AMap) => {
    const villageinfo = await getVillageByIdAPI(villageid);
    map.value = new AMap.Map('containerMap', {
      viewMode: '3D',
      zoom: 11,
      center: [116.397428, 39.90923]
    });

    mapReady.value = true;
    handleMap(AMap);
    initLocation(AMap);
  });
});

/** 清空选择地点 */
function clearLocation() {
  form.value.location = '';
  if (marker.value) {
    map.value.remove(marker.value);
    marker.value = null;
  }
}

function handleMap(AMap) {
  // 添加点击事件
  map.value.on('click', (e) => {
    const lnglat = e.lnglat;
    form.value.location = `${lnglat.lng},${lnglat.lat}`;
    // 如果有 marker.value，先移除
    if (marker.value) {
      map.value.remove(marker.value);
    }
    // 添加新 marker
    marker.value = new AMap.Marker({
      position: lnglat,
      map: map.value,
      title: form.value.pointName || '巡检点'
    });
  });
}

const initLocation = (AMap) => {
  if (!map.value || !form.value.location) return;

  const [lng, lat] = form.value.location.split(',').map((v) => Number(v.trim()));
  if (!Number.isFinite(lng) || !Number.isFinite(lat)) return;
  if (!lng || !lat) return;

  const lnglat = new AMap.LngLat(lng, lat);
  map.value.setCenter(lnglat);
  map.value.setZoom(16);

  if (marker.value) {
    map.value.remove(marker.value);
  }

  marker.value = new AMap.Marker({
    position: lnglat,
    map: map.value,
    title: form.value.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: 20px;
        margin-bottom: 10px;
        max-width: 200px;
        min-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        text-wrap: nowrap;
        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;
        }
        &.disabled {
          border-color: #eeeeee5b;
          color: #fff;
          cursor: not-allowed;
          background-color: #d1d1d1;
        }
      }
    }

    .map {
      width: 100%;
      min-height: 500px;
      background-color: #f0f0f0;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-top: 10px;
    }
    .tips {
      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>
