<template>
  <div>
    <div class="titleBox">
      <div class="title">公安机关要素</div>
      <div class="btnBox">
        <el-button type="primary" @click="addItemMenu">
          <el-icon><CirclePlus /></el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="要素名称">
          <el-input
            placeholder="请输入要素名称"
            v-model="listQuery.gajgmc"
            clearable
          ></el-input>
        </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
        v-if="refreshTable"
        :data="tableData"
        border
        row-key="id"
        style="width: 100%"
        :height="tableHeight"
        :key="keyCount"
      >
        <el-table-column
          prop="gajgmc"
          show-overflow-tooltip
          align="center"
          width="200px"
          label="要素名称"
        >
        </el-table-column>
        <el-table-column
          prop="gajgjc"
          align="center"
          show-overflow-tooltip
          width="200px"
          label="要素简称"
        />
        <el-table-column
          prop="wzBc"
          label="位置别称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="wzXz"
          show-overflow-tooltip
          label="位置"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="ysdl"
          label="要素大类"
          align="center"
          width="140px"
        >
          <template #default="{ row }">
            <dict-tag
              :options="D_ZDY_YSDL"
              :value="row.ysdl"
              :tag="false"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="yszl"
          label="要素中类"
          align="center"
          width="140px"
        >
          <template #default="{ row }">
            <dict-tag
              :options="D_ZDY_YSZL"
              :value="row.yszl"
              :tag="false"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="ysxl"
          label="要素小类"
          align="center"
          width="140px"
        >
          <template #default="{ row }">
            <dict-tag
              :options="D_ZDY_YSXL"
              :value="row.ysxl"
              :tag="false"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">编辑</el-button>
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要删除?"
              @confirm="delDictItem(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </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.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.size"
          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">{{ isEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button
            v-if="isEdit"
            type="primary"
            size="small"
            @click="onSave"
            :loading="buttonLoading"
            >保存</el-button
          >
          <!-- 新增 -->
          <el-button
            v-else
            type="primary"
            size="small"
            @click="onAdd"
            :loading="buttonLoading"
            >保存</el-button
          >
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form
        class="mosty-from-wrap"
        :inline="true"
        label-position="top"
        ref="editRef"
        :rules="rules"
        :model="dialogForm"
      >
        <el-form-item label="要素名称" prop="gajgmc" label-width="140px">
          <el-input
            v-model="dialogForm.gajgmc"
            placeholder="请输入要素名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="要素简称" prop="gajgjc" label-width="140px">
          <el-input
            v-model="dialogForm.gajgjc"
            placeholder="请输入要素简称"
          ></el-input>
        </el-form-item>
        <el-form-item label="关联部门" label-width="140px">
          <MOSTY.Department
            placeholder="部门"
            width="280px"
            clearable
            multiple
            filterable
            v-model="dialogForm.glbmDtoList"
          />
        </el-form-item>
        <el-form-item label="要素小类" prop="ysxl" label-width="140px">
          <el-select v-model="dialogForm.ysxl" placeholder="请选择要素小类">
            <el-option
              v-for="dict in D_ZDY_YSXL"
              :key="dict.value + 'ysxl'"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置别称" prop="wzBc" label-width="140px">
          <el-input
            v-model="dialogForm.wzBc"
            placeholder="请输入位置别称"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置" prop="wzXz" label-width="140px">
          <el-input
            v-model="dialogForm.wzXz"
            placeholder="请输入地址详址"
          ></el-input>
        </el-form-item>
        <el-form-item style="width: 48%" prop="jd" label="坐标位置">
          <div class="latlng">
            <el-input v-model="dialogForm.jd" clearable style="width: 45%" />
            <el-input v-model="dialogForm.wd" clearable style="width: 45%" />
            <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 GdMap from "@/components/Map/GdMap/index.vue";
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import ChooseIcon from "@/components/MyComponents/ChooseIcon";
import emitter from "@/utils/eventBus.js";
import { ElMessage } from "element-plus";
import { getAddressApi } from "@/utils/tools.js";
import {
  ref,
  reactive,
  watch,
  nextTick,
  onMounted,
  getCurrentInstance,
  onUnmounted
} from "vue";
import {
  getYsList,
  getYsAdd,
  getYsUpdate,
  getYsDelete,
  getYsInfo
} from "@/api/ysCenter";
import { useRouter, useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const { D_ZDY_YSDL, D_ZDY_YSZL, D_ZDY_YSXL } = proxy.$dict(
  "D_ZDY_YSDL",
  "D_ZDY_YSZL",
  "D_ZDY_YSXL"
);
const keyCount = ref(0); //tabel组件刷新值
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const rules = ref({
  gajgmc: [{ required: true, message: "请输入要素名称 " }],
  gajgjc: [{ required: true, message: "请输入要素简称 " }],
  glbmDtoList: [{ required: true, message: " 请选择关联部门" }],
  ysxl: [{ required: true, message: "请填写要素小类 " }],
  jd: [{ required: true, message: "请选择位置 " }]
});
const router = useRouter();
const route = useRoute();
//查询参数
const total = ref(0);
const currentRow = ref({});
const listQuery = ref({
  gajgmc: "",
  yszl: "",
  jsnr: "",
  ysxl:'',
  pageNum: 1,
  pageSize: 10
});
const buttonLoading = ref(false);
const topParentId = ref("");
const id = ref("");
const zdlx = ref();
const refreshTable = ref(true);
const isEdit = ref(true);
const dialogForm = ref({
  ysdl: "001",
  yszl: "001001"
});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  const res = await getYsList(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};
const editRef = ref(null);
const handleFilter = () => {
  listQuery.value.pageNum = 1;
  getListData();
};
getListData();
//获取经纬度
function chackLat(type) {
  emitter.emit("drawShape", {
    type: "drawPoint",
    flag: "point"
  });
  dialogForm.value.jd = "";
  dialogForm.value.wd = "";
}

const reset = () => {
  listQuery.value = {
    gajgmc: "",
    yszl: "",
    jsnr: "",
    pageNum: 1,
    pageSize: 10
  };
  getListData();
};
// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.current = currentPage;
  getListData();
};
/**修改字典 */
const update = (row) => {
  getYsInfo(row.id).then((res) => {
    isEdit.value = true;
    dialogForm.value = { ...res };
    dialogForm.value.glbmDtoList = res.glbmDtoList.map(
      (item) => item.ssbmid * 1
    );
    dialogFormVisible.value = true;
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [res],
        icon: require("@/assets/point/kfd.png"),
        flag: "kfd"
      });
    }, 1000);
  });
};
function isNull(data) {
  if (!data) return true;
  if (JSON.stringify(data) === "{}") return true;
  if (JSON.stringify(data) === "[]") return true;
  return false;
}
const addItemMenu = (row) => {
  id.value = isNull(row) ? topParentId.value : row.id;
  isEdit.value = false;
  dialogForm.value = {
    ysdl: "001",
    yszl: "001001"
  };
  dialogFormVisible.value = true;
};
const onSave = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      const data = { ...dialogForm.value };
      data.glbmDtoList = data.glbmDtoList.map((item) => {
        return { ssbmid: item };
      });
      getYsUpdate({
        ...data
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("修改成功");
          buttonLoading.value = false;
          handleFilter();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

const onAdd = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      const data = { ...dialogForm.value };
      data.glbmDtoList = data.glbmDtoList.map((item) => {
        return {
          ssbmid: item
        };
      });
      getYsAdd({
        ...data
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("新增成功");
          handleFilter();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

const delDictItem = (row) => {
  getYsDelete(row.id).then((res) => {
    ElMessage.success("删除成功");
    handleFilter();
  });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};

const toGoPage = (row) => {
  router.push("/user/role?zdbh=" + row.zdbh);
};
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
};
onMounted(() => {
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  emitter.on("coordString", (res) => {
    if (res.type === "drawPoint") {
      let arr = res.coord.split(",");
      dialogForm.value.jd = arr[0];
      dialogForm.value.wd = arr[1];
      // getAddressApi({ jd: arr[0], wd: arr[1] }, (res) => {
      //   dialogForm.value.wzXz = res.address;
      // });
    }
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
  emitter.off("coordString");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";
.user-manage-container {
  .table-header-wrap {
    margin-bottom: 22px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
  }
}
.map {
  width: 100%;
  height: 400px;
  position: relative;
}
.latlng {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
