<template>
  <div class="base-container">
    <fnHeader></fnHeader>
    <div class="top-bg"></div>
    <div class="top">
      <div class="back btn" @click="goBack">
        <img class="icon" src="@/assets/images/common/back-icon.png" alt="" />
        <span>返回</span>
      </div>
      <div class="search">
        <el-select
          v-model="locationVal"
          filterable
          remote
          effect="dark"
          reserve-keyword
          placeholder="搜索地区"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="handleSearchRes"
          class="v-select"
        >
          <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
          <el-option
            v-for="(item, index) in locationOptions.list"
            :key="index"
            :label="item.title"
            :value="item.point"
          >
            <span>{{ item.title }}</span>
            <span class="sub-title"
              >{{ item.province }}{{ item.city }}{{ item.district }}</span
            >
          </el-option>
        </el-select>
        <div class="upload btn" @click="handleExport">
          <img class="icon" src="@/assets/images/common/back-icon.png" alt="" />
          <span>导出</span>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="box">
        <div class="map-box">
          <div ref="mapRef" class="map"></div>
        </div>
        <div class="tool-group">
          <!-- <div class="btn">
            <img
              class="icon"
              src="@/assets/images/common/back-black-icon.png"
              alt=""
            />
            <span>撤销</span>
          </div>
          <div class="btn">
            <el-icon size="15"><CloseBold /></el-icon>
            <span>删除点</span>
          </div> -->
          <div class="btn delete" @click="handleDelete" v-show="isEdit">
            <el-icon size="15" color="#fff"><CloseBold /></el-icon>
            <span>删除地块</span>
          </div>
        </div>
        <div class="edit-popup" v-show="isEdit">
          <div class="edit-title">
            <div class="name">
              <img src="@/assets/images/common/chart-icon.png" alt="" />
              <span>地块属性</span>
            </div>
            <div v-show="disabledForm" class="edit" @click="handleEdit">
              编辑
            </div>
          </div>
          <div class="edit-cont">
            <el-form
              :inline="true"
              :disabled="disabledForm"
              :model="formInline"
              label-position="top"
              class="form-inline"
            >
              <el-form-item label="农场地址">
                <el-input
                  v-model="formInline.address"
                  placeholder="请输入农场地址"
                  clearable
                />
              </el-form-item>
              <el-form-item label="农场名称">
                <el-input
                  v-model="formInline.farmName"
                  placeholder="请输入农场名称"
                  clearable
                />
              </el-form-item>
              <el-form-item label="创建时间">
                <el-input v-model="formInline.createDate" clearable disabled />
              </el-form-item>
              <el-form-item label="农场面积">
                <el-input v-model="formInline.area" disabled clearable />
              </el-form-item>
              <el-form-item label="作物物种">
                <el-input
                  v-model="formInline.speciesTypeName"
                  placeholder="请输入作物物种"
                  clearable
                />
              </el-form-item>
              <el-form-item label="客户姓名">
                <el-input
                  v-model="formInline.masterName"
                  placeholder="请输入姓名"
                  clearable
                />
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input
                  v-model="formInline.masterTel"
                  placeholder="请输入联系电话"
                  clearable
                />
              </el-form-item>
            </el-form>
            <div class="list-box" v-show="pointList.length > 0">
              <span>边界点经纬度</span>
              <div class="list-cont">
                <div
                  class="list-item"
                  v-for="(item, index) in pointList"
                  :key="index"
                >
                  <span>A{{ index + 1 }}</span>
                  <div class="item-box">
                    北纬{{ item.lat }}，东经{{ item.lnt }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="edit-footer">
            <div @click="onCancel" class="btn cancel">取消</div>
            <div @click="onSubmit" class="btn save">保存</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 导出弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    width="82%"
    center
    :show-close="false"
    modal-class="dialog-dark"
  >
    <div>
      <el-table :data="gridData" border max-height="600" class="table-dark">
        <el-table-column
          property="farmName"
          label="农场名称"
          show-overflow-tooltip
        />
        <el-table-column
          property="address"
          label="农场地址"
          width="230"
          show-overflow-tooltip
        />
        <el-table-column property="createDate" label="创建时间" width="170" />
        <el-table-column property="mu" label="农场面积">
          <template #default="scope">
            <span>{{ scope.row.mu.toFixed(2) }}亩</span>
          </template>
        </el-table-column>
        <el-table-column property="speciesTypeName" label="作物物种" />
        <el-table-column property="masterName" label="客户姓名" />
        <el-table-column property="masterTel" label="联系电话" />
        <el-table-column
          property="points"
          label="边界点经纬度"
          width="480"
          show-overflow-tooltip
        />
      </el-table>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button class="btn" @click="dialogVisible = false">取消</el-button>
        <el-button class="btn" type="primary" @click="handleDowload">
          下载
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, watchEffect } from "vue";
import fnHeader from "@/components/fnHeader.vue";
import AuthenticMap from "./authenticMap";
import { mapData } from "./authenticMap";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { dateFormat } from "@/utils/date_util";
import { exportExcel } from "@/utils/index";
const router = useRouter();

