<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" style="" class="main-tree">
        <el-input v-model="deptName" placeholder="输入分组名称" prefix-icon="Search" clearable />
        <el-tree ref="deptTreeRef" class="mt-2" node-key="id" :data="deptOptions"
          :props="{ label: 'groupName', children: 'children' }" :expand-on-click-node="false"
          :filter-node-method="filterNode" highlight-current default-expand-all @node-click="handleNodeClick"></el-tree>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
          :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card>
              <!-- =========搜索按钮操作======= -->
              <div class="btn_search">
                <el-button type="primary" plain icon="Download" @click="handleExport">导出</el-button>
                <div style="position: absolute; right:30px; top:20px">
                  <el-input v-model="queryParams.content" placeholder="MAC/IMEI" clearable
                    style="width: 200px; margin-right: 20px;" @keyup.enter="handleQuery" @input="handleInput" />
                  <el-button type="primary" plain @click="toggleFilter">高级筛选</el-button>
                </div>
              </div>
              <el-collapse accordion v-model="activeNames">
                <el-collapse-item name="1">
                  <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="queryFormRef">
                    <el-form-item label="设备类型" prop="deviceType">
                      <el-select v-model="queryParams.deviceType" placeholder="设备类型" clearable>
                        <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.typeName"
                          :value="item.deviceTypeId" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="设备名称" prop="deviceName">
                      <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable />
                    </el-form-item>
                    <el-form-item label="设备MAC" prop="deviceMac">
                      <el-input v-model="queryParams.deviceMac" placeholder="请输入设备MAC" clearable />
                    </el-form-item>
                    <el-form-item label="设备IMEI" prop="deviceImei">
                      <el-input v-model="queryParams.deviceImei" placeholder="请输入设备IMEI" clearable
                        @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="操作时间" style="width: 308px">
                      <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="handleQuery">查询</el-button>
                      <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </div>
        </transition>
        <el-card class="Maplist">
          <div>
            <el-table v-loading="loading" border :data="deviceList" @selection-change="handleSelectionChange" height="calc(100vh - 400px)">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="设备名称" align="center" prop="deviceName" />
              <el-table-column label="设备型号" align="center" prop="deviceType" />
              <el-table-column label="操作模块" align="center" prop="deviceAction" />
              <el-table-column label="操作内容" align="center" prop="content" show-overflow-tooltip >
                  <template #default="scope">
                  <div>{{scope.row.content || '/'}}</div>
                </template>
              </el-table-column>

              <el-table-column label="操作时间" align="center" prop="createTime" />
            </el-table>
            <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
              :total="total" @pagination="getList" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

</template>

<script setup name="User" lang="ts">
import api from '@/api/controlCenter/delivey/index'
import apiTypeAll from '@/api/equipmentManagement/device/index';
import { deviceQuery, deviceVO } from '@/api/controlCenter/delivey/types';
const dateRange = ref(['', '']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceList = ref<deviceVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptName = ref();
const deptOptions = ref([])
const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const activeNames = ref([]);
const deviceTypeOptions = ref([]); //设备类型
const enabledDeptOptions = ref();
const debounceTimer = ref(null)   // 用于防抖的定时器
const initData: PageData<'', deviceQuery> = {
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: '',
    deviceMac: '',
    deviceImei: '',
    groupId: '',
    deviceType: '',
    startTime: '',
    endTime: '',
    content: ""
  },
  rules: undefined,
  form: ''
};
const data = reactive<PageData<'', deviceQuery>>(initData);
const { queryParams } = toRefs<PageData<'', deviceQuery>>(data);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.groupName.indexOf(value) !== -1;
};
// 设备类型
const getDeviceType = () => {
  apiTypeAll.deviceTypeAll().then(res => {
    if (res.code == 200) {
      deviceTypeOptions.value = res.data
    }
  }).catch(err => {

  })
};
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);
const toggleFilter = () => {
  if (activeNames.value.length > 0) {
    activeNames.value = [];
  } else {
    activeNames.value = ['1'];
  }
};


/** 过滤禁用的部门 */
const filterDisabledDept = (deptList: any[]) => {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  queryParams.value.groupId = data.id;
  handleQuery();
};
const handleInput = () => {
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
  }
  // 300ms后执行查询（避免输入过程中频繁调用接口）
  debounceTimer.value = setTimeout(() => {
    handleQuery()  // 调用查询接口的方法
  }, 300)
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.groupId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};

/** 选择条数  */
const handleSelectionChange = (selection: deviceVO[]) => {
  ids.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
onMounted(() => {
  getDeptTree(); // 初始化部门数据
  getList(); // 初始化列表数据
  getDeviceType() //设备类型
});
/** 查询用户列表 */
const getList = async () => {
  loading.value = false;
  const [startTime, endTime] = dateRange.value;
  queryParams.value = {
    ...queryParams.value,
    startTime: startTime,
    endTime: endTime
  };
  const res = await api.deviceInstructionRecord(queryParams.value)
  loading.value = false;
  deviceList.value = res.rows;
  total.value = res.total;
};

/** 查询部结构 */
const getDeptTree = async () => {
  const res = await api.devicegroupList('');
  const allDeviceOption = {
    id: '',
    groupName: '全部设备',
    disabled: false,
    children: []

  };
  deptOptions.value = [allDeviceOption, ...res.data]
  enabledDeptOptions.value = filterDisabledDept(res.data);
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/api/device/export',
    {
      ...queryParams.value
    },
    `指令下发记录${new Date().getTime()}.xlsx`,
    'get'
  );
};

</script>
<style lang="scss" scoped>
.p-2{
  background: rgba(247, 248, 252, 1);
height: calc(100vh - 8vh);
  box-sizing: border-box;
  padding: 15px;
}
:deep .el-collapse{
  border-top:none
}
:deep .el-collapse-item__header {
  display: none;
}

:deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  color: rgba(2, 124, 251, 1);
  background: transparent;
}

.main-tree {
  border-radius: 4px;
  box-shadow: 0px 0px 6px 0px rgba(0, 34, 96, 0.1);
  background: rgba(255, 255, 255, 1);
  width: 212px;
  border: none;
  padding-top: 10px;

}

.el-card {
  border: none
}

.btn_search {
  padding: 0px 15px 15px 0px;
  // border-bottom: 1px solid rgba(235, 238, 248, 1);
}

.queryFormRef {
  margin-top: 20px;
}

.green {
  color: rgba(0, 165, 82, 1);
}

.red {
  color: rgba(224, 52, 52, 1);
}

.Maplist {
 height: calc(100vh - 24vh);
 // overflow: auto;
}
</style>
