<template>
  <div>
    <div class="titleBox">
      <div class="title">必巡点管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="add">
          <el-icon style="vertical-align: middle">
            <CirclePlus />
          </el-icon>
          <span style="vertical-align: middle">新增</span>
        </el-button>

        <el-button
          @click="batchDelete"
          :disabled="ids.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 :model="listQuery" :inline="true">
        <el-form-item label="所属部门">
          <MOSTY.Department width="100%" clearable v-model="listQuery.ssbmid" />
        </el-form-item>
        <el-form-item label="必巡点名称">
          <el-input v-model="listQuery.bxdMc" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="所属巡防区域">
          <el-select style="width: 100%" v-model="listQuery.ssXfqyId">
            <el-option
              v-for="item in xfqyList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="必巡点类型">
          <el-select v-model="listQuery.bxdLx" placeholder="请选择" clearable>
            <el-option
              v-for="dict in D_BZ_BXDLX"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="必巡点来源">
          <el-select v-model="listQuery.bxdlydm" placeholder="请选择" clearable>
            <el-option
              v-for="dict in D_BZ_BXDLYDM"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据状态">
          <el-select v-model="listQuery.xtSjzt" placeholder="请选择" clearable>
            <el-option label="注销" value="0"></el-option>
            <el-option label="正常" value="1"></el-option>
          </el-select>
        </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="id"
        :tree-props="{ children: 'itemList', hasChildren: true }"
        style="width: 100%"
        :key="keyCount"
        @selection-change="handleSelectionChange"
        :height="tableHeight"
        v-loading="loadingTable"
        element-loading-background="rgba(0,0,0,0.3)"
        element-loading-text="数据加载中。。"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column
          type="index"
          show-overflow-tooltip
          align="center"
          width="60px"
          label="序号"
        >
        </el-table-column>

        <el-table-column
          prop="bxdMc"
          show-overflow-tooltip
          align="center"
          width="250px"
          label="必巡点名称"
        >
        </el-table-column>
        <el-table-column
          prop="bxdlydm"
          show-overflow-tooltip
          align="center"
          label="必巡点来源"
        >
          <template #default="{ row }">
            <dict-tag
              :options="D_BZ_BXDLYDM"
              :value="row.bxdlydm"
              :tag="false"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="bxdLx"
          show-overflow-tooltip
          align="center"
          label="必巡点类型"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_BXDLX" :value="row.bxdLx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          prop="ssXfqyId"
          show-overflow-tooltip
          align="center"
          label="所属巡防区域"
        >
          <template #default="{ row }">
            <dict-tag :options="xfqyList" :value="row.ssXfqyId" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          prop="xtSjzt"
          show-overflow-tooltip
          align="center"
          label="数据状态"
        >
          <template #default="{ row }">
            <span
              v-if="row.xtSjzt == 0"
              style="background: red; padding: 2px 4px; border-radius: 2px"
              >注销</span
            >
            <span
              v-if="row.xtSjzt == 1"
              style="background: green; padding: 2px 4px; border-radius: 2px"
              >正常</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="ssbm"
          show-overflow-tooltip
          align="center"
          label="所属部门"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="250px"
        >
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">修改</el-button>
            <el-button @click="delDictItem(row)" 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.pageCurrent"
          :page-sizes="[10, 20, 50, 100]"
          :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">{{ title }}</span>
        <div>
          <el-button
            type="primary"
            size="small"
            @click="submit"
            :loading="btnLoading"
            >保存</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"
      >
        <el-form-item style="width: 48%" prop="ssbmdm" label="所属部门">
          <MOSTY.Department
            width="100%"
            clearable
            :placeholder="form.ssbm"
            v-model="form.ssbmdm"
          />
        </el-form-item>
        <el-form-item style="width: 48%" prop="bxdMc" label="必巡点名称">
          <el-input
            v-model="form.bxdMc"
            placeholder="请填写必巡点名称"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item style="width: 48%" prop="bxdLx" label="必巡点类型">
          <el-select
            v-model="form.bxdLx"
            filterable
            style="width: 100%"
            placeholder="请选择必巡点类型"
          >
            <el-option
              v-for="dict in D_BZ_BXDLX"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 48%" prop="bxdLx" label="必巡点来源">
          <el-select
            v-model="form.bxdlydm"
            filterable
            style="width: 100%"
            placeholder="请选择必巡点来源"
          >
            <el-option
              v-for="dict in D_BZ_BXDLYDM"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          style="width: 48%"
          prop="ssXfqyId"
          label="必巡点所属巡防区域"
        >
          <el-select
            style="width: 100%"
            v-model="form.ssXfqyId"
            placeholder="请选择必巡点所属巡防区域"
          >
            <el-option
              v-for="item in xfqyList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="jd" label="选择必巡点" style="width: 100%">
          <div class="latlng">
            <el-input
              v-model="form.jd"
              @change="jdChange"
              clearable
              style="width: 45%"
              placeholder="经度"
            />
            <el-input
              v-model="form.wd"
              @change="wdChange"
              clearable
              style="width: 45%"
              placeholder="纬度"
            />
            <el-button @click="chackLat">选取坐标</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 {
  getBxd,
  addBxd,
  putBxd,
  infoBxd,
  delBxd
} from "@/api/basicsmanage/mandatoryPatrol.js";
import emitter from "@/utils/eventBus.js";
import { getJzList } from "@/api/basicsmanage/servicejz.js";
import GdMap from "@/components/Map/GdMap/index.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getXfqy } from "@/api/basicsmanage/patrolArea.js";
import { selectDeptPage } from "@/api/user-manage";
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const { D_BZ_BXDLX, D_BZ_PBLX, D_BZ_BXDLYDM } = proxy.$dict(
  "D_BZ_BXDLX",
  "D_BZ_PBLX",
  "D_BZ_BXDLYDM"
);
const cascader = ref(null);
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const tableData = ref([]); //表格数据
const loadingTable = ref(true);
const btnLoading = ref(false); //按钮截流
const mapRef = ref(null);
const depList = ref([]); //部门数据
const xfqyList = ref([]);
const checkAdd = ref(false);
const keyCount = ref(0); //tabel组件刷新值
const title = ref("新增必巡点");
const elform = ref(null);
const total = ref(0);
const ids = ref([]); //批量删除的ID
const dialogFormVisible = ref(false); //弹窗
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
//搜索数据
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
//表单数据
const form = ref({});
//表单验证
const rules = reactive({
  bxdMc: [
    {
      required: true,
      message: "请输必巡点名称",
      trigger: "change"
    }
  ],
  bxdLx: [
    {
      required: true,
      message: "请选择必巡点类型",
      trigger: "change"
    }
  ],
  ssbmdm: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "change"
    }
  ],
  jd: [
    {
      required: true,
      message: "请选择或填写必巡点",
      trigger: "change"
    }
  ]
});

