<template>
  <div>
    <div class="titleBox">
      <div class="title">快反点管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="addKfdList()">
          <el-icon style="vertical-align: middle">
            <CirclePlus />
          </el-icon>
          <span style="vertical-align: middle">新增</span>
        </el-button>
        <el-button @click="deletList" :disabled="multipleSelection.length == 0" typeof="danger">
          <el-icon style="vertical-align: middle">
            <Delete />
          </el-icon>
          <span style="vertical-align: middle">批量删除</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form class="mosty-from-wrap" :model="listQuery" :inline="true">
        <el-form-item label="所属部门">
          <MOSTY.Department width="100%" clearable v-model="listQuery.ssbmdm" />
        </el-form-item>
        <el-form-item label="快反点名称">
          <el-input v-model="listQuery.kfdMc" placeholder="请输入快反点名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleFilter"> 查询 </el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabBox">
      <el-table :data="tableData" border row-key="kfdId" :tree-props="{ children: 'itemList', hasChildren: true }"
        style="width: 100%" @selection-change="handleSelectionChange" :height="tableHeight" :key="keyCount"
        v-loading="loadingTable" element-loading-background="rgba(0,0,0,0.3)" element-loading-text="数据加载中。。">
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column type="index" show-overflow-tooltip align="center" width="60px" label="序号">
        </el-table-column>
        <el-table-column sortable prop="ssbm" label="所属部门" width="200px" align="center"></el-table-column>
        <el-table-column sortable prop="kfdMc" show-overflow-tooltip align="center" width="300px" label="快反点名称">
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="点位类型">
          <template #default="{ row }">
            <dict-tag :options="D_BZ_KFDLX" :value="row.dwlx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column prop="kfdDz" show-overflow-tooltip align="center" label="快反点地址">
        </el-table-column>
        <el-table-column sortable prop="jd" show-overflow-tooltip label="经度" align="center">
        </el-table-column>
        <el-table-column sortable prop="wd" show-overflow-tooltip label="纬度" align="center">
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right" width="180px">
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">编辑</el-button>
            <el-button @click="delDictItem(row.kfdId)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ diaTitle }}</span>
        <div>
          <el-button v-if="disable" type="primary" :loading="btnLoading" size="small" @click="submit">保存</el-button>
          <el-button size="small" @click="close">关闭</el-button>
        </div>
      </div>
      <el-form ref="elform" :model="form" :rules="rules" :inline="true" label-position="top" class="mosty-from-wrap">
        <el-form-item style="width: 31%" prop="ssbmdm" label="所属部门">
          <MOSTY.Department :placeholder="form.ssbm" style="width: 100%" ref="cascader" clearable filterable
            :options="depList" :props="props" v-model="form.ssbmdm" />
        </el-form-item>
        <el-form-item style="width: 31%" prop="kfdMc" label="快反点名称">
          <el-input v-model="form.kfdMc" placeholder="请输入快反点名称" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item style="width: 32%" prop="dwlx" :rules="[
          { required: true, message: '请选择点位类型', trigger: 'change' }
        ]" label="点位类型">
          <el-select @change="lxChange" v-model="form.dwlx" placeholder="请选择点位类型">
            <el-option v-for="item in D_BZ_KFDLX" :label="item.label" :key="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 100%" prop="kfdDz" label="快反点地址">
          <el-input v-model="form.kfdDz" placeholder="请输入快反点地址" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item style="width: 100%" prop="jd" label="坐标位置">
          <div class="latlng">
            <el-input @change="jwdChange" v-model="form.jd" clearable style="width: 45%" />
            <el-input @change="jwdChange" v-model="form.wd" clearable style="width: 45%" />
            <el-button @click="chackLat">选取坐标</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%" prop="yfzfw" @change="yfzChange" :rules="[
          { required: lxFlag, message: '请选择一分钟范围', trigger: 'change' }
        ]" label="一分钟范围">
          <div class="latlng">
            <el-input v-model="form.yfzfw" clearable style="width: 90%" />
            <el-button @click="chackLatY('yfzfw')">开始绘制</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%" prop="sfzfw" @change="sfzChange" :rules="[
          { required: lxFlag, message: '请选择三分钟范围', trigger: 'change' }
        ]" label="三分钟范围">
          <div class="latlng">
            <el-input v-model="form.sfzfw" clearable style="width: 90%" />
            <el-button @click="chackLatY('sfzfw')">开始绘制</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%" prop="wfzfw" @change="wfzChange" :rules="[
          { required: lxFlag, message: '请选择五分钟范围', trigger: 'change' }
        ]" label="五分钟范围">
          <div class="latlng">
            <el-input v-model="form.wfzfw" clearable style="width: 90%" />
            <el-button @click="chackLatY('wfzfw')">开始绘制</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <div class="map">
            <GdMap v-if="dialogFormVisible" />
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { selectDeptPage, getUserInfoToId } from "@/api/user-manage";
import * as MOSTY from "@/components/MyComponents/index";
import GdMap from "@/components/Map/GdMap/index.vue";
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  onUnmounted,
  inject,
  nextTick
} from "vue";
import {
  getKfd,
  addKfd,
  deleteKfd,
  updateKfd
} from "@/api/basicsmanage/quick-rebate.js";
import { spliceArray, spliceString } from "@/utils/auth.js";
import emitter from "@/utils/eventBus.js";
const chackipt = ref(true);
const cascader = ref(null);
const depList = ref([]); //部门数据
const { proxy } = getCurrentInstance();
const keyCount = ref(0); //tabel组件刷新值
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(null); // 表格高度
const mapRef = ref(null);
const diaTitle = ref("新增智能装备");
const loadingTable = ref(true);
const checkList = ref([]);
const reload = inject("reload");
const { D_BZ_KFDLX } = proxy.$dict("D_BZ_KFDLX");
const listQuery = ref({
  pageNum: 1,
  pageSize: 20,
  kfdMc: "",
  ssbmdm: ""
});
onMounted(() => {
  selectDeptPage({}).then((res) => {
    depList.value = res.records;
  });
  getListData();
  tabHeightFn();
  emitter.on("coordString", (res) => {
    if (res.type === "point") {
      form.value.jd = res.coord[0];
      form.value.wd = res.coord[1];
    }
    if (res.type === "polygon") form.value[res.flag] = res.coord[0];
  });
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
  emitter.off("coordString");
});
const disable = ref(false);
const btnLoading = ref(false); //按钮加载
const chackadd = ref(true); //切换新增修改
const tableData = ref([]); //表单数据
const total = ref(0); //总数据
const dialogFormVisible = ref(false);
const multipleSelection = ref([]); //批量数据
const handleFilter = () => {
  listQuery.value.pageNum = 1;
  getListData();
};
//获取数据
const getListData = () => {
  loadingTable.value = true;
  const params = listQuery.value;
  params.dwlxs = "01,02";
  getKfd(params).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  });
};
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
const reset = () => {
  listQuery.value = {
    pageNum: 1,
    pageSize: 20,
    kfdMc: "",
    ssbmdm: ""
  };
  getListData();
};
const addDict = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
  reload();
};
// 选择类型变化
const lxFlag = ref(true);
function lxChange(val) {
  lxFlag.value = val === "02" ? false : true
}
//获取经纬度 - 圈层范围清空
function chackLat(type) {
  form.value.jd = "";
  form.value.wd = "";
  form.value.yfzfw = "";
  form.value.sfzfw = "";
  form.value.wfzfw = "";
  emitter.emit("deletePointArea", "kfd");
  emitter.emit("removePlot", "yfzfw");
  emitter.emit("removePlot", "sfzfw");
  emitter.emit("removePlot", "wfzfw");
  emitter.emit("drawShape", { type: "point", flag: "kfd_ht", isclear: true });
}
// 绘制一、三、五分钟圈陈
function chackLatY(type) {
  emitter.emit("drawShape", { type: "polygon", flag: type, isclear: true });
  form.value[type] = "";
}
// 经纬度变化回显
function jwdChange() {
  if (form.value.jd && form.value.wd) {
    emitter.emit("deletePointArea", "kfd");
    emitter.emit("addPointArea", {
      coords: [{ jd: parseInt(form.value.jd), wd: form.value.wd }],
      icon: require("@/assets/point/kfd.png"),
      flag: "kfd"
    });
    emitter.emit("setMapCenter", {
      location: [form.value.jd, form.value.wd],
      zoomLevel: 10
    });
  }
}

