<template>
  <div v-if="showxfclgl">
    <div class="titleBox">
      <div class="title">巡防车辆管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="addLoad('add',id)">
          <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>
        <el-button type="info" plain icon="Upload" @click="isImport = true">
          <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.cph" clearable placeholder="请输入车牌号"></el-input>
        </el-form-item>
        <el-form-item label="车辆品牌">
          <el-input v-model="listQuery.clpp" clearable placeholder="请输入车辆品牌"></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="cntBox-bb">
      <div class="tabBox">
        <el-table
          @selection-change="handleSelectionChange"
          :data="tableData"
          border
          row-key="id"
          :height="tableHeight"
          :key="keyCount"
          v-loading="loadingTable"
          element-loading-background="rgba(0,0,0,0.3)"
          element-loading-text="数据加载中。。"
        >
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column align="center" type="index" width="60px" label="序号"/>
          <el-table-column prop="ssbm" align="center" label="所属部门" show-overflow-tooltip />
          <el-table-column prop="cplx" align="center" label="号牌种类" show-overflow-tooltip>
            <template #default="{ row }">
              <dict-tag :options="D_BZ_HPZL" :value="row.cplx" :tag="false" />
            </template>
          </el-table-column>
          <el-table-column prop="cph" label="车牌号" align="center"></el-table-column>
          <el-table-column prop="clpp" label="车辆品牌" align="center">
            <template #default="{ row }">
              <dict-tag :options="D_BZ_CLPP" :value="row.clpp" :tag="false" />
            </template>
          </el-table-column>
          <el-table-column prop="clnk" label="车辆年款" align="center" />
          <el-table-column label="状态" align="center">
            <template #default="{ row }">
              <dict-tag :value="row.zbzt" :options="D_ZDY_SBZT"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="350px">
            <template #default="{ row }">
              <el-button @click="lookGj(row,'clgj')" size="small">轨迹回放</el-button>
              <el-button @click="manage(row.cid)" size="small">设备管理</el-button>
              <el-button @click="addLoad('edit',row.cid)" size="small">修改</el-button>
              <el-button @click="deletList(row.cid)" 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 class="mapbox" v-if="isShowMap" :style="{ height: tableHeight +50+ 'px' }">
        <!-- 轨迹回放 -->
         <MapDialog  v-model:modelValue="isShowMap" lxtype="gjhf" :data="gJDate"/>
      </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="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form ref="elform" :model="form" :rules="rules" :inline="true" label-position="top">
        <el-form-item prop="cph" label="车牌号">
          <el-input
            v-model="form.cph"
            placeholder="请输入车牌号"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="ssbmdm" label="所属部门">
          <MOSTY.Department
            :placeholder="form.ssbm"
            style="width: 100%"
            clearable
            filterable
            v-model="form.ssbmdm"
          />
        </el-form-item>
        <el-form-item prop="cplx" label="号牌种类">
          <el-select
            v-model="form.cplx"
            class="m-2"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="dict in D_BZ_HPZL"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="zbzt" label="车辆状态">
          <el-select
            v-model="form.zbzt"
            class="m-2"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in D_ZDY_SBZT"
              :label="item.label"
              :key="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="clpp" label="车辆品牌">
          <el-select
            v-model="form.clpp"
            class="m-2"
            filterable
            placeholder="请选择车辆品牌"
            style="width: 100%">
            <el-option
              v-for="dict in D_BZ_CLPP"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="clxh" label="车辆型号">
          <el-input placeholder="请输入车辆型号" v-model="form.clxh"></el-input>
        </el-form-item>
        <el-form-item prop="clnk" label="车辆年款">
          <el-date-picker
            type="year"
            v-model="form.clnk"
            format="YYYY"
            value-format="YYYY"
            placeholder="请选择车辆年款"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="gmrq" label="车辆生产日期">
          <el-date-picker
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            v-model="form.gmrq"
            type="date"
            placeholder="请选择日期"
            style="width: 100%"
            :disabledDate="disableCgrq"
          />
        </el-form-item>
        <el-form-item prop="bfrq" label="车辆报废日期">
          <el-date-picker
            @focus="cgrqTs"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            v-model="form.bfrq"
            type="date"
            placeholder="请选择日期"
            style="width: 100%"
            :disabledDate="disableDqsj"
          />
        </el-form-item>
        <el-form-item prop="cllx" label="车辆类型">
          <el-select
            v-model="form.cllx"
            class="m-2"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="dict in D_BZ_CLLX"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="clys" label="车辆颜色">
          <el-select
            v-model="form.clys"
            class="m-2"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="dict in D_BZ_CLYS"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="GPS">
          <el-input v-model="form.gpsId" placeholder="请输入GPS" style="width: 100%"/>
        </el-form-item>
        <!-- 新增的电台和监控 -->
        <el-form-item label="车载电台">
          <el-input v-model="form.czdt" placeholder="请输入车载电台" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="车载监控">
          <el-input v-model="form.czjk" placeholder="请输入车载监控" style="width: 100%"/>
        </el-form-item>
         <el-form-item style="width: 100%" prop="jyqxList" label="警用器械" @click.stop="jyqxVisible = true">
          <el-input
            v-model="form.jyqx"
            placeholder="请选择警用器械"
            style="width: 100%"
            clearable
            readonly
            suffix-icon="ArrowDown"
            v-if="jyqxData.length <= 0"/>
          <template v-else>
            <el-tag v-for="tag in jyqxData" :key="tag.id" closable :type="tag.type" @close.stop="handleClose(tag)">
              {{ tag.qxMc }}
            </el-tag>
          </template>
        </el-form-item>
        <el-form-item label="器械数量" style="width: 100%" v-if="jyqxData.length >0">
          <span v-for="(item,idx) in jyqxData" :key="idx" style="margin:10px; 10px 0 10px 0;">
            {{item.qxMc}} <el-input-number :min="0" :max="1000" v-model="item.sl"></el-input-number>
          </span>
        </el-form-item>
        <el-form-item label="备注" style="width: 100%">
          <el-input v-model="form.textarea" placeholder="请输入关键字" show-word-limit type="textarea"/>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <!-- 设备管理 -->
  <Carmanage v-if="sbgl" :id="sbid" />
  <JyqxLoad
    v-if="jyqxVisible"
    :roleIds="hasChooseJyqx"
    v-model="jyqxVisible"
    @choosedUsers="hanlderChooseJyqx"
  />
  <!-- 导入 -->
  <Export
    :show="isImport"
    lx="car"
    @closeImport="isImport = false"
    @handleImport="handleFilter"
  />