let authenticMap = new AuthenticMap();
const mapRef = ref();
const location = ref("POINT (113.78049350268851 23.419886891845312)");

onMounted(() => {
  getList(true);
});

// 获取地块列表
const plotList = ref([]);
const getList = (isInitMap = false,a=false) => {
  VE_API.authentic.getList().then(({ code, data }) => {
    if (code !== 0) return authenticMap.initMap(location.value, mapRef.value);
    plotList.value = data || [];
    if (isInitMap) {
      authenticMap.initMap(data[0].point, mapRef.value);
      const geom = [];
      data.forEach((item) => {
        geom.push({ featureWkt: item.geom });
      });
      authenticMap.setAreaGeometry(geom);
    }
    if(a){
    const geom = [];
    console.log('data',data);
      data.forEach((item) => {
        geom.push({ featureWkt: item.geom });
      });
        authenticMap.setAreaGeometry(geom);
        authenticMap.c()
    }
    // const geom = [];
    //   data.forEach((item) => {
    //     geom.push({ featureWkt: item.geom });
    //   });
    //   authenticMap.setAreaGeometry(geom);
    //   authenticMap.c()
    authenticMap.addPoint(data);
  });
};

// 搜索
const locationVal = ref("");
const loading = ref(false);
const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";

const handleSearchRes = (v) => {
  authenticMap.setMapCenter(v);
};

const locationOptions = reactive({
  list: [],
});
const remoteMethod = async (keyword) => {
  if (keyword) {
    locationOptions.list = [];
    loading.value = true;
    const params = {
      key: MAP_KEY,
      keyword,
      // location: store.getters.userLocation,
      location: "22.574540836684672,113.1093017627431",
    };
    await VE_API.old_mini_map
      .getCtiyList({ word: keyword })
      .then(({ data }) => {
        if (data && data.length) {
          data.forEach((item) => {
            item.point = item.location.lat + "," + item.location.lng;
            locationOptions.list.push(item);
          });
        }
      });
    VE_API.old_mini_map.search(params).then(({ data }) => {
      loading.value = false;
      data.forEach((item) => {
        item.point = item.location.lat + "," + item.location.lng;
        locationOptions.list.push(item);
      });
    });
  } else {
    locationOptions.list = [];
  }
};

const initForm = {
  address: "",
  farmName: "",
  createDate: "",
  area: "",
  speciesTypeName: "",
  masterName: "",
  masterTel: "",
  geom: "",
};
const formInline = reactive({
  ...initForm,
});
const disabledForm = ref(false);

const isEdit = ref(false);

// 编辑
const handleEdit = () => {
  disabledForm.value = false;
};

// 取消
const onCancel = () => {
  isEdit.value = false;
  authenticMap.startDraw();
    // authenticMap.b();
//   console.log('mapData.curPointData.id',mapData.curPointData.id);
//   if (!mapData.curPointData.id || mapData.selectPointArr.length) return;
  authenticMap.setPoint("point");
};

// 保存
const onSubmit = () => {
  VE_API.authentic.saveData(formInline).then((res) => {
    if (formInline.id) {
      onCancel();
    } else {
      isEdit.value = false;
      authenticMap.startDraw();
    }
    // authenticMap.b()
    getList();
  });
};