function yfzChange() {
  if (form.value.yfzfw) {
    emitter.emit("deletePointArea", "yfzArea");
    let arr = form.value.yfzfw.split(",");
    form.value.yfzfw = spliceArray(arr);
    setTimeout(() => {
      emitter.emit("polygonFigure", {
        coords: [spliceString(form.value.yfzfw)],
        flag: "yfzArea",
        isclear: true
      });
    }, 1000);
  }
}
function sfzChange() {
  if (form.value.sfzfw) {
    emitter.emit("deletePointArea", "sfzArea");
    let arr = form.value.sfzfw.split(",");
    form.value.sfzfw = spliceArray(arr);
    setTimeout(() => {
      emitter.emit("polygonFigure", {
        coords: [spliceString(form.value.sfzfw)],
        flag: "sfzArea",
        isclear: true
      });
    }, 1000);
  }
}
function wfzChange() {
  if (form.value.wfzfw) {
    emitter.emit("deletePointArea", "wfzArea");
    let arr = form.value.wfzfw.split(",");
    form.value.wfzfw = spliceArray(arr);
    setTimeout(() => {
      emitter.emit("polygonFigure", {
        coords: [spliceString(form.value.wfzfw)],
        flag: "wfzArea",
        isclear: true
      });
    }, 1000);
  }
}

