<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="add btn" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>创建</span>
        </div>
        <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">
      <el-form
        :inline="true"
        :model="formInlineSearch"
        class="search-form"
        ref="formInlineRef"
      >
        <el-form-item label="农场地址">
          <el-input
            v-model="formInlineSearch.address"
            placeholder="请输入农场地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="农场名称">
          <el-input
            v-model="formInlineSearch.farmName"
            placeholder="请输入农场名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="作物物种">
          <el-input
            v-model="formInlineSearch.speciesTypeName"
            placeholder="请输入作物物种"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input
            v-model="formInlineSearch.masterName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input
            v-model="formInlineSearch.masterTel"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>
        <div class="button">
          <el-button class="btn" type="primary" @click="onSearch">查询</el-button>
          <el-button class="btn reset" @click="onRest">重置</el-button>
        </div>
      </el-form>
      <div class="box">
        <div class="map-box">
          <div ref="mapRef" class="map"></div>
        </div>
        <div class="tool-group">
          <!-- <div class="btn" @click="handleCancel" v-show="isEdit&&mapData.point">
            <img
              class="icon"
              src="@/assets/images/common/back-black-icon.png"
              alt=""
            />
            <span>撤销</span>
          </div> -->
          <!-- <div class="btn" @click="handleDeletePoint">
            <el-icon size="15"><CloseBold /></el-icon>
            <span>删除点</span>
          </div> -->
          <div class="btn delete" @click="handleDelete" v-show="mapData.selectPointArr.length>0">
            <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 class="btn-group">
                <div v-show="disabledForm" class="edit" @click="handleEdit">
                    编辑
                </div>
                <div v-show="mapData.selectPointArr.length>0" class="edit ml" @click="handlePrint">打印</div>
            </div>
          </div>
          <div class="edit-cont">
            <el-form
              :inline="true"
              ref="ruleFormRef"
              :disabled="disabledForm"
              :model="formInline"
              :rules="rules"
              label-position="top"
              class="form-inline"
            >
              <el-form-item label="农场地址" prop="address">
                <el-input
                  v-model="formInline.address"
                  placeholder="请输入农场地址"
                  clearable
                />
              </el-form-item>
              <el-form-item label="农场名称" prop="farmName">
                <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="作物物种" prop="speciesTypeName">
                <el-input
                  v-model="formInline.speciesTypeName"
                  placeholder="请输入作物物种"
                  clearable
                />
              </el-form-item>
              <el-form-item label="客户姓名" prop="masterName">
                <el-input
                  v-model="formInline.masterName"
                  placeholder="请输入姓名"
                  clearable
                />
              </el-form-item>
              <el-form-item label="联系电话" prop="masterTel">
                <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[1] }}</div>
                  <div class="item-box">东经{{ item[0] }}</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>
  <Pdf :title="formInline.id+''" :showDialog="pdfShow" @closeDialog="pdfShow = false" v-if="formInline.id && pdfShow" :rowId="formInline.id"></Pdf>

</template>

<script setup>
import { onMounted, ref, reactive, watchEffect, watch } 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, parseMultiPolygon } from "@/utils/index";
import Pdf from "./Pdf";
const pdfShow = ref(false)
const router = useRouter();

let authenticMap = new AuthenticMap();
const mapRef = ref();
const userInfo = JSON.parse(sessionStorage.getItem("userinfo"));
const location = ref(userInfo.location);

onMounted(() => {
  authenticMap.initMap(location.value, mapRef.value);
  getList();
});

// 获取地块列表
const plotList = ref([]);
const getList = () => {
  authenticMap.clearLayer();
  return VE_API.authentic.getList(formInlineSearch).then(({ code, data }) => {
    plotList.value = data || [];
    const geom = [];
    data.forEach((item) => {
      geom.push({ featureWkt: item.geom, ...item });
    });
    authenticMap.setAreaGeometry(geom);
    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 rules = {
  address: [{ required: true, message: "请输入农场地址", trigger: "change" }],
  farmName: [{ required: true, message: "请输入农场名称", trigger: "change" }],
  speciesTypeName: [
    { required: true, message: "请输入作物物种", trigger: "change" },
  ],
  masterName: [{ required: true, message: "请输入姓名", trigger: "change" }],
  masterTel: [{ required: true, message: "请输入联系电话", trigger: "change" }],
};
const ruleFormRef = ref(null);
const initForm = {
  id: "",
  address: "",
  farmName: "",
  createDate: "",
  area: "",
  speciesTypeName: "",
  masterName: "",
  masterTel: "",
  geom: "",
};
const formInline = reactive({
  ...initForm,
});
const disabledForm = ref(false);

// 筛选
const formInlineRef = ref(null);
const formInlineSearch = reactive({
  ...initForm,
});

const onSearch = () => {
    isUpdata.value = false
    onCancel()
};

const onRest = () => {
    Object.assign(formInlineSearch, initForm);
    onCancel()
};

const isEdit = ref(false);

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

// 取消
const isUpdata = ref(true);
const onCancel = () => {
  isEdit.value = false;
  authenticMap.setPoint("point");
  authenticMap.clearMapData("isEdit", false);
  authenticMap.endDraw();
  if (isUpdata.value) {
    authenticMap.cancelDraw();
  } else {
    getList();
  }
};

// 保存
const onSubmit = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      VE_API.authentic.saveData(formInline).then((res) => {
        isUpdata.value = false
        disabledForm.value = true;
        const point = mapData.curPointData
        authenticMap.endDraw();
        getList().then(()=>{
            isRefresh.value = false
            isEdit.value = true;
            authenticMap.getSelectPointArr(point.id||plotList.value[plotList.value.length - 1].id)
        })
      });
    }
  });
};

