<template>
  <div class="card-box" v-if="!configurationParameters.drawerMode">
    <div
      class="section-tab"
      :innerText="configurationParameters"
      contenteditable="true"
      :style="{ backgroundColor: configurationParameters.tabBackgroundColor }">
      <a-icon :type="configurationParameters.icon" style="margin-left: 2%;font-size: medium;"/>
      {{ configurationParameters.tab }}
    </div>
    <div class="patient-overview">
      <div
        class="overview-section"
        v-for="(item,index) in data"
        :key="index"
        :style="{borderBottom: index === data.length - 1 ? 'none' : '1px solid #ddd'}">
        <div class="section-header" :style="{ backgroundColor: item.backgroundColor, color: item.fontColor }">
          {{ item.titleName }}({{ item.messageNumber }})
        </div>
        <div class="patient-list-container">
          <div class="patient-list">
            <div
              v-for="(patient, i) in item.showData"
              :key="i"
              class="patient-item"
              :title="`${patient.room_number} - ${patient.patient_name}`">
              <span class="card_data" :style="{ color: item.fontColor }">{{ patient.room_number }}</span>
              <span class="card_data" >{{ patient.patient_name }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div v-else class="card-box">
    <div
      class="section-tab"
      :innerText="configurationParameters"
      contenteditable="true"
      :style="{ backgroundColor: configurationParameters.tabBackgroundColor }">
      <a-icon :type="configurationParameters.icon" style="margin-left: 2%;font-size: medium;"/>
      {{ configurationParameters.tab }}
    </div>
    <a-collapse accordion class="accordion" :activeKey="activeKey" @change="switchDrawers">
      <a-collapse-panel
        v-for="(time, rowId) in times"
        :header="time"
        :style="{backgroundColor:rowId === rowIndex ? configurationParameters.tabBackgroundColor : '#fff'}"
        :key="rowId" >
        <div class="patient-overview">
          <div
            class="overview-section"
            v-for="(item,index) in data"
            :key="index"
            :style="{borderBottom: index === data.length - 1 ? 'none' : '1px solid #ddd'}">
            <div class="section-header" :style="{ backgroundColor: item.backgroundColor, color: item.fontColor }">
              {{ item.titleName }}({{ item.messageNumber }})
            </div>
            <div class="patient-list-container">
              <div class="patient-list">
                <div
                  v-for="(patient, i) in item.showData"
                  :key="i"
                  class="patient-item"
                  :title="`${patient.room_number} - ${patient.patient_name}`">
                  <span class="card_data" :style="{ color: item.fontColor }">{{ patient.room_number }}</span>
                  <span class="card_data" >{{ patient.patient_name }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>

<script>

import { getConfigByName, runLogic } from '@vue2-client/services/api/common'

export default {
  name: 'CardComponent',
  data () {
    return {
      tab: 'container',
      data: [
        { room_number: '', patient_name: '' }
      ],
      activeKey: '0',
      times: [],
      DateTimes: [],
      rowIndex: 0,
      /* 配置参数(titleName：行标题名，dataSource：数据源，parameter：参数，fontColor：文字颜色，backgroundColor：背景颜色，
     pageSize：分页数量，tabBackgroundColor：标签背景颜色，isPrimarySource：是否取mainDataSource中的元素)， drawerMode：是否选用抽屉模式
     times：如果选用抽屉 */
      configurationParameters: {
        drawerMode: false,
        tab: '',
        icon: '',
        tabBackgroundColor: '',
        mainDataSource: '',
        serverName: '',
        parameter: { pageSize: 8 },
        times: 4,
        configurationData: [
          {
            titleName: '',
            isPrimarySource: true,
            dataSource: '',
            fontColor: '',
            backgroundColor: ''
          }
        ]
      }
    }
  },
  props: {
    queryParamsName: {
      type: String,
      default: 'nurseStationHomeConfig'
    }
  },
  created () {
    this.getData(this.queryParamsName)
  },
  methods: {
    async getData (data) {
      this.data = []
      getConfigByName(data, 'af-his', res => {
        if (!res.drawerMode) {
          this.renderDeck(res)
        } else { this.renderData(res) }
      })
    },
    // 渲染卡片组数据
    async renderDeck (res, times) {
      this.configurationParameters = await res
      if (res.drawerMode) {
        res.parameter.times = await times
      }
      runLogic(res.mainDataSource, res.parameter).then(result => {
        for (let i = 0; i < res.configurationData.length; i++) {
          const ConfigureDisplayData = {
            titleName: res.configurationData[i].titleName,
            fontColor: res.configurationData[i].fontColor,
            backgroundColor: res.configurationData[i].backgroundColor,
            messageNumber: result[res.configurationData[i].dataSource + 'Total'][0].total,
            showData: []
          }
          this.data.push(ConfigureDisplayData)
          this.data[i].showData = result[res.configurationData[i].dataSource]
        }
      })
    },
    formatTime (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')
      return `${year}-${month}-${day} ${hours}:00`
    },
    getTimes (n) {
      const times = []
      const now = new Date()
      for (let i = 0; i <= n; i++) {
        const time = new Date(now.getTime() + i * 60 * 60 * 1000)
        times.push(this.formatTime(time))
      }
      return times
    },
    formatTimeToHHMM (timeString) {
      const date = new Date(timeString)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },
    // 获取数据并渲染数据
    renderData (data) {
      this.times = []
      this.DateTimes = []
      const time = this.getTimes(data.times)
      for (let i = 0; i < data.times; i++) {
        const startTime = this.formatTimeToHHMM(time[i])
        const endTime = this.formatTimeToHHMM(time[i + 1])
        this.times.push(`${startTime} ~ ${endTime}`)
        this.DateTimes.push(`${time[i]} and ${time[i + 1]}`)
      }
      this.renderDeck(data, `${time[0]} and ${time[1]}`)
    },
    // 切换抽屉
    switchDrawers (activeKey) {
      if (activeKey !== undefined) {
        console.log('Active Header:', this.DateTimes[activeKey])
        this.data = []
        this.renderDeck(this.configurationParameters, this.DateTimes[activeKey])
        this.rowIndex = activeKey
      }
    }
  },
  watch: {
    queryParamsName: {
      handler (newValue) {
        this.getData(newValue)
      },
      deep: true
    }
  },
}
</script>

<style scoped>
.accordion{
  width: 100%;
}
.patient-overview {
  width: 100%;
  padding: 0.5%;
  border: 1px solid #ddd;
  border-radius: 0 5px 5px 5px;
  height: 100%;
  background-color: white;
  overflow: scroll;
}
.section-header {
  font-weight: bold;
  display: flex;
  width: 10%;
  align-items: center;
  justify-content: center;
  min-height: 45px;
  border-radius: 5px;
  min-width: 90px;
}
.patient-list-container {
  display: flex;
  align-items: center;
  width: 100%;
  padding-left: 1%;
}
.overview-section{
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  margin-top: 1%;
  border-bottom: 1px solid #ddd;
  padding-bottom: 0.7%;
}
.patient-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}
.patient-item {
  background-color: #fff;
  padding: 0.3%;
  border: 1px solid #ddd;
  width: 4%;
  height: 21%;
  text-align: center;
  font-size: x-small;
  border-radius: 5px;
  min-width: 45px;
  min-height: 45px;
  cursor: pointer;
}
.patient-item:hover {
  background-color: #f0f0f0;
}
.patient-item span {
  display: block;
}
.section-tab {
  width: 2vw;
  height: 22vh;
  display: flex;
  writing-mode: vertical-rl;
  align-items: center;
  justify-content: space-evenly;
  border-radius: 5px 0 0 5px;
  color: white;
  min-width: 27px;
  min-height: 80px;
  max-height: 95px;
  max-width: 30px;
}
.card-box {
  display: flex;
  flex-direction: row;
  height: 100%;
}
.card_data{
  display: inline-block;
  max-width: 5ch; /* 最多显示 3 个字符 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