// 返回
const goBack = () => {
  router.go(-1);
};

function updateFormInline(newData) {
  Object.assign(formInline, newData);
}

const handleDelete = () => {
  if (!mapData.curPointData.id) return ElMessage("请选择地块");
  const id = mapData.selectPointArr.map((item) => item.values_.id);
  ElMessageBox.confirm("您确定删除该地块吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      VE_API.authentic
        .deleteData({ id:id[0] })
        .then((res) => {
          authenticMap.b();
          onCancel();
          getList(false,true);
        });
    })
    .catch(() => {});
};

// 导出
const gridData = ref([]);
const dialogVisible = ref(false);
const handleExport = () => {
  if (mapData.selectPointArr.length < 1) return ElMessage("请选择地块");
  const ids = mapData.selectPointArr.map((item) => item.values_.id);
  VE_API.authentic.exportData(ids).then(({ data }) => {
    gridData.value = data.map((item) => {
      return {
        ...item,
        createDate: dateFormat(
          new Date(item.createDate),
          "YYYY-mm-dd HH:MM:SS"
        ),
      };
    });
    dialogVisible.value = true;
  });
};

// 下载
const handleDowload = () => {
  const fieldLabels = [
    "农场名称",
    "农场地址",
    "创建时间",
    "农场面积",
    "作物物种",
    "客户姓名",
    "联系电话",
    "边界点经纬度",
  ];
  const fieldKeys = [
    "farmName",
    "address",
    "createDate",
    "mu",
    "speciesTypeName",
    "masterName",
    "masterTel",
    "points",
  ];
  const fileName = "农场数据" + dateFormat(new Date(), "YYYY-mm-dd");
  exportExcel(gridData.value, fieldLabels, fieldKeys, fileName);
};

const pointList = ref([]);

// 获取编辑回显数据
const getDetailsData = (id) => {
  VE_API.authentic.getDetails({ id }).then(({ data }) => {
    isEdit.value = true;
    disabledForm.value = true;

    data.createDate = dateFormat(
      new Date(data.createDate),
      "YYYY-mm-dd HH:MM:SS"
    );
    updateFormInline({ ...data });
    const { area } = authenticMap.getAreaGeometry();
    formInline.area = area + "亩";

    //   经纬度列表
    const arr = JSON.parse(data.points);
    pointList.value = arr.map((item) => {
      return {
        lat: item[1].toString().slice(0, 6),
        lnt: item[0].toString().slice(0, 7),
      };
    });
    authenticMap.endEdit();
  });
};

watchEffect(() => {
  updateFormInline({ ...initForm });
  pointList.value = [];
  isEdit.value = false;
  if (mapData.isEdit && mapData.selectPointArr.length < 2) {
    isEdit.value = true;
    disabledForm.value = false;
    const { geometryArr, area } = authenticMap.getAreaGeometry();
    const lastItem = geometryArr[geometryArr.length - 1];
    formInline.geom = lastItem.featureWkt;
    formInline.area = area + "亩";
    formInline.createDate = dateFormat(new Date(), "YYYY-mm-dd HH:MM:SS");
    authenticMap.endEdit();
  }

  if (mapData.isEditArea) {
    const { geometryArr, area } = authenticMap.getAreaGeometry();
    formInline.geom = geometryArr[0].featureWkt;
    formInline.area = area + "亩";
  }

  if (
    mapData.curPointData.id &&
    !mapData.isEdit &&
    mapData.selectPointArr.length === 1
  ) {
    const id = mapData.selectPointArr.map((item) => item.values_.id);
    getDetailsData(id[0]);
  }
});
</script>