//执勤时长验证
function checkZqsc(rule, value, callback) {
  if (value <= 0 || value >= 1000) {
    return callback(new Error("请选择正确的时间范围"));
  } else {
    callback();
  }
}
//获取经纬度
function chackLat() {
  form.value.jd = "";
  form.value.wd = "";
  emitter.emit("drawShape", { type: "point", flag: "bxd_ht", isclear: true });
}

function getLngLat(coordinates) {
  form.value.jd = coordinates[0];
  form.value.wd = coordinates[1];
}
// 经纬度变化回显
function jdChange() {
  if (form.value.jd && form.value.wd) {
    emitter.emit("deletePointArea", "kfd");
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [form.value],
        icon: require("@/assets/point/kfd.png"),
        flag: "kfd"
      });
    }, 1000);
    emitter.emit("setMapCenter", {
      location: [form.value.jd, form.value.wd],
      zoomLevel: 14
    });
  }
}
function wdChange() {
  if (form.value.jd && form.value.wd) {
    emitter.emit("deletePointArea", "kfd");
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [form.value],
        icon: require("@/assets/point/kfd.png"),
        flag: "kfd"
      });
    }, 1000);
    emitter.emit("setMapCenter", {
      location: [form.value.jd, form.value.wd],
      zoomLevel: 14
    });
  }
}
//搜索
function handleFilter() {
  getListData();
}
//计算执勤时长
function setZqsc() {
  if (form.value.jssj && form.value.kssj) {
    let a = new Date(form.value.jssj).getTime();
    let b = new Date(form.value.kssj).getTime();
    form.value.zqsc = Math.floor((a - b) / 60000);
  }
}
//新增选择部门
function addHandleChange(e) {
  const info = cascader.value.getCheckedNodes()[0];
  form.value.ssbm = info.label;
  form.value.ssbmdm = info.value;
}
//批量数据
const handleSelectionChange = (val) => {
  ids.value = [];
  if (val) {
    val.forEach((item) => {
      ids.value.push(item.id);
    });
  }
};
//批量删除数据
const batchDelete = () => {
  proxy
    .$confirm("确定要删除", "警告", {
      type: "warning"
    })
    .then(() => {
      delBxd(ids.value).then((res) => {
        proxy.$message({
          message: "删除成功",
          type: "success"
        });
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
};
//重置
function reset() {
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 20
  };
  getListData();
}
//新增表单重置
function resetForm() {
  form.value = {};
}
//新增
function add() {
  resetForm();
  checkAdd.value = true;
  title.value = "新增必巡点";
  dialogFormVisible.value = true;
}
//修改
function update(row) {
  infoBxd(row.id).then((res) => {
    checkAdd.value = false;
    form.value = res;
    title.value = "修改必巡点";
    dialogFormVisible.value = true;
    if (row.jd && row.wd) {
      setTimeout(() => {
        emitter.emit("addPointArea", {
          coords: [res],
          icon: require("@/assets/point/xfq.png"),
          flag: "kfd"
        });
        emitter.emit("setMapCenter", {
          location: [res.jd, res.wd],
          zoomLevel: 13
        });
      }, 1000);
    }
  });
}
//删除
function delDictItem(row) {
  proxy
    .$confirm("确定要删除", "警告", {
      type: "warning"
    })
    .then(() => {
      delBxd([row.id]).then(() => {
        proxy.$message({
          type: "success",
          message: "删除成功"
        });
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
}
//获取列表数据
function getListData() {
  loadingTable.value = true;
  getBxd(listQuery.value)
    .then((res) => {
      tableData.value = res.records;
      total.value = res.total;
      loadingTable.value = false;
    })
    .catch(() => {
      loadingTable.value = false;
    });
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
}
//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      form.value.ssbmid = form.value.ssbmdm;
      btnLoading.value = true;
      setTimeout(() => {
        btnLoading.value = false;
      }, 1500);
      if (!checkAdd.value) {
        putBxd(form.value).then(() => {
          proxy.$message({
            type: "success",
            message: "修改成功"
          });
          dialogFormVisible.value = false;
          getListData();
        });
      } else {
        let params = form.value;
        params.yxq = "2099-12-31";
        addBxd(params).then(() => {
          proxy.$message({
            type: "success",
            message: "新增成功"
          });
          dialogFormVisible.value = false;
          getListData();
        });
      }
    }
  });
}
/**
 * pageSize 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
};
onMounted(() => {
  selectDeptPage({}).then((res) => {
    depList.value = res.records;
  });
  getXfqy({ pageCurrent: 1, pageSize: 1000 }).then((res) => {
    xfqyList.value = res.records.map((item) => {
      return { value: item.id, label: item.xfqMc };
    });
  });
  getListData();
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  emitter.on("coordString", (res) => {
    if (res.type === "point") {
      form.value.jd = res.coord[0];
      form.value.wd = res.coord[1];
    }
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
  emitter.off("coordString");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";
.min {
  position: relative;
}
.min::after {
  position: absolute;
  top: 0;
  right: 12px;
  bottom: 0;
  content: "分钟";
}
.map {
  width: 100%;
  height: 400px;
  position: relative;
}
.latlng {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
