<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.jczmc" placeholder="请输入检查站名称" clearable />
        </el-form-item>
        <el-form-item label="执勤类型">
          <el-select clearable style="width: 100%" v-model="listQuery.zqlx" placeholder="请选择执勤类型">
            <el-option v-for="dict in D_BZ_ZQLX" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="点位类型">
          <el-select clearable style="width: 100%" v-model="listQuery.jczlx" placeholder="请选择点位类型">
            <el-option v-for="dict in D_BZ_JCZLX" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属圈层">
          <el-select v-model="qcidList" collapse-tags multiple class="m-2" placeholder="请选择所属圈层">
            <el-option v-for="item in ssqcList" :key="item.value" :label="item.label" :value="item.value" />
          </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 @selection-change="handleSelectionChange" :data="tableData" border row-key="kfdId" 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" align="center" width="55" />
        <el-table-column type="index" align="center" width="60px" label="序号" />
        <el-table-column prop="ssbm" label="所属部门" show-overflow-tooltip align="center" />
        <el-table-column prop="jczmc" show-overflow-tooltip align="center" label="检查站名称" />
        <el-table-column show-overflow-tooltip align="center" label="执勤类型">
          <template #default="{ row }">
            <DictTag :options="D_BZ_ZQLX" :value="row.zqlx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="点位类型">
          <template #default="{ row }">
            <DictTag :options="D_BZ_JCZLX" :value="row.jczlx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="所属圈层">
          <template #default="{ row }">
            <el-tag v-for="item in row.qcList" :key="item.id">{{ item.qcmc }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="xxdz" show-overflow-tooltip align="center" label="检查站地址" />
        <el-table-column label="感知源操作" align="center" width="250">
          <template #default="{ row }">
            <el-button size="small" @click="onClickDygzy(row, 'gzyz')" type="primary">配置感知源</el-button>
            <el-button type="success" size="small" @click="onClickDygzy(row, 'sp')">配置现场天网</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="250">
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">编辑</el-button>
            <el-button @click="delDictItem(row.id)" type="danger" size="small">删除</el-button>
            <!-- <el-button @click="commonQC(row)" size="small">同步圈层</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination" :current-page="listQuery.pageCurrent" :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 type="primary" :loading="btnLoading" size="small" @click="submit">保存</el-button>
          <el-button size="small" @click="dialogFormVisible = false">关闭</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="jczmc" label="检查站名称">
          <el-input v-model="form.jczmc" placeholder="请输入检查站名称" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item label="执勤类型" style="width: 31%" prop="zqlx">
          <el-select v-model="form.zqlx" placeholder="请选择执勤类型">
            <el-option v-for="item in D_BZ_ZQLX" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 32%" prop="jczlx" label="点位类型">
          <el-select v-model="form.jczlx" placeholder="请选择点位类型">
            <el-option v-for="item in D_BZ_JCZLX" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 31%" label="站点负责人">
          <el-input v-model="form.fzr" placeholder="请输入站点负责人" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item style="width: 31%" label="联系电话">
          <el-input v-model="form.lxdh" placeholder="请输入联系电话" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item label="道路类型" style="width: 31%" prop="dllx">
          <el-select v-model="form.dllx" placeholder="请选择道路类型">
            <el-option v-for="item in D_BZ_DLLX" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item style="width: 31%" prop="xxdz" label="检查站地址">
          <el-input v-model="form.xxdz" placeholder="请输入检查站地址" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item @click="showRichOnly = true" style="width: 31%" prop="ssqc" label="所属圈层" required>

          <el-input v-model="form.ssqc" placeholder="所属圈层" style="width: 100%" clearable suffix-icon="ArrowDown" v-if="qcList.length === 0" />
          <template v-else>
            <el-tag v-for="(item, index) in qcList" :key="item.id" closable @close="onCloseQc(index)">{{ item.qcmc }}</el-tag>
          </template>
        </el-form-item>
         <MOSTY.RichOnly width="100%" :data="qcList" v-model="showRichOnly" @close="showRichOnly = false" @choosedQc="choosedQcData" />
        <el-form-item label="示意图(最多3张)" prop="fjid" style="width: 48%">
          <MOSTY.Upload :isImg="true" width="100%" :limit="3" v-model="form.fjid"></MOSTY.Upload>
        </el-form-item>

        <el-form-item label="全景图(正面、侧面、俯视共3张)" prop="qjfjid" style="width: 48%">
          <MOSTY.Upload width="100%" :isImg="true" :limit="3" v-model="form.qjfjid"></MOSTY.Upload>
        </el-form-item>
        <el-form-item style="width: 100%" prop="jd" label="坐标位置">
          <div class="latlng">
            <el-input v-model="form.jd" clearable style="width: 45%" />
            <el-input v-model="form.wd" clearable style="width: 45%" />
            <el-button @click="seachLat">确定</el-button>
            <el-button @click="zdyLat">自定义坐标</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <div class="map">
            <GdMap :isShowDraw="true" />
          </div>
        </el-form-item>
      </el-form>

    </div>
    <!-- 订阅天网视频 -->
    <div v-if="dialogSpVisible" class="dialog">
      <div class="head_box">
        <span class="title">选择现场视频</span>
        <div>
          <el-button @click="(dialogSpVisible = false), (formGzy.radius = 2000)">关闭</el-button>
        </div>
      </div>
      <Pzgzy :dyLx="'02'" :jczid="formGzy.jczid" :dict="{ D_BZ_GZSBLX, D_BZ_SBLX, D_BZ_SF }" v-if="formGzy.jczid"/>
    </div>
    <!-- 添加感知源组 -->
    <div v-if="dialogGzyzVisible" class="dialog">
      <div class="head_box">
        <span class="title">感知源组管理</span>
        <div>
          <el-button @click="dialogGzyzVisible = false">关闭</el-button>
        </div>
      </div>
      <AddGzyZ :jczid="formGzy.jczid" :dict="{ D_BZ_GZSBLX, D_BZ_SBLX, D_BZ_SF }" :data="gzyList"/>
    </div>
  </div>
</template>

<script setup>
import { selectDeptPage } from "@/api/user-manage";
import * as MOSTY from "@/components/MyComponents/index";
import GdMap from "@/components/GdMap/index.vue";
import AddGzyZ from "./component/addGzyZ.vue";
import Pzgzy from "./component/pzgzy.vue";
import {
  selectQcList,
  sysQcck,
} from "@/api/file.js";
import {JczSelectJczList,qcSelectQcList,JczupdateJcz,JczSaveJcz,JczDeletesJcz,} from '@/api/lzjcz/index.js'
import { getItem } from "@/utils/storage.js";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  onUnmounted,
  inject,
  watch,
  nextTick
} from "vue";
const { proxy } = getCurrentInstance();
const userId = getItem("USERID");
import emitter from "@/utils/eventBus.js";
const {
  D_BZ_KFDLX,
  D_BZ_DLLX,
  D_BZ_JCZJB,
  D_BZ_JCZLX,
  D_BZ_QCLX,
  D_BZ_ZQLX,
  D_BZ_GZSBLX,
  D_BZ_SBLX,
  D_BZ_SF
} = proxy.$dict(
  "D_BZ_KFDLX",
  "D_BZ_DLLX",
  "D_BZ_JCZJB",
  "D_BZ_JCZLX",
  "D_BZ_QCLX",
  "D_BZ_ZQLX",
  "D_BZ_GZSBLX",
  "D_BZ_SBLX",
  "D_BZ_SF"
);
const showRichOnly = ref(false);
const chackipt = ref(true);
const cascader = ref(null);
const depList = ref([]); //部门数据
const keyCount = ref(0); //tabel组件刷新值
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(null); // 表格高度
const diaTitle = ref("新增检查站");
const loadingTable = ref(false);
const checkList = ref([]);
const reload = inject("reload");
const isShow = ref(false); //是否是修改
const qcidList = ref([]);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  jczmc: "",
  ssbmdm: ""
});
//表单数据
const form = ref({
  jczmc: "",
  ssbmdm: "",
  jd: "",
  wd: "",
  qjfjid: []
});
const gzyTotal = ref(0); //感知源总数
const gzyFunction = ref("01"); //感知源功能选项
const dialogSpVisible = ref(false); //显示视频弹窗
const dialogGzyzVisible = ref(false); //显示感知源组弹窗
const btnLoading = ref(false); //按钮加载
const tableData = ref([]); //表单数据
const total = ref(0); //总数据
const dialogFormVisible = ref(false);
const multipleSelection = ref([]); //批量数据
const mapType = ref(""); //地图绘制对象
const gzyMapList = ref([]); //感知源数据
const selectJcz = ref(); //已选择感知源
const router = useRouter();
const store = useStore();
const handleFilter = () => {
  listQuery.value.pageCurrent = 1;
  getListData();
};
//表单验证
const rules = reactive({
  jczmc: [{ required: true, message: "请输入检查站名称", trigger: "change" }],
  ssbmdm: [{ required: true, message: "请选择部门", trigger: "change" }],
  jczlx: [{ required: true, message: "请选择点位类型", trigger: "change" }],
  zqlx: [{ required: true, message: "请选择执勤类型", trigger: "change" }],
  fzr: [{ required: true, message: "请输入站点负责人", trigger: "change" }],
  lxdh: [{ required: true, message: "请输入联系电话", trigger: "change" }],
  dllx: [{ required: true, message: "请选择道路类型", trigger: "change" }],
  xxdz: [{ required: true, message: "请输入检查站地址", trigger: "change" }],
  jd: [{ required: true, message: "请选择快返点位置", trigger: "change" }],
  ssqc: [{ required: true, message: "请选择所属圈层", trigger: "change blur" }]
});
const elform = ref(null);
const qcList = ref([]); //选中的圈层数据
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
const formGzy = ref({
  pageNum: 1,
  pageSize: 20,
  isChild: 1
});

