<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="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 :model="listQuery" :inline="true" class="mosty-from-wrap">
        <el-form-item label="所属部门">
          <MOSTY.Department width="100%" clearable v-model="listQuery.ssbmdm" />
        </el-form-item>
        <el-form-item label="警务站类型">
          <el-select filterable v-model="listQuery.jwzLx" placeholder="请选择" style="width: 100%">
            <el-option v-for="(item, index) in D_BZ_JWZLX" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="listQuery.fzrXm" 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 ref="dataTreeList" row-key="id"
        :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" width="40" />
        <el-table-column type="index" align="center" width="60" label="序号" />
        <el-table-column prop="ssbm" show-overflow-tooltip label="所属部门" align="center" />
        <el-table-column prop="jwzLx" align="center" width="300" label="警务站类型" show-overflow-tooltip>
          <template #default="{ row }">
            <dict-tag :options="D_BZ_JWZLX" :value="row.jwzLx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column prop="jwzMc" label="警务站名称" width="200" align="center" />
        <el-table-column prop="fzrXm" label="负责人" align="center" />
        <el-table-column prop="xjSj" label="建立时间" align="center" />
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">编辑</el-button>
            <el-button @click="delDictItem(row.jwzId)" 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.pageNo" :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="loading">保存</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 class="two" prop="ssbmdm" label="所属部门">
          <MOSTY.Department style="width: 100%" ref="cascader" clearable filterable
            :options="depList" :props="props" v-model="form.ssbmdm"  :placeholder="form.ssbm"/>
        </el-form-item>
        <el-form-item class="two" prop="jwzLx" label="警务站类型">
          <el-select v-model="form.jwzLx" placeholder="请选择警务站类型" style="width: 100%">
            <el-option v-for="(item, index) in D_BZ_JWZLX" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="two" prop="xjSj" label="建立时间">
          <el-date-picker v-model="form.xjSj" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            placeholder="请选择日期" style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="jwzMc" label="警务站名称">
          <el-input v-model="form.jwzMc" placeholder="请输入警务站名称" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="jwzjgdm" label="警务站机构代码">
          <el-input v-model="form.jwzjgdm" placeholder="请输入警务站机构代码" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="jwzDz" label="警务站详细地址">
          <el-input v-model="form.jwzDz" placeholder="请输入警务站详细地址" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="fzrXm" label="负责人">
          <el-input @click="mjVisible = true" v-model="form.fzrXm" placeholder="请选择负责人姓名" clearable
            style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="fzrSfzh" label="负责人身份证号码">
          <el-input v-model="form.fzrSfzh" placeholder="请输入负责人身份证号码" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item class="two" prop="snwsp" label="室内外视频">
          <el-input v-model="form.snwsp" placeholder="请输入" clearable style="width: 100%" />
        </el-form-item>
        <!-- <el-form-item style="width: 100%" prop="upload" label="图片上传">
          <MOSTY.Upload width="100%" :limit="2" v-model="form.upload"></MOSTY.Upload>
        </el-form-item> -->
        <el-form-item style="width: 100%" prop="jwzTp	" label="警务站图片">
          <MOSTY.Upload width="100%" :limit="5" v-model="form.jwzTp"></MOSTY.Upload>
        </el-form-item>
        <el-form-item class="one" prop="jd" label="坐标位置">
          <div class="latlng">
            <el-input @change="jdChange" v-model="form.jd" clearable style="width: 45%" />
            <el-input @change="wdChange" v-model="form.wd" clearable style="width: 45%" />
            <el-button @click="chackLat">选取坐标</el-button>
          </div>
        </el-form-item>
        <el-form-item class="one">
          <div class="map">
            <GdMap v-if="dialogFormVisible" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <MjLoad :Single="true" v-model="mjVisible" titleValue="选择负责人" @choosedUsers="hanlderChooseMj" />
  </div>
</template>