// 打印
const handlePrint = () =>{
    pdfShow.value = true
}

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

function updateFormInline(newData,name) {
  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).then((res) => {
        isUpdata.value = false
        onCancel();
      });
    })
    .catch(() => {});
};

// 创建
const isRefresh = ref(true)
const handleAdd = () => {
    isRefresh.value = false
  authenticMap.clearMapData("curPointData", {});
  authenticMap.clearMapData("isEdit", false);
  authenticMap.setPoint("point");
  updateFormInline({ ...initForm });
  pointList.value = [];
  isEdit.value = false;
  ruleFormRef.value.resetFields();
  if (isUpdata.value) {
    authenticMap.cancelDraw();
  } else {
    getList();
    isUpdata.value = true;
  }
  authenticMap.startDraw();
};

// 删除点
const handleDeletePoint = () => {
  authenticMap.removePoint();
};

// 撤销
const handleCancel = () => {
  authenticMap.undoLastDraw();
//   authenticMap.cancelDraw()
};

// 导出
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 });
    formInline.area = data.mu.toFixed(2) + "亩";

    //   经纬度列表
    let arr = JSON.parse(data.points);
    // 删除最后数组最后一项闭合数据
    arr.pop();
    pointList.value = arr;
  });
};

// 添加经纬度列表
const updatePointList = () => {
  const { geometryArr, area } = authenticMap.getAreaGeometry();
  const lastItem = geometryArr[geometryArr.length - 1];
  formInline.geom = lastItem.featureWkt;
  formInline.area = area + "亩";
  let result = parseMultiPolygon(lastItem.featureWkt);
  result.pop();
  pointList.value = result;
};

watchEffect(() => {
    isRefresh.value = true
  if (mapData.isEdit && mapData.selectPointArr.length < 2&&isRefresh.value) {
    isEdit.value = true;
    disabledForm.value = false;
    isUpdata.value = true;
    formInline.createDate = dateFormat(new Date(), "YYYY-mm-dd HH:MM:SS");
    updatePointList();
    authenticMap.startModify();
  }

  if (mapData.isEditArea) {
    isUpdata.value = false;
    updatePointList();
  }
});

watch(
  () => mapData.selectPointArr,
  (newVale, oldValue) => {
    if (mapData.selectPointArr.length === 1) {
      const id = mapData.selectPointArr.map((item) => item.values_.id);
      getDetailsData(id[0]);
    } else {
        if(isRefresh.value){
            isEdit.value = false;
            authenticMap.endDraw();
        }
    }
  }
);
</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;
    justify-content: flex-end;
    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;
      align-items: center;
      justify-content: flex-end;
      width: 60%;
      .input-with-select {
        margin-left: 25px;
      }
      .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;
      }
      .add {
        background: #fff;
        color: #000;
        margin-left: 25px;
      }
    }
  }

  .content {
    width: 100%;
    height: calc(100% - 74px - 40px);
    box-sizing: border-box;
    background: #101010;
    padding: 13px 20px 20px 20px;
    .search-form {
      height: 40px;
      margin: 5px 0;
      display: flex;
      justify-content: flex-end;
      ::v-deep{
        .el-form-item__label{
            color: #fff;
        }
        .el-form-item__content{
            width: 190px;
        }
        .el-input__wrapper{
            background: #101010;
            box-shadow: none;
            border: 1px solid rgba(255, 255, 255, 0.7);
            .el-input__inner {
              color: #fff;
            }
        }
      }
      .button{
        display: flex;
        .btn{
            width:84px;
            &.reset{
                margin-left: 25px;
            }
        }
      }
    }
    .box {
      border: 1px solid rgba(255, 255, 255, 0.4);
      border-radius: 8px;
      padding: 20px;
      box-sizing: border-box;
      background: #232323;
      width: 100%;
      height: calc(100% - 50px);
      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;
          .btn-group{
            display: flex;
            .ml{
                margin-left: 20px;
            }
          }
          .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 {
            height: 320px;
            ::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%;
            height: calc(100% - 320px);
            span {
              color: #bbbbbb;
            }
            .list-cont {
              width: 100%;
              height: calc(100% - 20px);
              border-radius: 4px;
              margin-top: 5px;
              background: rgba(68, 68, 68, 0.4);
              padding: 12px 16px;
              box-sizing: border-box;
              overflow-y: auto;

              .list-item {
                width: 100%;
                margin-bottom: 8px;
                display: flex;
                align-items: center;
                .item-box {
                  padding: 8px;
                  border: 1px solid #444444;
                  border-radius: 4px;
                  margin-left: 10px;
                }
              }
            }
          }
        }
        .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>
