<template>
  <div class="blocking-data-screen">
    <div class="screen-header">
      <div class="header-title">盛世鹰眸质控系统【查堵】（安检站）</div>
    </div>

    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">日期：</span>
          <el-date-picker v-model="filterParams.dateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime"
            style="width: 280px" />
        </div>

        <div class="filter-item">
          <span class="filter-label">分管主管：</span>
          <el-select v-model="filterParams.supervisorId" placeholder="请选择主管" filterable clearable style="width: 200px">
            <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <div class="filter-item">
          <span class="filter-label">分管班组长：</span>
          <el-select v-model="filterParams.teamLeaderId" placeholder="请选择班组长" filterable clearable style="width: 200px">
            <el-option v-for="item in teamLeaderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">航站楼：</span>
          <el-select v-model="filterParams.terminalId" placeholder="请选择区域" clearable style="width: 200px"
            @change="terminalChange">
            <el-option v-for="item in terminalOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <div class="filter-item">
          <span class="filter-label">漏检物品：</span>
          <el-tree-select v-model="filterParams.missCheckItem" :data="missedItemOptions"
            :props="{ value: 'id', label: 'name', children: 'children', disabled: data => data.children && data.children.length > 0 }"
            value-key="id" placeholder="请选择漏检物品" check-strictly style="width: 200px" clearable @change="missCheckItemChange"/>
        </div>

        <div class="filter-item">
          <span class="filter-label">分大队：</span>
          <el-select v-model="filterParams.brigadeId" placeholder="请选择大队" clearable style="width: 200px">
            <el-option v-for="item in brigadeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <!-- <div class="filter-actions">
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div> -->
      </div>


    </div>

    <div class="screen-content">
      <div v-if="filterParams.brigadeId=='all'" class="grid-layout">
        <div class="grid-item">
          <module-one :filter-params="filterParams" />
        </div>
        <div class="grid-item">
          <module-two :filter-params="filterParams" />
        </div>
        <div class="grid-item">
          <module-three :filter-params="filterParams" />
        </div>
        <div class="grid-item">
          <module-four :filter-params="filterParams" />
        </div>
      </div>
      <div v-else class="grid-layout">
        <div class="grid-item">
          <module-brigade-one :filter-params="filterParams" />
        </div>
        <div class="grid-item">
          <module-brigade-two :filter-params="filterParams" />
        </div>
        <div class="grid-item">
          <module-brigade-three :filter-params="filterParams" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { listDept } from '@/api/system/dept'
import { selectUserLeaderListByCondition } from '@/api/system/user'
import { listCategory } from '@/api/system/category'
import { listPosition } from '@/api/system/position'
import ModuleOne from './components/ModuleOne.vue'
import ModuleTwo from './components/ModuleTwo.vue'
import ModuleThree from './components/ModuleThree.vue'
import ModuleFour from './components/ModuleFour.vue'
import ModuleBrigadeOne from './components/ModuleBrigadeOne.vue'
import ModuleBrigadeTwo from './components/ModuleBrigadeTwo.vue'
import ModuleBrigadeThree from './components/ModuleBrigadeThree.vue'

// 默认时间设置
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 1, 1, 23, 59, 59)
]

// 筛选参数
const filterParams = reactive({
  dateRange: [],
  supervisorId: '',
  teamLeaderId: '',
  terminal: '',
  terminalId: '',
  missCheckItem: '',
  brigadeId: 'all'
})

// 选项数据
const supervisorOptions = ref([])
const teamLeaderOptions = ref([])
const brigadeOptions = ref([])
const missedItemOptions = ref([])
const terminalOptions = ref([])

// 获取漏检物品树状选项
function getMissedItemOptions() {
  listCategory().then(response => {
    missedItemOptions.value = handleTree(response.data, "id", "parentId")
  })
}
const terminalChange = (value) => {
  if(!value){
    filterParams.terminal = ''
    filterParams.terminalId = ''
    return;
  }

  filterParams.terminal = terminalOptions.value.find(item => item.value === value).label
}

const missCheckItemChange = (value) => { 
  if(!value){
    filterParams.missCheckItem = ''
    return;

  }
}

// 树形数据处理函数
function handleTree(data, id, parentId) {
  const result = []
  const map = {}

  data.forEach(item => {
    map[item[id]] = { ...item, children: [] }
  })

  data.forEach(item => {
    const parent = map[item[parentId]]
    if (parent) {
      parent.children.push(map[item[id]])
    } else {
      result.push(map[item[id]])
    }
  })

  return result
}

// 获取航站楼选项
function getTerminalOptions() {
  listPosition({ positionType: 'TERMINL' }).then(response => {
    terminalOptions.value = (response.data || []).map(item => ({
      value: item.id,
      label: item.name
    }))
    // 添加"整体"选项到最前面
    terminalOptions.value.unshift({ label: '整体', value: 'all' })
  })
}
function getTeamLeaderOptions() {
  selectUserLeaderListByCondition({ roleKeyList: ['banzuzhang'] }).then(response => {
    teamLeaderOptions.value = (response.data || []).map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

// 获取主管选项
function getSupervisorOptions() {
  selectUserLeaderListByCondition({ roleKeyList: ['kezhang'] }).then(response => {
    supervisorOptions.value = (response.data || []).map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

// 获取大队选项
function getBrigadeOptions() {
  listDept({}).then(response => {
    const deptList = response.data || []
    // 筛选类型为 BRIGADE 的部门，并过滤特定的大队ID
    brigadeOptions.value = deptList.filter(item => item.deptType === 'BRIGADE' && [311, 314, 315].includes(item.deptId)).map(item => ({
      value: item.deptId,
      label: item.deptName
    }))
    // 添加"全站"选项到最前面
    brigadeOptions.value.unshift({ label: '全站', value: 'all' })
  })
}
const setDefaultDateRange = () => {
  const now = new Date()
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
  const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)

  // 格式化日期为 YYYY-MM-DD HH:mm:ss 格式
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  filterParams.dateRange = [formatDate(startOfMonth), formatDate(endOfToday)]
}

// 处理筛选
const handleFilter = () => {
  console.log('筛选参数:', filterParams)
  // 强制触发响应式更新，确保子组件能监听到变化
  filterParams.dateRange = [...filterParams.dateRange]
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterParams, {
    dateRange: [],
    supervisorId: '',
    teamLeaderId: '',
    terminal: '',
    missCheckItem: '',
    terminalId: '',
    brigadeId: 'all'
  })
  setDefaultDateRange()
}

// 组件挂载时设置默认日期和获取用户数据
onMounted(() => {
  setDefaultDateRange()
  getTeamLeaderOptions()
  getSupervisorOptions()
  getBrigadeOptions()
  getMissedItemOptions()
  getTerminalOptions()
})
</script>

<style lang="less" scoped>
.blocking-data-screen {
  width: 100%;
  height: 100vh;

  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.screen-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;

  // border-bottom: 2px solid rgba(112, 207, 231, 0.5);
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  color: black;
  // text-shadow: 0 0 10px rgba(112, 207, 231, 0.5);
}

.filter-section {
  // background: #f8f9fa;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
}

.screen-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.grid-layout {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  height: 100%;
}

.grid-item {
  width: 100%;
}
</style>
