<template>
  <div class="iot-region-table">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="区域编号" prop="regionCode">
        <el-input
          v-model="queryParams.regionCode"
          placeholder="请输入区域编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          size="small"
          @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="['iot:project:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="tableLoading"
      :data="list"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexFormatter"
        width="80px"
      ></el-table-column>
      <el-table-column label="区域编码" align="left" prop="regionCode" />
      <el-table-column label="区域名称" align="left" prop="regionName" />
      <el-table-column label="区域地址" align="left" prop="regionAddr" >
        <template slot-scope="scope">
          <span class="lay-table-textarea" :title="scope.row.regionAddr">
            {{ scope.row.regionAddr }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center" prop="recordStatus" :formatter="statusFormat" />
      <el-table-column
        label="创建时间"
        sortable="custom"
        align="center"
        width="160"
        prop="createTime"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetails(scope.row)"
            v-hasPermi="['system:region:edit']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:region:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:region: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
      class="eldialog-wrap"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="720px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域名称:" prop="regionName">
              <el-input
                v-model="form.regionName"
                placeholder="请输入区域名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="区域编号:" prop="regionCode">
             <el-input
                v-model="form.regionCode"
                placeholder="请输入区域编号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="状态:" prop="recordStatus">
              <el-radio-group v-model="form.recordStatus" style="width: 100%">
                <el-radio
                  v-for="dict in regionStatusOptions"
                  :key="dict.dictValue"
                  :label="Number(dict.dictValue)"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="行政区划" prop="regionalismId">
            <treeselect
              @select="regionalismChange"
              :disable-branch-nodes="true"
              v-model="form.regionalismId"
              :options="regionalismOption"
              :normalizer="normalizer"
              placeholder="请选择上级行政区划"
            />
          </el-form-item> -->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目经度" prop="longitude">
              <el-input
                v-model="form.longitude"
                disabled
                placeholder="请输入项目经度"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目纬度" prop="latitude">
              <el-input
                v-model="form.latitude"
                disabled
                placeholder="请输入项目纬度"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="regionAddr">
              <el-input
                v-model="form.regionAddr"
                @blur="mapAddressFromPoint"
                placeholder="请输入详细地址"
              >
                <el-popover
                  slot="suffix"
                  placement="left-start"
                  title="地图选择坐标"
                  width="730"
                  trigger="manual"
                  v-model="visible"
                >
                  <i
                    slot="reference"
                    class="el-icon-map-location"
                    @click="mapClick"
                  ></i>
                  <slot>
                    <el-row>
                      <el-col :span="7">
                        <span>经度：{{ mapForm.lng }}</span>
                      </el-col>
                      <el-col :span="7">
                        <span>纬度：{{ mapForm.lat }}</span>
                      </el-col>
                      <el-col :span="10">
                        <span>地址：{{ mapForm.address }}</span>
                      </el-col>
                    </el-row>

                    <shop-location
                      v-if="visible === true"
                      style="height: 300px"
                      :mapCenter="mapCenter"
                      :draggable="true"
                      @mapEvent="mapEvent"
                      :zoom="zoom"
                    />

                    <div
                      style="
                        width: 100%;
                        height: 50px;
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;
                        margin-top: 5px;
                      "
                    >
                      <el-button type="primary" @click="mapSureClick"
                        >确 定</el-button
                      >
                      <el-button @click="visible = false">取 消</el-button>
                    </div>
                  </slot>
                </el-popover>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="总路设备:">
          <el-input
            v-model="form.projectDeviceName"
            suffix-icon="el-icon-caret-bottom"
            @focus="openTableSelectDialog()"
            placeholder="请输入总路设备"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { initMap, gjzCode } from "@/utils/latlngFromAddress.js";
import ShopLocation from "@/components/Amap/components/shopLocation/index";
import {
  listRegion,
  getRegion,
  addRegion,
  updateRegion,
  delRegion,
} from "@/api/iot/region";
export default {
  name: "IotRegionTable",
  components: {
    Treeselect,
    ShopLocation,
  },
  data() {
    return {
      list: [],
      open: false,
      tableLoading: false,
      title: "",
      regionStatusOptions: [],
      showSearch: true,
      mapCenter: {
        lng: 119.459889,
        lat: 25.98974,
      },
      mapForm: {},
      baiduMapKey: "N05AG95Umzs3fouk6WpFqtGxcDlw0fRn",
      zoom: 15,
      BMap: null,
      map: null,
      visible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      total: 0,
      // 表单校验
      rules: {
        recordId: [
          { required: true, message: "编号 记录ID不能为空", trigger: "blur" },
        ],
        recordStatus: [
          { required: true, message: "记录状态不能为空", trigger: "blur" },
        ],
        regionName: [
          { required: true, message: "区域名称不能为空", trigger: "blur" },
        ],
        regionCode: [
          { required: true, message: "区域编号不能为空", trigger: "blur" },
        ]
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("region_status").then((response) => {
      this.regionStatusOptions = response.data;
    });
  },
  methods: {
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.regionStatusOptions, row.regionStatus);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.recordId != null) {
            updateRegion(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegion(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delRegion(row.regionCode);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        recordStatus: 0,
        regionCode: null,
        regionName: null,
        regionAddr: null,
        latitude: null,
        longitude: null,
      };
      this.resetForm("form");
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.tableLoading = true;
      listRegion(this.queryParams).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.tableLoading = false;
      });
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    handleUpdate(row) {
      this.reset()
      getRegion(row.regionCode).then(res => {
        this.form = Object.assign(this.form, res.data)
        this.open = true;
        this.title = "编辑区域";
      })
    },
    handleDetails(row) {
      this.$emit("handleEvent", { event: "linkDetail", value: row });
    },
    // 地图方法
    handler({ BMap, map }) {
      //地图
      this.BMap = BMap;
      this.map = map;
      this.mapLoading = false;
      // this.getPointByIp()
    },
    mapEvent(data) {
      this.mapForm.lng = data.lng;
      this.mapForm.lat = data.lat;
      this.mapForm.address = data.address;
      this.$forceUpdate();
    },
    // 使用地图方式定位
    mapClick() {
      if (this.form.longitude && this.form.latitude) {
        this.mapCenter.lng = this.form.longitude;
        this.mapCenter.lat = this.form.latitude;
        this.mapForm.lng = this.form.longitude;
        this.mapForm.lat = this.form.latitude;
        this.mapForm.address = this.form.regionAddr;
      } else {
        this.mapCenter = {
          lng: 119.459889,
          lat: 25.98974,
        };
        this.mapForm.lng = 119.459889;
        this.mapForm.lat = 25.98974;
        this.mapForm.address = "";
      }
      this.visible = !this.visible;
      this.$forceUpdate()
    },
    mapSureClick() {
      // 确认的时候将值赋值给form表单并且关闭地图
      this.form.regionAddr = this.mapForm.address
        ? this.mapForm.address
        : this.form.regionAddr;
      this.form.longitude = this.mapForm.lng;
      this.form.latitude = this.mapForm.lat;
      this.visible = false;
    },
    mapAddressFromPoint() {
      if (this.form.regionAddr) {
        // geoCode(this.form.regionAddr, this, { form: 'form', lat: 'shopLat', lng: 'shopLng' })
        gjzCode(this.form.regionAddr, this, {
          form: "form",
          lat: "shopLat",
          lng: "shopLng",
        });
      }
    },
  },
};
</script>