<!-- 首页看板 -->
<script lang="ts" setup name="Dashboard">
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { Search } from '@element-plus/icons-vue'
import editScheduleDialog from './components/editScheduleDialog.vue'
import tableList from './components/tableList.vue'
import BarChartVerticalCom from './components/BarChartVertical.vue'
import BarChartHorizontalCom from './components/BarChartHorizontalCom.vue'
import { delSchedule, getCalendarList } from '@/api/eqpt/dashboard/calendar'
import { getMeasureDetail, getMeasureDetailTrend } from '@/api/eqpt/dashboard/index'
import useUserStore from '@/store/modules/user'
const height = ref(document.body.clientHeight - 50 - 60 - 10)
const user = useUserStore()// 用户信息
// ------------------------------------UI------------------------------------------
const blockHeight = ref(300) // 每个展示块高度
const bigBlockHeight = ref(300) // 大展示块的高度
const blockWidth = ref(400)
const smallBlockHeight = ref()
// 计算工作台区域高度 - 顶部-面包屑-边距
const benchDivHeight = ref(215)
function calcBlockSize() { // 36是消息滚动栏的高度
  const bodyHeight = document.body.clientHeight - 60 - 20 - 50 - 15
  bigBlockHeight.value = bodyHeight
  blockHeight.value = bodyHeight > 610 ? (bodyHeight) / 3 : 300
  smallBlockHeight.value = bodyHeight > 610 ? (bodyHeight) / 4 : 215
  blockWidth.value = (document.body.clientWidth - 180 - 20 - 20) / 3
  console.log(blockHeight.value, blockWidth.value - 20)
  benchDivHeight.value = blockHeight.value - 60
}
// -----------------------------------日历--------------------------------------------
const calendarValue = ref(new Date())
const selectedDate = ref('') // 选中的日期
const selectDateRecord = ref('') // 选中的日期记录--完整日期
const editScheduleRef = ref() // 编辑日程ref
const redCircleData = ref() // 日程列表
// 点击编辑日程
const editSchedule = () => {
  editScheduleRef.value.initDialog()
}
// 获取日程列表
const fetchCalendarList = () => {
  const param = {
    userId: user.id,
    calendarMonth: selectedDate.value,
  }
  getCalendarList(param).then((res) => {
    redCircleData.value = res.data
  })
}
// 点击日期
const clickDate = (day: string) => {
  selectDateRecord.value = day
  selectedDate.value = day.slice(0, 7)
  fetchCalendarList() // 获取日历列表
}
// 点击删除icon
const deleteData = () => {
  if (!redCircleData.value || (Object.keys(redCircleData.value).length && !redCircleData.value[selectDateRecord.value].length)) {
    ElMessage.warning(`${selectDateRecord.value}没有日程，无法删除`)
    return false
  }
  ElMessageBox.confirm(
    `确定删除${selectDateRecord.value}的日程吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      const param = {
        userId: user.id,
        scheduleDate: selectDateRecord.value,
      }
      delSchedule(param).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchCalendarList() // 获取日历列表
      })
    })
}

// 编辑日程成功
const editScheduleSuccess = () => {
  fetchCalendarList() // 获取日历列表
}

// -----------------------------------------检定详情-------------------------------------
const measureDetailLoading = ref(false) // 检定详情loading
const measureDetailXData = ref([]) as any // 检定详情x轴数据
const measureDetailYDataMax = ref() // 检定详情Y轴数据最大值
const measureDetailData = ref([]) as any // 检定详情数据
const measureDetailYearCount = ref(0) // 年度已检数量
const measureDetailMonthCount = ref(0) // 年度应检数量
// 获取检定详情
const fetchMeasureDetail = () => {
  measureDetailLoading.value = true
  getMeasureDetail().then((res) => {
    console.log(res.data, 'aaa')
    measureDetailMonthCount.value = res.data.yearToCheck
    measureDetailYearCount.value = res.data.yearChecked
  })
  getMeasureDetailTrend().then((res) => {
    measureDetailXData.value = res.data.map((item: any) => item.time)
    measureDetailData.value = [
      {
        name: '已检设备数量',
        data: res.data.map((item: any) => item.haveChecked),
        color: '#19be6b',
      },
      {
        name: '应检设备数量',
        data: res.data.map((item: any) => item.shouldCheck),
        color: '#2d8cf0',
      },
    ]
    measureDetailLoading.value = false
  })
}

// -----------------------------------------设备详情-------------------------------------

const Devicedept = ref()// 所属部门
const Devicelegend = ref({ // 饼图legend
  show: true,
  orient: 'horizontal',
  // right: '20%',
  top: '0',
  icon: 'circle',
  itemWidth: 12,
  itemHeight: 12,
  itemStyle: {
    fontSize: 18,
  },
})
// -----------------------------------------设备状态-------------------------------------
// 导航菜单
const deviceTable = ref([
  {
    name: '在检设备',
    img: '/src/assets/images/bench/在检设备.png',
  },
  {
    name: '待检设备',
    img: '/src/assets/images/bench/待检设备.png',
  },
  {
    name: '在用设备',
    img: '/src/assets/images/bench/在用设备.png',
  },
])
// 展示 0在检设备 1待检设备 2在用设备
const showDevice = ref(0)
const changeShow = (index: number) => {
  showDevice.value = index
}
const tableDept = ref() // 所属部门
const columns = ref([
  { text: '设备名称', value: 'planName' },
  { text: '规格型号', value: 'director' },
  { text: '所属部门', value: 'trainTime' },
  { text: '在检数量', value: 'count' },
])
const haveCheckList = ref([
  {
    planName: '1',
    director: '123',
    trainTime: '顶级',
    count: '1',
  },
  {
    planName: '2',
    director: '123',
    trainTime: '顶级',
    count: '9',
  },
  {
    planName: '3',
    director: '123',
    trainTime: '顶级',
    count: '7',
  },
  {
    planName: '5',
    director: '123',
    trainTime: '顶级',
    count: '4',
  },
  {
    planName: '6',
    director: '123',
    trainTime: '顶级',
    count: '6',
  },
  {
    planName: '8',
    director: '123',
    trainTime: '顶级',
    count: '8',
  },
])
const scrollTable = ref()
const scrolltimer = ref()
// 设置自动滚动
const autoScroll = (stop: boolean) => {
  const table = scrollTable.value
  console.log(table, 'tabletabletable')
  // 拿到表格中承载数据的div元素
  const divData = table?.$refs.bodyWrapper.getElementsByClassName('el-scrollbar__wrap')[0]

  // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
  if (stop) {
    // 再通过事件监听，监听到 组件销毁 后，再执行关闭计时器。
    window.clearInterval(scrolltimer.value)
    scrolltimer.value = null
  }
  else {
    scrolltimer.value = window.setInterval(() => {
      // divData.style.transition = 'all 1s'
      // 元素自增距离顶部1像素
      divData.scrollTop += 1
      // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
      if (divData.clientHeight + divData.scrollTop == divData.scrollHeight) {
        // 重置table距离顶部距离
        divData.scrollTop = 0
        // 重置table距离顶部距离。值=(滚动到底部时，距离顶部的大小) - 整个高度/2
        // divData.scrollTop = divData.scrollTop - divData.scrollHeight / 2
      }
    }, 100) // 滚动速度
  }
}

// ------------------------------------------------------------------------------------
onMounted(() => {
  calcBlockSize()
  selectedDate.value = dayjs().format('YYYY-MM')
  selectDateRecord.value = dayjs().format('YYYY-MM-DD')
  fetchMeasureDetail() // 获取检定详情
  // fetchApprovalMessageData() // 审批提醒
  // fetchWorkMessageData() // 工作提醒
  // fetchNoticeList() // 获取通知公告列表
  fetchCalendarList() // 获取日历列表

  // -------------------监听日历三个按钮操作（上个月、今天、下个月）------------------
  // 点击上个月
  const prevBtn = document.querySelector(
    '.el-calendar__button-group .el-button-group>button:nth-child(1)',
  )
  prevBtn!.addEventListener('click', (e) => {
    const day = dayjs(calendarValue.value).format('YYYY-MM')
    clickDate(day)
  })

  // 点击下一个月
  const nextBtn = document.querySelector(
    '.el-calendar__button-group .el-button-group>button:nth-child(3)',
  )
  nextBtn!.addEventListener('click', () => {
    const day = dayjs(calendarValue.value).format('YYYY-MM')
    clickDate(day)
  })

  // 点击今天
  const todayBtn = document.querySelector(
    '.el-calendar__button-group .el-button-group>button:nth-child(2)',
  )
  todayBtn!.addEventListener('click', () => {
    const day = dayjs(calendarValue.value).format('YYYY-MM')
    clickDate(day)
  })
  autoScroll(false)
  // ------------------------------------------------------------------------------
})
onBeforeUnmount(() => {
  autoScroll(true)
  // clearInterval()
  // clea
})
</script>

<template>
  <app-container>
    <div class="container">
      <div class="container" style="width: 66.66%;">
        <bench-col
          style="position: relative;overflow-y: scroll;width: 49%;"
          icon="icon-calendar"
          title="工作日历"
          :height="blockHeight"
          :is-edit="true"
          :is-show-delete="true"
          @edit-data="editSchedule"
          @delete-data="deleteData"
        >
          <el-calendar v-model="calendarValue" class="calendar" :style="`height:${blockHeight}px`">
            <template #dateCell="{ data }">
              <div style="width: 100%;height: 100%;text-align: center;" @click="clickDate(data.day)">
                <span>
                  {{ data.day.split("-").slice(2).join() }}
                </span>
              </div>
              <div v-for="(value, key, index) in redCircleData" :key="index">
                <el-popover
                  v-if="key === data.day && value.length"
                  placement="top-start"
                  trigger="hover"
                  width="auto"
                >
                  <div class="popover-content-area-class">
                    <span style="font-weight: 600;">{{ key }}</span>
                    <li v-for="(e, i) in value" :key="i" class="calendar-li-item">
                      {{ e.scheduleMatters }}
                    </li>
                  </div>
                  <template #reference>
                    <div style="width: 100%;height: 100%;display: flex;flex-direction: column;align-items: center;" @click="clickDate(data.day)">
                      <!-- <span>
                        {{ data.day.split("-").slice(2).join() }}
                      </span> -->
                      <span style="margin-top: -30px;">
                        <el-icon :size="20" color="#f56c6c">
                          <alarm-clock />
                        </el-icon>
                        <!-- <span v-if="key === data.day" class="redCircle" /> -->
                      </span>
                    </div>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-calendar>
        </bench-col>
        <bench-col
          v-loading="measureDetailLoading"
          style="width: 49%;position: relative;"
          icon="icon-line"
          title="检定详情"
          :height="blockHeight"
        >
          <div style="display: flex;margin-bottom: 10px;position: absolute; top: 5px;right: 10px;">
            <div style="display: flex;margin-right: 20px;">
              <img src="../../../assets/images/bench/have.png" width="40" height="40">
              <div>
                <div style="font-size: 14px;">
                  年度已检数量
                </div>
                <div style="margin-left: 10px;color: #000;font-weight: 600;">
                  {{ measureDetailYearCount }}
                </div>
              </div>
            </div>
            <div style="display: flex;">
              <img src="../../../assets/images/bench/to.png" width="40" height="40">
              <div>
                <div style="font-size: 14px;">
                  年度应检数量
                </div>
                <div style="margin-left: 10px;color: #000;font-weight: 600;">
                  {{ measureDetailMonthCount }}
                </div>
              </div>
            </div>
          </div>
          <line-chart
            style="width: 100%; height: 100%;"
            :x-axis-data="measureDetailXData"
            :width="`${blockWidth - 20}px`"
            :data="measureDetailData"
          />
        </bench-col>
        <bench-col
          v-loading="false"
          style="width: 99%;margin-top: 6px;position: relative;"
          icon="icon-line"
          title="设备详情"
          :height="blockHeight"
        >
          <div class="device-search">
            <dept-select v-model="Devicedept" placeholder="所属部门" style="width: 150px;" />
            <el-icon class="search" style="font-size: 28px;">
              <search style=" margin-left: 8px;" />
            </el-icon>
          </div>

          <div :style="`height:${blockHeight - 65}px`" class="device-container">
            <!-- 设备分类分析 -->
            <pie-chart style="width: 33%; height: 100%;" title="设备分类分析" label-position="outside" :legend="Devicelegend" :width="`${(blockWidth * 2) / 3 - 10}px`" :data="[{ name: '无线电', value: 10 }, { name: '压力', value: 20 }]" :radius="['70%']" />
            <!-- 设备状态分析 -->
            <pie-chart style="width: 33%; height: 100%;" title="设备状态分析" label-position="outside" :legend="Devicelegend" :width="`${(blockWidth * 2) / 3 - 10}px`" :data="[{ name: '无线电', value: 10 }, { name: '压力', value: 20 }]" :radius="['70%']" />
            <!-- 设备类型分析 -->
            <bar-chart-vertical-com style="width: 33%; height: 100%;" title="设备类型分析" :width="`${(blockWidth * 2) / 3 - 10}px`" :legend="{ show: false }" :data="[2, 13, 19, 16]" :x-axis-data="['data1', 'data2', 'data3', 'data4']" />
          </div>
        </bench-col>
        <bench-col
          v-loading="false"
          style="width: 99%; margin-top: 6px;position: relative;"
          icon=""
          title=""
          :height="blockHeight"
        >
          <div class="device-table">
            <div v-for="(item, index) in deviceTable" :key="item.name" class="tab" :class="`${showDevice === index ? 'tab-active' : ''}`">
              <img :src="item.img" width="40" height="40">
              <span class="content" @click="changeShow(index)"> {{ item.name }}</span>
            </div>
          </div>
          <div class="device-search-table">
            <dept-select v-model="tableDept" placeholder="所属部门" style="width: 150px;" />
            <el-icon class="search" style="font-size: 28px;">
              <search style=" margin-left: 8px;" />
            </el-icon>
          </div>
          <!-- 在检设备 -->
          <div :class="`${showDevice === 0 ? '' : 'none'}`" :style="`height:${blockHeight - 65}px`" class="device-container">
            <!-- 检定设备态势 -->
            <pie-chart style="width: 33%; height: 100%;" title="检定设备态势" :legend="Devicelegend" :width="`${(blockWidth * 2) / 3 - 10}px`" :data="[{ name: '无线电', value: 10 }, { name: '压力', value: 20 }]" :radius="['70%', '50%']" />
            <!-- 部门排行榜 -->
            <bar-chart-horizontal-com
              style="width: 33%;  height: 100%;" title="部门排行榜" :width="`${(blockWidth * 2) / 3 - 10}px`" :series-data="[{ width: 8, data: [9, 13, 15, 19, 12, 15, 13, 16, 18, 20, 21, 14, 13] },
                                                                                                                        { width: 1, data: [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22] }]" :y-axis-data="['data1-1-9', 'data2-2-13', 'data3-3-15', 'data4-4-19', 'data5-5-12', 'data6-6-15', 'data7-7-13', 'data8-8-16', 'data9-9-18', 'data10-10-20', 'data11-11-21', 'data12-12-14', 'data13-13-13']"
            />
            <!-- 在检设备列表 -->
            <el-table
              ref="scrollTable"
              :data="haveCheckList"
              style="width: 33%;  height: 100%;"
              :height="blockHeight - 65"
              stripe
              header-row-class-name="bench-table-header"
              row-class-name="bench-table-row"
              class="bench-table"
              @mouseenter="autoScroll(true)"
              @mouseleave="autoScroll(false)"
            >
              <el-table-column
                v-for="item in columns"
                :key="item.value"
                :prop="item.value"
                align="center"
                :label="item.text"
                :width="item.width"
                show-overflow-tooltip
              />
            </el-table>
          </div>
          <div :class="`${showDevice === 1 ? '' : 'none'}`" :style="`height:${blockHeight - 65}px`" class="device-container">
            <!-- 检定设备态势 -->
            <pie-chart style="width: 33%; height: 100%;" title="检定设备态势" :legend="Devicelegend" :width="`${(blockWidth * 2) / 3 - 10}px`" :data="[{ name: '无线电1', value: 101 }, { name: '压力1', value: 120 }]" :radius="['70%', '50%']" />
            <!-- 部门排行榜 -->
            <bar-chart-horizontal-com
              style="width: 33%;  height: 100%;" title="部门排行榜" :width="`${(blockWidth * 2) / 3 - 10}px`" :series-data="[{ width: 8, data: [19, 13, 15, 19, 12, 15, 13, 16, 18, 20, 21, 14, 13] },
                                                                                                                        { width: 1, data: [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22] }]" :y-axis-data="['data1-1-19', 'data2-2-13', 'data3-3-15', 'data4-4-19', 'data5-5-12', 'data6-6-15', 'data7-7-13', 'data8-8-16', 'data9-9-18', 'data10-10-20', 'data11-11-21', 'data12-12-14', 'data13-13-13']"
            />
            <!-- 在检设备列表 -->
            <el-table
              ref="scrollTable"
              :data="haveCheckList"
              style="width: 33%;  height: 100%;"
              :height="blockHeight - 65"
              stripe
              header-row-class-name="bench-table-header"
              row-class-name="bench-table-row"
              class="bench-table"
              @mouseenter="autoScroll(true)"
              @mouseleave="autoScroll(false)"
            >
              <el-table-column
                v-for="item in columns"
                :key="item.value"
                :prop="item.value"
                align="center"
                :label="item.text"
                :width="item.width"
                show-overflow-tooltip
              />
            </el-table>
          </div>
          <div :class="`${showDevice === 2 ? '' : 'none'}`" :style="`height:${blockHeight - 65}px`" class="device-container">
            <!-- 检定设备态势 -->
            <pie-chart style="width: 33%; height: 100%;" title="检定设备态势" :legend="Devicelegend" :width="`${(blockWidth * 2) / 3 - 10}px`" :data="[{ name: '无线电', value: 100 }, { name: '压力', value: 20 }]" :radius="['70%', '50%']" />
          </div>
        </bench-col>
      </div>
      <div class="container" style="width: 33.33%;">
        <bench-col
          v-loading="false"
          path-url="123"
          style="width: 98%;"
          icon="icon-line"
          title="检定通知"
          :height="smallBlockHeight"
        >
          <table-list :height="smallBlockHeight - 50" :limit="5" />
        </bench-col>
        <bench-col
          v-loading="false"
          path-url="123"
          style="width: 98%; margin-top: 6px;"
          icon="icon-line"
          title="通知公告"
          :height="smallBlockHeight"
        >
          <table-list :height="smallBlockHeight - 50" :limit="5" />
        </bench-col>
        <bench-col
          v-loading="false"
          path-url="123"
          style="width: 98%; margin-top: 6px;"
          icon="icon-line"
          title="审批提醒"
          :height="smallBlockHeight"
        >
          <table-list :height="smallBlockHeight - 50" :limit="5" />
        </bench-col>
        <bench-col
          v-loading="false"
          path-url="123"
          style="width: 98%; margin-top: 6px;"
          icon="icon-line"
          title="工作提醒"
          :height="smallBlockHeight"
        >
          <table-list :height="smallBlockHeight - 50" :limit="5" />
        </bench-col>
      </div>
    </div>

    <!-- 编辑日程组件 -->
    <edit-schedule-dialog ref="editScheduleRef" @edit-schedule-success="editScheduleSuccess" />
  </app-container>
</template>

<style lang="scss" scoped>
.none {
  opacity: 0;
}

.bench-table {
  .el-table__header-wrapper {
    border-radius: 8px;
  }
}

.bench-table-header {
  th {
    font-weight: normal;
    font-size: 14px;
  }
}

.bench-table-row {
  border-radius: 8px;
}

.device-search-table {
  position: absolute;
  top: 10px;
  right: 15px;
  display: flex;
  align-items: center;
}

.tab-active {
  background-color: #3d7eff !important;
}

.device-table {
  position: relative;
  top: 0;
  left: 10px;
  display: flex;

  .tab {
    background-color: #eee7e7;
    // margin: 0 10px;
    display: flex;
    align-items: center;
    border-radius: 5px;

    &:hover {
      cursor: pointer;
    }

    .content {
      display: inline-block;
      padding-right: 10px;
    }
  }
}

.container {
  // width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 0;
  overflow: hidden;

  .device-search {
    position: absolute;
    top: 10px;
    left: 150px;
    display: flex;
    align-items: center;
  }
}

.search {
  &:hover {
    cursor: pointer;
  }
}

.device-container {
  display: flex;
  justify-content: space-around;
  position: absolute;
  width: 100%;
}

.calendar {
  position: absolute;
  top: 34px;
  left: 0;

  ::v-deep(.el-calendar__body) {
    transform: scaleY(0.6);
    padding: 0 15px;
    margin-top: -76px;
    // position: absolute;
    // top: 0;
  }
}
</style>
