<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="communityName">
        <el-input
          v-model="queryParams.communityName"
          placeholder="请输入小区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.sys_is_enable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="['business:community: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="['business:community: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="['business:community: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="['business:community:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="communityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="communityId" v-if="false"/>-->
      <el-table-column label="小区名称" align="center" prop="communityName" />
      <el-table-column label="地理位置经度" align="center" prop="longitude" />
      <el-table-column label="地理位置纬度" align="center" prop="latitude" />
<!--      <el-table-column label="地理位置精度" align="center" prop="locPrecision" />-->
      <el-table-column label="是否启用" align="center" prop="isEnable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
        </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="['business:community:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:community: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="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="小区名称" prop="communityName">
          <el-input v-model="form.communityName" placeholder="请输入小区名称" />
        </el-form-item>
        <!-- 地图选点部分 -->
        <el-form-item label="地理位置" prop="latitude">
          <div style="display: flex; margin-bottom: 10px;">
            <el-input v-model="form.longitude" disabled placeholder="经度" style="width: 200px; margin-right: 10px;" readonly />
            <el-input v-model="form.latitude" disabled placeholder="纬度" style="width: 200px; margin-right: 10px;" readonly />
            <el-button type="primary" @click="openMapDialog">选择位置</el-button>
          </div>
          <!-- 地图容器 -->
<!--          <div id="map-container" style="width: 100%; height: 300px; border: 1px solid #ddd;"></div>-->
        </el-form-item>
<!--        <el-form-item label="地理位置精度" prop="locPrecision">-->
<!--          <el-input v-model="form.locPrecision" placeholder="请输入地理位置精度" />-->
<!--        </el-form-item>-->
        <el-form-item label="是否启用" prop="isEnable">
          <el-select v-model="form.isEnable" style="width: 100%" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.sys_is_enable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图选择对话框 - 已优化 -->
    <el-dialog title="选择位置" :visible.sync="mapDialogVisible" width="80%" append-to-body>
<!--      <div style="margin-bottom: 10px;">-->
<!--        <el-input-->
<!--          v-model="searchKeyword"-->
<!--          placeholder="请输入地点名称进行搜索"-->
<!--          clearable-->
<!--          style="width: 300px; margin-right: 10px;"-->
<!--          @keyup.enter.native="handleSearch"-->
<!--        />-->
<!--        <el-button type="primary" @click="handleSearch">搜索</el-button>-->
<!--        <el-button @click="locateCurrentPosition" v-if="supportGeolocation">定位当前位置</el-button>-->
<!--      </div>-->
      <div id="big-map-container" style="width: 100%; height: 500px;" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommunity, getCommunity, delCommunity, addCommunity, updateCommunity } from "@/api/business/community";
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: "Community",
  dicts: ['sys_is_enable'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小区表格数据
      communityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        communityName: undefined,
        latitude: undefined,
        longitude: undefined,
        locPrecision: undefined,
        isEnable: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        communityName: [
          { required: true, message: "小区名称不能为空", trigger: "blur" }
        ],
        latitude: [
          { required: true, message: "地理位置不能为空", trigger: "change" }
        ],
        // longitude: [
        //   { required: true, message: "地理位置经度不能为空", trigger: "blur" }
        // ],
        // locPrecision: [
        //   { required: true, message: "地理位置精度不能为空", trigger: "blur" }
        // ],
        isEnable: [
          { required: true, message: "是否启用不能为空", trigger: "change" }
        ],
      },
      // 新增地图相关数据
      mapDialogVisible: false,
      map: null, // 主地图实例
      bigMap: null, // 大地图实例
      marker: null, // 标记点
      selectedPosition: null, // 选中的位置
      // 新增地图搜索相关数据
      searchKeyword: '', // 搜索关键词
      placeSearch: null, // 地点搜索服务
      supportGeolocation: false, // 是否支持定位
      geolocation: null, // 定位服务
    };
  },
  created() {
    this.getList();
    // 检测浏览器是否支持定位
    this.supportGeolocation = 'geolocation' in navigator;
  },
  methods: {
    /** 查询小区列表 */
    getList() {
      this.loading = true;
      listCommunity(this.queryParams).then(response => {
        this.communityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        communityId: undefined,
        communityName: undefined,
        latitude: undefined,
        longitude: undefined,
        locPrecision: undefined,
        isEnable: 1,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.communityId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const communityId = row.communityId || this.ids
      getCommunity(communityId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改小区";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.communityId != null) {
            updateCommunity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCommunity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const communityIds = row.communityId || this.ids;
      this.$modal.confirm('是否确认删除小区编号为"' + communityIds + '"的数据项？').then(() => {
        this.loading = true;
        return delCommunity(communityIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/community/export', {
        ...this.queryParams
      }, `community_${new Date().getTime()}.xlsx`)
    },

    // 打开地图选择对话框
    openMapDialog() {
      this.mapDialogVisible = true;
      this.$nextTick(() => {
        this.initBigMap();
      });
    },

    async initBigMap() {
      try {
        // 销毁旧实例
        if (this.bigMap) {
          this.bigMap.destroy();
          this.bigMap = null;
        }

        // 配置安全密钥（如果启用了）
        window._AMapSecurityConfig = {
          securityJsCode: '44255e7f71b0344ad567cfcff4c8e381'
        };

        // 异步加载AMap
        const AMap = await AMapLoader.load({
          key: 'ed6cc1d37c6db81aac6d65c9d7d1b4d8', // 替换为你的Key
          version: '2.0',
          plugins: [
            'AMap.Scale', // 比例尺
            'AMap.ToolBar', // 缩放工具条
            'AMap.ControlBar', // 3D控制
            'AMap.HawkEye', // 鹰眼图
            'AMap.MapType', // 地图类型切换
            'AMap.Geolocation', // 定位
            'AMap.PlaceSearch', // 地点搜索
            'AMap.AutoComplete' // 输入提示
          ]
        });

        // 创建新实例
        this.bigMap = new AMap.Map('big-map-container', {
          zoom: 15,
          viewMode: '3D', // 开启3D视图
          center: this.form.longitude && this.form.latitude
            ? [parseFloat(this.form.longitude), parseFloat(this.form.latitude)]
            : [113.613951, 34.721327] // 默认中心点
        });

        // 添加地图控件
        this.bigMap.addControl(new AMap.Scale());
        this.bigMap.addControl(new AMap.ToolBar());
        this.bigMap.addControl(new AMap.ControlBar());
        this.bigMap.addControl(new AMap.HawkEye({isOpen: true}));
        this.bigMap.addControl(new AMap.MapType());

        // 初始化地点搜索服务
        this.placeSearch = new AMap.PlaceSearch({
          map: this.bigMap,
          pageSize: 5,
          pageIndex: 1,
          citylimit: true
        });

        // 初始化定位服务
        this.geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位
          timeout: 10000, // 超时时间
          buttonPosition: 'RB', // 定位按钮位置
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮偏移
          zoomToAccuracy: true // 定位成功后是否自动调整视野
        });
        this.bigMap.addControl(this.geolocation);

        // 添加标记（如果已有坐标）
        if (this.form.longitude && this.form.latitude) {
          this.marker = new AMap.Marker({
            position: [parseFloat(this.form.longitude), parseFloat(this.form.latitude)],
            map: this.bigMap,
            draggable: true // 可拖动
          });

          // 监听标记拖动事件
          this.marker.on('dragend', (e) => {
            this.selectedPosition = {
              lng: e.lnglat.getLng(),
              lat: e.lnglat.getLat()
            };
          });
        }

        // 点击事件
        this.bigMap.on('click', (e) => {
          this.selectedPosition = {
            lng: e.lnglat.getLng(),
            lat: e.lnglat.getLat()
          };

          // 清除旧标记
          if (this.marker) {
            this.marker.setMap(null);
          }

          // 添加新标记
          this.marker = new AMap.Marker({
            position: [this.selectedPosition.lng, this.selectedPosition.lat],
            map: this.bigMap,
            draggable: true
          });

          // 监听标记拖动事件
          this.marker.on('dragend', (e) => {
            this.selectedPosition = {
              lng: e.lnglat.getLng(),
              lat: e.lnglat.getLat()
            };
          });
        });

      } catch (error) {
        console.error('地图初始化失败:', error);
        this.$message.error('地图加载失败，请检查Key配置');
      }
    },

    // 搜索地点
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      if (this.placeSearch) {
        this.placeSearch.search(this.searchKeyword, (status, result) => {
          if (status === 'complete' && result.poiList.pois.length) {
            const firstResult = result.poiList.pois[0];
            this.selectedPosition = {
              lng: firstResult.location.lng,
              lat: firstResult.location.lat
            };

            // 清除旧标记
            if (this.marker) {
              this.marker.setMap(null);
            }

            // 添加新标记
            this.marker = new AMap.Marker({
              position: [this.selectedPosition.lng, this.selectedPosition.lat],
              map: this.bigMap,
              draggable: true
            });

            // 移动到搜索结果
            this.bigMap.setCenter([this.selectedPosition.lng, this.selectedPosition.lat]);

            // 监听标记拖动事件
            this.marker.on('dragend', (e) => {
              this.selectedPosition = {
                lng: e.lnglat.getLng(),
                lat: e.lnglat.getLat()
              };
            });
          } else {
            this.$message.warning('未找到相关地点');
          }
        });
      }
    },

    // 定位当前位置
    locateCurrentPosition() {
      if (this.geolocation) {
        this.geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            this.selectedPosition = {
              lng: result.position.lng,
              lat: result.position.lat
            };

            // 清除旧标记
            if (this.marker) {
              this.marker.setMap(null);
            }

            // 添加新标记
            this.marker = new AMap.Marker({
              position: [this.selectedPosition.lng, this.selectedPosition.lat],
              map: this.bigMap,
              draggable: true
            });

            // 移动到当前位置
            this.bigMap.setCenter([this.selectedPosition.lng, this.selectedPosition.lat]);

            // 监听标记拖动事件
            this.marker.on('dragend', (e) => {
              this.selectedPosition = {
                lng: e.lnglat.getLng(),
                lat: e.lnglat.getLat()
              };
            });
          } else {
            this.$message.error('定位失败: ' + result.message);
          }
        });
      }
    },

    confirmLocation() {
      if (this.selectedPosition) {
        this.form.longitude = this.selectedPosition.lng.toString();
        this.form.latitude = this.selectedPosition.lat.toString();
        this.mapDialogVisible = false;
      } else {
        this.$message.warning('请先选择位置');
      }
    },
  }
};
</script>