//批量数据
const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  if (val) {
    val.forEach((item) => {
      multipleSelection.value.push(item.kfdId);
    });
  }
};
//新增
function addKfdList() {
  chackipt.value = false;
  disable.value = true;
  diaTitle.value = "新增快反点";
  chackadd.value = false;
  dialogFormVisible.value = true;
}
//删除
const delDictItem = (id) => {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    const ids = [id];
    deleteKfd(ids).then(() => {
      proxy.$message({ type: "success", message: "删除成功" });
      getListData();
    });
  })
    .catch(() => {
      proxy.$message.info("已取消");
    });
};
//批量删除
const deletList = () => {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    const ids = multipleSelection.value;
    deleteKfd(ids).then(() => {
      proxy.$message({ type: "success", message: "删除成功" });
      getListData();
    });
  })
    .catch(() => {
      proxy.$message.info("已取消");
    });
};

//修改
const update = (row) => {
  chackipt.value = true;
  disable.value = true;
  diaTitle.value = "修改";
  form.value = row;
  form.value.ssbmdm = form.value.ssbmdm * 1;
  if (form.value.dwlx) lxFlag.value = false;
  chackadd.value = true;
  dialogFormVisible.value = true;
  nextTick(() => {
    if (row.jd && row.wd) {
      let icon = require("@/assets/point/kfd.png")
      emitter.emit("addPointArea", { coords: [row], icon, flag: "kfd" });
      emitter.emit("setMapCenter", { location: [row.jd, row.wd], zoomLevel: 10 });
    }
    if (row.yfzfw.length > 0) {
      emitter.emit("drawShape", { coords: [row.yfzfw], flag: "yfzfw", type: 'geoJson', isclear: true });
    }
    if (row.sfzfw.length > 0) {
      emitter.emit("drawShape", { coords: [row.sfzfw], flag: "sfzfw", type: 'geoJson', isclear: false });
    }
    if (row.wfzfw.length > 0) {
      emitter.emit("drawShape", { coords: [row.wfzfw], flag: "wfzfw", type: 'geoJson', isclear: false });
    }
  })
};

//表单数据
const form = ref({ kfdMc: "", ssbmdm: "", hzfw: "" });
//表单验证
const rules = reactive({
  kfdMc: [{ required: true, message: "请选择点位类型", trigger: "change" }],
  ssbmdm: [{ required: true, message: "请选择部门", trigger: "change" }],
  kfdDz: [{ required: true, message: "请输入快反点地址", trigger: "change" }],
  jd: [{ required: true, message: "请选择快反点位置", trigger: "change" }]
});
const elform = ref(null);


//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  checkList.value = [];
  form.value = {};
  getListData();
}
// 新增-编辑数据
function submit() {
  elform.value.validate((valid) => {
    if (!valid) return false;
    btnLoading.value = true;
    if (chackadd.value) {
      updateKfd(form.value).then(() => {
        proxy.$message({ type: "success", message: "修改成功" });
        btnLoading.value = false;
        close()
      });
    } else {
      addKfd(form.value).then(() => {
        proxy.$message({ type: "success", message: "新增成功" });
        btnLoading.value = false;
        close()
      });
    }
  });
}
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageNum = currentPage;
  getListData();
};
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
  window.onresize = function () { tabHeightFn(); };
};
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.map {
  width: 100%;
  height: 400px;
}

.latlng {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