<style lang="scss" scoped>
.base-container {
  width: 100%;
  height: 100vh;
  color: #fff;
  box-sizing: border-box;
  z-index: 1;
  position: relative;
  .top-bg {
    position: absolute;
    top: 0;
    width: 100%;
    height: 74px;
    background: #101010;
    z-index: -1;
  }
  .btn {
    display: flex;
    align-items: center;
    padding: 6px 16px;
    border-radius: 4px;
    cursor: pointer;
    .icon {
      width: 13px;
      height: 13px;
    }
    span {
      margin-left: 10px;
    }
  }

  .top {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    background: #101010;
    padding: 17px 20px 0 20px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .back {
      border: 1px solid rgba(255, 255, 255, 0.4);
    }
    .search {
      display: flex;
      .v-select {
        width: 300px;
        ::v-deep {
          .el-select__wrapper {
            background: #101010;
            box-shadow: none;
            border: 1px solid rgba(255, 255, 255, 0.7);
            .el-select__input {
              color: #fff;
            }
          }
        }
      }
      .upload {
        background: #2199f8;
        margin-left: 25px;
      }
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 74px - 40px);
    box-sizing: border-box;
    background: #101010;
    padding: 13px 20px 20px 20px;
    .box {
      border: 1px solid rgba(255, 255, 255, 0.4);
      border-radius: 8px;
      padding: 20px;
      box-sizing: border-box;
      background: #232323;
      width: 100%;
      height: 100%;
      position: relative;
      .map-box {
        width: 100%;
        height: 100%;
        border-radius: 4px;
        border: 1px solid rgba(255, 255, 255, 0.4);
        .map {
          width: 100%;
          height: 100%;
        }
      }

      .tool-group {
        position: absolute;
        display: flex;
        right: calc(500px + 36px);
        top: 42px;
        .btn {
          background: #fff;
          color: #000;
          margin-right: 10px;
        }
        .delete {
          background: #e45c5c;
          color: #fff;
        }
      }
      .edit-popup {
        width: 500px;
        height: calc(100% - 53px - 20px);
        position: absolute;
        top: 36px;
        right: 36px;
        border: 1px solid rgba(255, 255, 255, 0.4);
        border-radius: 8px;
        background: #232323;
        .edit-title {
          padding: 0 10px;
          background: rgba(68, 68, 68, 0.4);
          border-bottom: 1px solid rgba(68, 68, 68, 0.4);
          display: flex;
          align-items: center;
          justify-content: space-between;
          .name {
            display: flex;
            padding: 12px 0px;
            align-items: center;
          }
          span {
            margin-left: 8px;
            font-size: 18px;
            font-family: "SOURCEHANTIFINE";
          }
          .edit {
            color: #2199f8;
            padding: 6px 20px;
            border: 1px solid #2199f8;
            border-radius: 4px;
            cursor: pointer;
          }
        }
        .edit-cont {
          padding: 16px;
          width: calc(100% - 32px);
          height: calc(100% - 64px - 84px);
          .form-inline {
            ::v-deep {
              .el-input {
                width: 200px;
                --el-input-placeholder-color: #666666;
              }
              .el-form-item__label {
                color: #bbbbbb;
              }
              .el-input__wrapper {
                background: #232323;
                border: 1px solid #444444;
                box-shadow: none;
                .el-input__inner {
                  color: #fff;
                }
              }
            }
          }
          .list-box {
            width: 100%;
            span {
              color: #bbbbbb;
            }
            .list-cont {
              width: 100%;
              height: 234px;
              border-radius: 4px;
              margin-top: 5px;
              background: rgba(68, 68, 68, 0.4);
              display: flex;
              flex-wrap: wrap;
              align-content: flex-start;
              justify-content: space-between;
              padding: 12px 16px;
              box-sizing: border-box;
              overflow-y: auto;

              .list-item {
                width: 47.5%;
                margin-bottom: 12px;
                .item-box {
                  padding: 8px;
                  border: 1px solid #444444;
                  border-radius: 4px;
                  margin-top: 5px;
                }
              }
            }
          }
        }
        .edit-footer {
          width: 100%;
          height: 64px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          box-sizing: border-box;
          padding: 12px 16px;
          border-top: 1px solid rgba(68, 68, 68, 0.4);
          background: rgba(68, 68, 68, 0.4);
          .btn {
            padding: 10px 35px;
          }
          .cancel {
            border: 1px solid rgba(255, 255, 255, 0.4);
            margin-right: 16px;
          }
          .save {
            background: #2199f8;
          }
        }
      }
    }
  }
}
.dialog-footer {
  .btn {
    width: 200px;
    height: 40px;
  }
}
</style>