</template>

<script setup>
import MapDialog from './mapDialog.vue'
import Export from "@/components/export/index.vue";
import JyqxLoad from "@/components/MyComponents/ChooseJz/JyqxLoad.vue";
import { getXfcl, addXfcl, upXfcl, delXfcl, infoXfcl, infoXfsb, getXfclsb } from "@/api/basicsmanage/watchmanCar";
import * as rule from "@/utils/rules.js";
import emitter from "@/utils/eventBus.js";
import { selectDeptPage, getUserInfoToId } from "@/api/user-manage";
import Carmanage from "./carmanage/index.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ref, reactive, onMounted, getCurrentInstance,watch, onUnmounted } from "vue";
const { proxy } = getCurrentInstance();
const { D_BZ_HPZL, D_ZDY_SBZT, D_BZ_CLLX, D_BZ_CLYS,D_BZ_CLPP } = proxy.$dict( "D_BZ_CLLX", "D_BZ_HPZL", "D_BZ_CLYS", "D_ZDY_SBZT", "D_BZ_CLPP");
const showxfclgl = ref(true);//弹窗切换
const isImport = ref(false);
const multipleSelection = ref([]); //批量数据
const listQuery = ref({ pageCurrent: 1, pageSize: 20 });
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const tableData = ref([]); //表单数据
const keyCount = ref(0); //tabel组件刷新值
const loadingTable = ref(true);
const dialogFormVisible = ref(false);
const total = ref(0); //总数据
const diaTitle = ref("");
const btnLoading = ref(false);
const jyqxVisible = ref(false)
const jyqxData = ref([]) //警用器械数据
const hasChooseJyqx = ref([])//警用器械数据ids
const sbgl = ref(false); //设备管理弹窗
const sbid = ref(""); //设备id
const elform = ref(null);
const isShowMap = ref(false)
const gJDate = ref({})
//新增表单对象
const formDefault = ref({})
const form = ref({
  ssbmdm: "",
  cplx: "",
  cph: "",
  clpp: "",
  clnk: "",
  bfrq: "",
  bz: ""
});
const rules = reactive({
  ssbmdm: [{ required: true, message: "请选择部门", trigger: "change" }],
  cplx: [{ required: true, message: "请选择号牌种类", trigger: "change" }],
  cph: [{ required: true, message: "请输入车牌号", trigger: "change" }],
  clpp: [{ required: true, message: "请输入车辆品牌", trigger: "change" }],
  clnk: [{ required: true, message: "请选择车辆年款", trigger: "change" }],
  bfrq: [{ required: true, message: "请选择车辆报废日期", trigger: "change" }],
  gmrq: [{ required: true, message: "请选择车辆生产日期", trigger: "change" }]
});
watch(()=>isShowMap.value,(val)=>{
  emitter.emit('closeMeun')
})
onMounted(() => {
  formDefault.value = JSON.parse(JSON.stringify(form.value))
  getListData();
  tabHeightFn();
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  emitter.on("reback", (res) => {
    sbgl.value = false;
    showxfclgl.value = true;
    sbid.value = "";
  });
});

onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});

// 轨迹回放
function lookGj (row,type){
  if(row.gpsId){
    gJDate.value = row
    isShowMap.value = true;
  }else{
    proxy.$message({ type: "warning", message: "该数据无gpsId!" });
    isShowMap.value = false;
  }
}

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

//重置搜索
const reset = () => {
  listQuery.value = { pageCurrent: 1, pageSize: 20 };
  getListData();
};

//获取数据
const getListData = () => {
  loadingTable.value = true;
  getXfcl(listQuery.value).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  }).catch(() => {
    loadingTable.value = false;
  });
};
// 新增-修改
function addLoad(type,id) {
  dialogFormVisible.value = true;
  if(type == 'add'){
    diaTitle.value = "新增巡防车辆";
  }else{
    diaTitle.value ='编辑巡防车辆'
    getDetailInfo(id)
  }
}
//根据id查看详情
function getDetailInfo(id) {
  infoXfcl(id).then((res) => {
    form.value = res;
    jyqxData.value = res.jyqx ? JSON.parse(res.jyqx) : []
    hasChooseJyqx.value = jyqxData.value.map(item=>{ return item.id})
    form.value.ssbmdm = form.value.ssbmdm * 1;
    form.value.jyqx = ''
  });
}

//批量选择数据
const handleSelectionChange = (val) => {
  multipleSelection.value = val,map(item=>{
    return item.cid
  });
};

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

// 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 - 240;
  window.onresize = function () { tabHeightFn(); };
};

//设备管理
function manage(id) {
  sbgl.value = true;
  showxfclgl.value = false;
  sbid.value = id;
}

//选择警用器械
function hanlderChooseJyqx(arr) {
  hasChooseJyqx.value = arr.map((item) => { return item.id; });
  jyqxData.value = arr;
}

// 删除警用器械
function handleClose(tag){
  jyqxData.value.splice(jyqxData.value.indexOf(tag), 1);
  hasChooseJyqx.value = jyqxData.value.map((item) => { return item.id; });
}

// 关闭弹窗
function closeDialog(){
  form.value = JSON.parse(JSON.stringify(formDefault.value))
  dialogFormVisible.value = false;
  jyqxData.value = []
  hasChooseJyqx.value = []
}

//提交
function submit() {
  elform.value.validate((valid) => {
    if (!valid) return false
    btnLoading.value = true;
    form.value.jyqx = JSON.stringify(jyqxData.value)
    if (diaTitle.value  == '编辑巡防车辆') {
      upXfcl(form.value).then(() => {
        proxy.$message({ type: "success", message: "修改成功" });
        btnLoading.value = false;
        closeDialog()
        getListData();
      }).catch(() => {
        btnLoading.value = false;
      });
    } else {
      addXfcl(form.value).then(() => {
        proxy.$message({ type: "success", message: "新增成功" });
        closeDialog()
        btnLoading.value = false;
        getListData();
      }).catch(() => {
        btnLoading.value = false;
      });
    }
  });
}

//购置日期限制
function disableCgrq(row) {
  let time = new Date();
  return time.getTime() <= row.getTime();
}

// 到期日期限制
function disableDqsj(row) {
  if (form.value.gmrq) {
    let time = new Date(form.value.gmrq);
    return time.getTime() >= row.getTime();
  } else {
    return true;
  }
}

function cgrqTs() {
  if (!form.value.gmrq) {
    proxy.$message({ message: "请先选择车辆生产日期", type: "warning" });
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";
.cntBox-bb{
  display: flex;
  height: 100%;
  .tabBox{
    flex: 1;
    height: 100%;
  }
  .mapbox{
    width: 1000px;
    padding: 0 10px;
    box-sizing: border-box;
  }
}
</style>
