<template>
  <div>
    <div class="titleBox">
      <div class="title">巡防区管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="addEdit('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="巡防区名称">
          <el-input v-model="listQuery.xfqMc" placeholder="请输入巡防区名称" clearable />
        </el-form-item>
        <el-form-item label="所属部门">
          <MOSTY.Department width="100%" clearable v-model="listQuery.ssbmdm" />
        </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" @selection-change="handleSelectionChange"
        :tree-props="{ children: 'itemList', hasChildren: true }" style="width: 100%" :height="tableHeight"
        :key="keyCount" 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" align="center" width="60px" label="序号">
        </el-table-column>
        <el-table-column prop="xfqMc" show-overflow-tooltip align="center" label="巡防区名称">
        </el-table-column>
        <el-table-column prop="ssbm" show-overflow-tooltip label="所属部门" align="center"></el-table-column>
        <el-table-column prop="xfqDj" label="巡防区等级" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <dict-tag :options="D_BZ_XFQDJ" :value="row.xfqDj" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column prop="xfqLx" label="巡防区类型" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <dict-tag :options="D_BZ_XQLX" :value="row.xfqLx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="140px">
          <template #default="{ row }">
            <el-button @click="addEdit('edit', row.id)" size="small">编辑</el-button>
            <el-button @click="delDictItem(row.id)" 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 :loading="loading" type="primary" 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">
        <el-form-item style="width: 48%" prop="ssbmdm" label="所属部门">
          <MOSTY.Department width="100%" clearable :placeholder="form.ssbm" filterable v-model="form.ssbmdm"
            @getDepValue="getDepValue" />
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqMc" label="巡防区名称">
          <el-input v-model="form.xfqMc" placeholder="请输入巡防区名称" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqLx" label="巡防区类型">
          <el-select v-model="form.xfqLx" placeholder="请选择巡防区类型">
            <el-option v-for="dict in D_BZ_XQLX" :key="dict.value" :value="dict.value" :label="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqSx" label="巡防区属性">
          <el-select v-model="form.xfqSx" placeholder="请选择巡防区属性">
            <el-option v-for="dict in D_BZ_XFQSX" :key="dict.value" :value="dict.value" :label="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqDJ" label="巡防区等级">
          <el-select v-model="form.xfqDj" placeholder="请选择巡防区等级">
            <el-option v-for="dict in D_BZ_XFQDJ" :key="dict.value" :value="dict.value" :label="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqFzr" label="巡防区负责人">
          <el-input @click="choosePoliceVisible = true" v-model="form.xfqFzr" placeholder="请选择巡防区负责人"
            style="width: 100%" :suffix-icon="ArrowDown" clearable />
        </el-form-item>
        <el-form-item style="width: 48%" prop="xfqFzrSfz" label="负责人身份证号">
          <el-input v-model="form.xfqFzrSfz" placeholder="请输入负责人身份证号" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item style="width: 100%" prop="pgis" label="坐标位置">
          <div class="latlng">
            <el-input v-model="form.pgis" @change="xfqChange" clearable style="width: 90%" />
            <el-button @click="chackLat">绘制区域</el-button>
            <el-color-picker v-model="form.color"></el-color-picker>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <div class="map">
            <GdMap v-if="dialogFormVisible" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <ChoosePolice v-model="choosePoliceVisible" PoliceType="MJ" :Single="true" @choosedPolice="choosedPolice" />
  </div>
</template>

<script setup>
import { ArrowDown } from "@element-plus/icons-vue";
import { ref, reactive, onMounted, getCurrentInstance, onUnmounted, nextTick } from "vue";
import { selectDeptPage } from "@/api/user-manage";
import { getXfqy, addXfqy, putXfqy, infoXfqy, delXfqy } from "@/api/basicsmanage/patrolArea.js";
import emitter from "@/utils/eventBus.js";
import GdMap from "@/components/Map/GdMap/index.vue";
import { spliceArray, spliceString } from '@/utils/auth.js'
import * as MOSTY from "@/components/MyComponents/index";
import ChoosePolice from "@/components/MyComponents/choosePolice";
const { proxy } = getCurrentInstance();
const { D_BZ_XFQDJ, D_BZ_XQLX,D_BZ_XFQSX } = proxy.$dict("D_BZ_XFQDJ", "D_BZ_XQLX","D_BZ_XFQSX");
const ids = ref([]); //批量删除的ID
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  ssbmdm: '',
  xfqMc: ''
});
const tableData = ref([]); //表单数据
const searchBox = ref(null); // 搜索盒子
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = ref(); // 表格高度
const loadingTable = ref(true);
const choosePoliceVisible = ref(false); //民警辅警弹窗
const loading = ref(false);
const title = ref("新增巡防区");
const drawData = reactive({
  pgis: null
});
const total = ref(0); //总数据
const dialogFormVisible = ref(false);
const formDefault = ref({})
//表单数据
const form = ref({
  xfqMc: "",
  gljg: "",
  jd: "",
  wd: "",
  hzfw: "",
  color: '#409eff'
});
//表单验证
const rules = reactive({
  xfqMc: [{ required: true, message: "请输入巡防区名称", trigger: "change" }],
  ssbmdm: [{ required: true, message: "请选择部门", trigger: "change" }]
});
const elform = ref(null);
const listQueryDefault = ref({})