<script setup>
import GdMap from "@/components/GdMap/index.vue";
import MjLoad from "@/components/MyComponents/ChooseJz/MjLoad.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { selectDeptPage } from "@/api/user-manage";
import emitter from "@/utils/eventBus.js";
import { ref, reactive, onMounted, getCurrentInstance, onUnmounted } from "vue";
import { getPoliceStationList, deletePoliceStation, addPoliceStation, updatePoliceStation } from "@/api/basicsmanage/policeStation.js";
//获取字典数据
const { proxy } = getCurrentInstance();
const { D_BZ_JWZLX } = proxy.$dict("D_BZ_JWZLX");
const mjVisible = ref(false); //民警弹窗
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const map = ref(null);
const loadingTable = ref(true);
const chackadd = ref(true); //切换新增修改
const mapRef = ref(null); // 地图
const multipleSelection = ref([]); //批量数据
const chackipt = ref(true);
const depList = ref([]); //部门数据
const loading = ref(false); //按钮是否为加载状态
const modalKey = ref(0);
const title = ref("新增警务站");
const ssbmIds = ref([]); //级联选择器回显ID
const keyCount = ref(0); //tabel组件刷新值
const tableData = ref([]); //表单数据
const total = ref(0); //总数据
const dialogFormVisible = ref(false);
const cascader = ref(null); //部门选择器
//部门组件配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
const listQuery = ref({
  pageNo: 1,
  pageSize: 20,
  jwzLx: "",
  jwzMc: "",
  ssbmdm: "",
  fzrXm: ""
});
//表单数据
const form = ref({
  xjSj: "",
  jwzMc: "",
  jwzLx: "",
  jwzDz: "",
  jwzjgdm: "",
  fzrXm: "",
  fzrSfzh: "",
  hzfw: "",
  ssbmdm: ssbmIds.value[ssbmIds.value - 1],
  ssbm: ""
});
const elform = ref(null);
//表单验证
const rules = reactive({
  jd: [{ required: true, message: "请选择经纬度" }],
  fzrSfzh: [{ required: true, message: "请输入负责人身份证号码" }],
  fzrXm: [{ required: true, message: "请输入负责人姓名" }],
  jwzLx: [{ required: true, message: "请选择警务站类型" }],
  ssbmdm: [{ required: true, message: "请选择所属部门" }],
  xjSj: [{ required: true, message: "请选择建立时间" }],
  jwzMc: [{ required: true, message: "请输入警务站名称" }]
});

onMounted(() => {
  getListData();
  tabHeightFn();
  //获取部门信息
  selectDeptPage({}).then((res) => {
    depList.value = res.records;
  });
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  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");
});

//获取经纬度
function chackLat() {
  emitter.emit("drawShape", { type: "point", flag: "jcz_ht", isclear: true });
  form.value.jd = "";
  form.value.wd = "";
}
// 经纬度变化回显
function jdChange() {
  if (form.value.jd && form.value.wd) {
    emitter.emit("deletePointArea", "jwz");
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [form.value],
        icon: require("@/assets/point/jwz.png"),
        flag: "jwz"
      });
    }, 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", "jwz");
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [form.value],
        icon: require("@/assets/point/jwz.png"),
        flag: "jwz"
      });
    }, 1000);
    emitter.emit("setMapCenter", {
      location: [form.value.jd, form.value.wd],
      zoomLevel: 14
    });
  }
}
function add() {
  chackipt.value = false;
  title.value = "新增警务站";
  dialogFormVisible.value = true;
  form.value = {};
  // form.value.upload = [];
  // form.value.uploadNew = [];
  console.log(form.value, 'form.value');
  chackadd.value = false;
}
//点击查询
const handleFilter = () => {
  listQuery.value.pageNo = 1;
  getListData();
};
//选择民警
function hanlderChooseMj(arr) {
  const data = arr[0];
  form.value.fzrXm = data.xm;
  form.value.fzrSfzh = data.sfzh;
}
//获取数据
const getListData = () => {
  loadingTable.value = true;
  getPoliceStationList(listQuery.value).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  }).catch(() => {
    loadingTable.value = false;
  });
};
//点击重置
const reset = () => {
  listQuery.value = { pageNo: 1, pageSize: 20 };
  getListData();
};
//批量数据
const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  if (val) {
    val.forEach((item) => {
      multipleSelection.value.push(item.jwzId);
    });
  }
};
//批量删除
const deletList = () => {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    const ids = multipleSelection.value;
    deletePoliceStation(ids).then(() => {
      proxy.$message({ type: "success", message: "删除成功" });
      getListData();
    });
  }).catch(() => { proxy.$message.info("已取消"); });
};
//重置表单
function formReset() {
  form.value = {};
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  formReset();
}
//详情
const update = (row, view = "put") => {
  chackipt.value = true;
  chackadd.value = true;
  title.value = view == "view" ? "警务站详情" : '修改警务站';
  modalKey.value += 1;
  ssbmIds.value = [];
  proxy.$set(row.ssbmdm, depList.value, "childDeptList", (res) => { ssbmIds.value.push(res); });
  console.log(row);

  form.value = {...row};
  form.value.ssbmdm = form.value.ssbmdm * 1;
  dialogFormVisible.value = true;
  if (row.jd && row.wd) {
    setTimeout(() => {
      emitter.emit("addPointArea", { coords: [row], icon: require("@/assets/point/jwz.png"), flag: "jwz" });
      emitter.emit("setMapCenter", { location: [row.jd, row.wd], zoomLevel: 14 });
    }, 1000);
  }
};


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

//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      let params = form.value;
      if (chackadd.value) {
        updatePoliceStation(params).then(() => {
          loading.value = false;
          proxy.$message({ type: "success", message: "修改成功" });
          close();
          getListData();
        }).catch(res => { loading.value = false; });
      } else {
        addPoliceStation(params).then(() => {
          loading.value = false;
          proxy.$message({ type: "success", message: "新增成功" });
          getListData();
          close();
        }).catch(() => { loading.value = false; });
      }
    }
  });
}

// 分页
function handleCurrentChange(val) {
  listQuery.value.pageNo = 1
  getListData();

}

// 分页数
function handleSizeChange(val) {
  listQuery.value.pageSize = 20
  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>
