<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.ssbmdm"
          />
        </el-form-item>
        <el-form-item label="必巡线名称">
          <el-input v-model="listQuery.bxxMc" 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.bxxLx" 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>
          <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%"
        :key="keyCount"
        :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="ssbm"
          show-overflow-tooltip
          align="center"
          label="所属部门"
        >
        </el-table-column>
        <el-table-column
          prop="bxxMc"
          show-overflow-tooltip
          align="center"
          width="250px"
          label="必巡线名称"
        >
        </el-table-column>
        <el-table-column
          prop="jzId"
          show-overflow-tooltip
          align="center"
          label="责任警组"
        >
          <template #default="{ row }">
            <dict-tag :options="jzList" :value="row.jzId" :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="bxxLx"
          show-overflow-tooltip
          align="center"
          label="必巡线类型"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_BXDLX" :value="row.bxxLx" :tag="false" />
          </template>
        </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="bxxMc" label="必巡线名称">
          <el-input
            v-model="form.bxxMc"
            placeholder="请填写必巡线名称"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item style="width: 48%" prop="bxxLx" label="必巡线类型">
          <el-select
            v-model="form.bxxLx"
            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="jzId" label="必巡线责任警组">
          <el-select
            style="width: 100%"
            v-model="form.jzId"
            placeholder="请选择必巡线责任警组"
          >
            <el-option
              v-for="item in jzList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></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="zb" label="选择必巡线" style="width: 100%">
          <div class="latlng">
            <el-input
              v-model="form.zb"
              @change="bxxChange"
              clearable
              style="flex: 1"
            />
            <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 {
  getBxx,
  addBxx,
  putBxx,
  infoBxx,
  delBxx
} from "@/api/basicsmanage/patrolLine.js";
import { getXfqy } from "@/api/basicsmanage/patrolArea.js";
import { getJzList } from "@/api/basicsmanage/servicejz.js";
import * as MOSTY from "@/components/MyComponents/index";
import GdMap from "@/components/Map/GdMap/index.vue";
import { spliceArray, spliceString } from "@/utils/auth.js";
import { selectDeptPage } from "@/api/user-manage";
import emitter from "@/utils/eventBus.js";
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  inject
} from "vue";
const { proxy } = getCurrentInstance();
const { D_BZ_BXDLX, D_BZ_PBLX } = proxy.$dict("D_BZ_BXDLX", "D_BZ_PBLX");
const searchBox = ref(null); // 搜索盒子
const xfqyList = ref([]);
const tableHeight = ref(); // 表格高度
const depList = ref([]); //部门数据
const tableData = ref([{ bcname: "123", kssj: "2022-05-22 18:00:00" }]); //表格数据
const btnLoading = ref(false); //按钮截流
const keyCount = ref(0); //tabel组件刷新值
const drawData = reactive({
  zb: null
});
const title = ref("新增必巡线");
const loadingTable = ref(true);
const jzList = ref([]); // 警组下拉数据
const elform = ref(null);
const total = ref(0);
const mapRef = ref(null);
const ids = ref([]); //批量删除的ID
const checkAdd = ref(false);
const cascader = ref(null);
const dialogFormVisible = ref(false); //弹窗
const reload = inject("reload");
//搜索数据
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  bcName: ""
});
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
//表单数据
const form = ref({});
//表单验证
const rules = reactive({
  bxxMc: [
    {
      required: true,
      message: "请输必巡线名称",
      trigger: "change"
    }
  ],
  jzId: [
    {
      required: true,
      message: "请选择必巡线责任警组",
      trigger: "blur"
    }
  ],
  ssXfqyId: [
    {
      required: true,
      message: "请选择必巡线所属巡防区域",
      trigger: "blur"
    }
  ],
  bxxLx: [
    {
      required: true,
      message: "请选择必巡线类型",
      trigger: "blur"
    }
  ],
  ssbmdm: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "blur"
    }
  ],
  zb: [
    {
      required: true,
      message: "请选择或填写必巡线",
      trigger: "blur"
    }
  ]
});

// 必巡线回显
function bxxChange() {
  if (form.value.zb) {
    let arr = form.value.zb.split(",");
    form.value.zb = spliceArray(arr);
    setTimeout(() => {
      let arrStr = form.value.zb.join(',')
      emitter.emit("drawLine", arrStr);
    }, 1000);
  }
}

//批量数据
const handleSelectionChange = (val) => {
  ids.value = [];
  if (val) {
    val.forEach((item) => {
      ids.value.push(item.id);
    });
  }
};
//执勤时长验证
function checkZqsc(rule, value, callback) {
  if (value <= 0 || value >= 1000) {
    return callback(new Error("请选择正确的时间范围"));
  } else {
    callback();
  }
}
function getLngLat(coordinates) {
  form.value.zb = coordinates.overlay.getPath().map((item) => {
    return [item.lng, item.lat];
  });
}

//搜 索
function handleFilter() {
  getListData();
}
function chackLat() {
  emitter.emit("drawShape", {type: "line",flag: "xl-route",isclear:true });
  form.value.zb = "";
}
//计算执勤时长
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 batchDelete = () => {
  proxy
    .$confirm("确定要删除", "警告", {
      type: "warning"
    })
    .then(() => {
      delBxx(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() {
  drawData.zb = null;
  resetForm();
  checkAdd.value = true;
  title.value = "新增必巡线";
  dialogFormVisible.value = true;
}
//修改
function update(row) {
  drawData.zb = [];
  infoBxx(row.id).then((res) => {
    form.value = res;
    checkAdd.value = false;
    title.value = "修改必巡线";
    dialogFormVisible.value = true;
    if (res.zb.length > 0) {
      setTimeout(() => {
        let obj = { coords:[res.zb], text:res.bxxMc }
        console.log(obj);
        emitter.emit("echoLine", { coords: [obj], flag: "xl-route", type:'solid', isclear: true });
        let len = parseInt(res.zb.length/2)
        emitter.emit("setMapCenter", {  location: res.zb[len], zoomLevel: 10 });
      }, 1000);
    }
  });
}
//删除
function delDictItem(row) {
  proxy
    .$confirm("确定要删除", "警告", {
      type: "warning"
    })
    .then(() => {
      delBxx([row.id]).then(() => {
        proxy.$message({
          type: "success",
          message: "删除成功"
        });
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
}
//获取列表数据
function getListData() {
  loadingTable.value = true;
  getBxx(listQuery.value).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  }).catch(()=>{
    loadingTable.value = false;
  });
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  //   formReset();
}
//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      form.value.ssbmdm = form.value.ssbmdm;
      btnLoading.value = true;
      setTimeout(() => {
        btnLoading.value = false;
      }, 1500);
      if (!checkAdd.value) {
        putBxx(form.value).then(() => {
          proxy.$message({
            type: "success",
            message: "修改成功"
          });
          dialogFormVisible.value = false;
          getListData();
        });
      } else {
        addBxx(form.value).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;
 window.onresize = function () {
    tabHeightFn();
  };
};
onMounted(() => {
  selectDeptPage({}).then((res) => {
    depList.value = res.records;
  });
  getJzList({ pageCurrent: 1, pageSize: 1000 }).then((res) => {
    jzList.value = res.records.map((item) => {
      return { value: item.id, label: item.jzMc };
    });
  });
  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();
  
  emitter.on("coordString", (res) => {
    if(res.type == 'line') form.value.zb = res.coord
  });
 
});
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>