onMounted(() => {
  listQueryDefault.value = JSON.parse(JSON.stringify(listQuery.value))
  formDefault.value = JSON.parse(JSON.stringify(form.value))
  getListData();
  tabHeightFn();
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  emitter.on("coordString", (res) => {
    if (res.type === "polygon") form.value.pgis = res.coord[0];
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
  emitter.off("coordString")
});

// 查询
const handleFilter = () => {
  listQuery.value.pageCurrent = 1;
  getListData();
};

//获取数据
const getListData = () => {
  loadingTable.value = true;
  getXfqy(listQuery.value).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  }).catch(() => {
    loadingTable.value = false;
  });
};

// 新增巡防区域 - 编辑
function addEdit(type, id) {
  dialogFormVisible.value = true;
  if (id) {
    title.value = "修改巡防区";
    drawData.pgis = [];
    infoXfqy(id).then((res) => {
      form.value = res;
      if (res.pgis.length > 0) {
        setTimeout(() => {
          let obj = { position: [res.pgis], text: res.xfqMc, id: res.id }
          emitter.emit("echoPlane", { coords: [obj], color: res.color, linecolor: res.color, flag: "qclk", type: 'polygon' });
          emitter.emit("setMapCenter", { location: res.pgis[0], zoomLevel: 12 });
        }, 500)
      }
    });
  } else {
    title.value = "新增巡防区";
    drawData.pgis = null;
  }
}
//批量数据
const handleSelectionChange = (val) => {
  ids.value = val.map(v => { return v.id });
};

// 获取部门类型
function getDepValue(val) {
  form.value.xfbmlx = val ? val.orgBizType : ''
}

// 单个删除
function delDictItem(id) {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    delXfqy([id]).then((res) => {
      proxy.$message({ message: "删除成功", type: "success" });
      getListData();
    });
  }).catch(() => {
    proxy.$message.info("已取消");
  });
}

//批量删除数据
const batchDelete = () => {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    delXfqy(ids.value).then((res) => {
      proxy.$message({ message: "删除成功", type: "success" });
      getListData();
    });
  }).catch(() => {
    proxy.$message.info("已取消");
  });
};

//提交
function submit() {
  elform.value.validate((valid) => {
    if (!valid) return false
    loading.value = true;
    if (title.value == "新增巡防区") {
      addXfqy(form.value).then(() => {
        proxy.$message({ type: "success", message: "新增成功" });
        close()
        loading.value = false;
        getListData();
      }).catch(() => {
        loading.value = false;
      })
    } else {
      putXfqy(form.value).then(() => {
        proxy.$message({ type: "success", message: "修改成功" });
        close()
        loading.value = false;
        getListData();
      }).catch(() => {
        loading.value = false;
      })
    }
  });
}

//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  form.value = JSON.parse(JSON.stringify(formDefault.value))
}

// 重置
const reset = () => {
  listQuery.value = JSON.parse(JSON.stringify(listQueryDefault.value))
  getListData();
};
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
  window.onresize = function () { tabHeightFn(); };
};

/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};

//负责人
function choosedPolice(police) {
  form.value.xfqFzrId = police[0].ryid;
  form.value.xfqFzrSfz = police[0].sfzh;
  form.value.xfqFzr = police[0].xm;
}



//获取经纬度
function chackLat() {
  emitter.emit("deletePointArea", 'qclk');
  emitter.emit("drawShape", { type: "polygon", flag: "qc", isclear: true });
  form.value.pgis = "";
}
// 输入框地图回显
function xfqChange() {
  if (form.value.pgis) {
    emitter.emit("deletePointArea", "xfq");
    let arr = form.value.pgis.split(",");
    form.value.pgis = spliceArray(arr);
    let xfq = spliceString(form.value.pgis);
    setTimeout(() => {
      emitter.emit("polygonFigure", {
        coords: [xfq],
        flag: "xfq",
        isclear: true
      });
    }, 1000);
    emitter.emit("setMapCenter", {
      location: form.value.pgis[0],
      zoomLevel: 14
    });
  }
}

</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>