onMounted(() => {
  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];
    }
  });
  getListData();
  getQCListData();
  emitter.on("drawLngLat", (res) => {
    //如果点位存在 删除点位
    if (store.getters.points.length > 0) {
      for (let i = 0; i < store.getters.points.length; i++) {
        const item = store.getters.points[i];
        egis.removePlotFeature(item);
      }
      store.commit("map/setPoints", []);
    }
    if (res.properties.t == "Point") {
      store.commit("map/setPoints", [res.properties.id]);
      form.value.jd = res.properties.conteolPoint[0];
      form.value.wd = res.properties.conteolPoint[1];
    } else {
      proxy.$message.warning("请选择绘制点位");
      egis.removePlotFeature(res.properties.id);
      return;
    }
  });
});
const ssqcList = ref([]);
//圈层数据
const getQCListData =() => {
  let params = { pageCurrent: 1, pageSize: 100 };
  qcSelectQcList(params).then((res) => {
    let arr = res.records || [];
    ssqcList.value = arr.map((item, index) => {
      return { label: item.qcmc, value: item.id };
    });
  });
};
// 同步圈层
// const commonQC = (val) => {
//   proxy
//     .$confirm("确定要同步该数据到检查站", "警告", { type: "warning" })
//     .then(() => {
//       console.log(val);
//       sysQcck(val.id).then((res) => {
//         proxy.$message.success(res);
//         getListData();
//       });
//     })
//     .catch((err) => {console.log(err);});
// };
onUnmounted(() => {
  emitter.off("coordString");
  emitter.off("showJczDygzy");
  emitter.off("drawLngLat");
});
//选中的圈层数据
const choosedQcData = (val) => {
  qcList.value = val;
  form.value.ssqc = "111";
};
const onCloseQc = (index) => {
  qcList.value.splice(index, 1);
  if (qcList.value.length == 0) {
    form.value.ssqc = "";
  }
};

