<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 id="big-map-container" style="width: 100%; height: 500px;"></div>
      <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, // 选中的位置
    };
  },
  created() {
    this.getList();
  },
  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;
        }

        // 异步加载AMap
        const AMap = await AMapLoader.load({
          key: 'ed6cc1d37c6db81aac6d65c9d7d1b4d8', // 替换为你的Key
          version: '2.0',
          plugins: ['AMap.Scale']
        });

        // 创建新实例
        this.bigMap = new AMap.Map('big-map-container', {
          zoom: 15,
          center: this.form.longitude && this.form.latitude
            ? [parseFloat(this.form.longitude), parseFloat(this.form.latitude)]
            : [113.613997, 34.721334]
        });

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

        // 点击事件
        this.bigMap.on('click', (e) => {
          this.selectedPosition = {
            lng: e.lnglat.getLng(),
            lat: e.lnglat.getLat()
          };
          new AMap.Marker({  // 实时更新标记
            position: [this.selectedPosition.lng, this.selectedPosition.lat],
            map: this.bigMap
          });
        });

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

    confirmLocation() {
      if (this.selectedPosition) {
        this.form.longitude = this.selectedPosition.lng.toString();
        this.form.latitude = this.selectedPosition.lat.toString();
        this.mapDialogVisible = false;
      }
    },

    // 在大地图上显示标记
    showMarkerOnBigMap(position) {
      if (this.marker) {
        this.marker.setPosition(position);
      } else {
        this.marker = new AMapLoader.Marker({
          position: position,
          map: this.bigMap
        });
      }
      this.bigMap.setCenter(position);
    },
  }
};
</script>