//显示订阅感知源
function onClickDygzy(row, type) {
  switch (type) {
    case "gzyz":
      dialogGzyzVisible.value = true;
      break;
    case "sp":
      dialogSpVisible.value = true;
      break;
  }
  formGzy.value = {
    ...formGzy.value,
    jczid: row.id
  };
}
//获取数据
const getListData = () => {
  loadingTable.value = true;
  listQuery.value.qcidList = qcidList.value.join(",");
  JczSelectJczList(listQuery.value)
    .then((res) => {
      loadingTable.value = false;
      if (res && res.records) {
        tableData.value = res.records;
        total.value = res.total;
      }
    })
    .catch((err) => {
      loadingTable.value = false;
    });
};

const reset = () => {
  listQuery.value = { pageCurrent: 1, pageSize: 20 };
  form.value = { fjid: "", qjfjid: "" };
  qcidList.value = [];
  getListData();
};

//批量数据
const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  if (val) {
    val.forEach((item) => {
      multipleSelection.value.push(item.id);
    });
  }
};
//新增
function addKfdList() {
  qcList.value = [];
  diaTitle.value = "新增检查站";
  nextTick(() => {
    dialogFormVisible.value = true;
  });
  form.value = {
    fjid: "",
    qjfjid: ""
  };
  isShow.value = false;
}
//删除
const delDictItem = (id) => {
  proxy
    .$confirm("确定要删除", "警告", { type: "warning" })
    .then(() => {
      JczDeletesJcz({ids:[id]}).then(() => {
        proxy.$message.success("删除成功");
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
};
//批量删除
const deletList = () => {
  proxy
    .$confirm("确定要删除", "警告", {
      type: "warning"
    })
    .then(() => {
      const ids = multipleSelection.value;
      JczDeletesJcz({ids:ids}).then(() => {
        proxy.$message.success("删除成功");
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
};

//修改
const update = (row) => {
  nextTick(() => {
    dialogFormVisible.value = true;

    let obj = JSON.parse(JSON.stringify(row));
    if (obj.qjfjid) obj.qjfjid = obj.qjfjid.split(",");
    if (obj.fjid) obj.fjid = obj.fjid.split(",");

    form.value = obj;

    isShow.value = true;
    diaTitle.value = "修改检查站";
    setTimeout(() => {
      emitter.emit("addPointArea", {
        coords: [row],
        icon: require("@/assets/point/jwz.png"),
        flag: "zqd",
        isBounds: true
      });
      emitter.emit("setMapCenter", {
        location: [row.jd, row.wd],
        zoomLevel: 10
      });
    }, 1e3);
    qcList.value = [];
    if (row.qcList) {
      qcList.value = row.qcList;
      form.value.ssqc = "111";
    }
  });
};

function changeStatus(row) {
  let params = { id: row.id, sfqd: row.sfqd };
  qcckPost(params, "/mosty-jcgl/jcz/updateJcz").then((res) => {
    let text = row.sfqd == 0 ? "关闭成功" : "启动成功";
    proxy.$message.success(text);
    getListData();
  });
}

function zdyLat() {
  form.value.jd = "";
  form.value.wd = "";
  emitter.emit("drawShape", { type: "point", flag: "zqd", isclear: true });
}

// 搜索经纬度
function seachLat() {
  emitter.emit("deletePointArea", "zqd");
  if (form.value.jd && form.value.wd) {
    let item = { jd: form.value.jd, wd: form.value.wd };
    emitter.emit("addPointArea", {
      coords: [item],
      icon: require("@/assets/point/jwz.png"),
      flag: "zqd"
    });
    emitter.emit("setMapCenter", {
      location: [form.value.jd, form.value.wd],
      zoomLevel: 10
    });
  } else {
    proxy.$message.info("经度,纬度不能未空");
  }
}

//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      form.value.qcidList = qcList.value.map((item) => item.id);
      console.log(form.value, "form.value.");
      let prams = { ...form.value };
      if (prams.fjid && Array.isArray(prams.fjid))
        prams.fjid = prams.fjid.join(",");
      if (prams.qjfjid && Array.isArray(prams.qjfjid))
        prams.qjfjid = prams.qjfjid.join(",");
      if (!isShow.value) {
        JczSaveJcz(prams).then((res) => {
          proxy.$message.success("新增成功");
          dialogFormVisible.value = false;
          reset();
        });
      } else {
        JczupdateJcz(prams).then((res) => {
          proxy.$message.success("编辑成功");
          dialogFormVisible.value = false;
          reset();
        });
      }
    }
  });
}
/**
 * size 改变触发
 */
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 - 238;
};
</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;
}
.dygzy {
  padding: 20px;
  .function_box {
    display: flex;
    align-items: center;
  }
}
</style>
