<template>
  <div class="app-container" style="height: 100%">
    <!-- 患者信息卡片-->
    <el-card v-loading="basicLoading" class="card">
      <div slot="header" class="patient-card-header">
        <span>患者信息</span>
      </div>
      <div class="patient-card-body">
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">患者姓名:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.patientName }}</div>
        </div>
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">性别:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.gender }}</div>
        </div>
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">年龄:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.age }}</div>
        </div>
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">病人类型:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.visitTypeName }}</div>
        </div>
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">病人标识:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.patientId }}</div>
        </div>
        <div class="patient-card-body-item">
          <div class="patient-card-body-item-title">电话号码:</div>
          <div class="patient-card-body-item-content">{{ patientInfo.phone }}</div>
        </div>
      </div>
    </el-card>
    <div class="body">
      <el-row>
        <el-col :span="10">
          <el-card class="body-left card" style="min-height: 600px">
            <div slot="header">
              <span>申请单列表</span>
            </div>
            <el-table ref="multipleTable" v-loading="basicLoading"
                      :data="applyList" border
                      highlight-current-row row-key="applyNum" stripe
                      tooltip-effect="light" @current-change="currentChange"
                      @selection-change="selectionChange"
            >
              <el-table-column v-if="false" :selectable="selectable" type="selection" width="40"/>
              <el-table-column align="left" fixed="left" label="项目信息" min-width="240" prop="itemName"
                               show-overflow-tooltip
              />
              <el-table-column :formatter="applyStateFormat" align="center" label="预约状态"
                               show-overflow-tooltip width="100"
              />
              <el-table-column :formatter="reservationDateFormat" align="center" label="预约时间段"
                               width="180"
              />
              <el-table-column align="center" label="序号" prop="reservationNum" show-overflow-tooltip width="50"/>
              <el-table-column align="left" label="申请单号" min-width="240" prop="applyNum"
                               show-overflow-tooltip
              />
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="14">
          <div v-loading="sourceLoading" class="calendar">
            <div v-for="item in dateList" :class="item.day === activeDate ? 'active-item':'' "
                 class="calendar-item" @click="calendarClick(item)"
            >
              <div>
                <span>{{ item.day.substring(5, 10) }} {{ item.week }}</span>
              </div>
              <!--              <div class="calendar-item-source" style="min-height: 21px">
                                        <span v-for="i in item.source">
                                          {{ i.queueName.substring(0, 1) }}
                                        </span>
                            </div>-->
              <div style="display: flex;align-items: center;justify-content: flex-start;flex-wrap: wrap">
                <el-tag
                  v-for="i in item.source"
                  :key="i.span"
                  effect="plain"
                  style="background-color: #00974f;color: #FFFFFF;height: 22px;font-size: 17px;padding: 0 4px;"
                  type="success"
                >
                  {{ i.span }}
                </el-tag>
              </div>
              <div style="min-height: 21px">
                <span v-if="activeSource.sourceId&&item.day === activeSource.examDate"
                      style="color: #eed200"
                >✔</span>
                <span v-if="dateHasBeen(item)">已约</span>
              </div>
            </div>
          </div>
          <div v-loading="changeSourceLoading" class="source-list">
            <div v-for="item in sourceList" class="source-list-item">
              <div class="item-left">
                {{ item.queueName }}
              </div>
              <div class="item-right">
                <div v-for="source in item.list"
                     :class="{'source-item-active':source.sourceId === activeSource.sourceId,'source-item-disabled':!sourceEnabled(source)}"
                     class="source-item" @click="sourceClick(source)"
                >
                  {{ source.timeSlot + '  ' + sourceFormat(source) }}
                  <span v-if="isUsedSource(source)" style="color: #f5222d;padding-left: 10px;padding-bottom: 5px;"
                  >已约</span>
                </div>
              </div>
            </div>
          </div>
          <div style="padding-left: 30px">
            <!--已经预约与已经登记的才能取消-->
            <el-button :disabled="![1,6].includes(activeApply.applyState)" type="success" @click="cancel">取消预约
            </el-button>
            <!--未预约,已预约,已登记的可以预约,并且要求队列id与申请单队列id相同-->
            <el-button
              :disabled="reservationDisabled()"
              type="success" @click="reservation"
            >预约
            </el-button>
            <!--<el-button type="success" @click="reservation">预约</el-button>-->
            <!--<el-button :disabled="multiApply.length===0" type="success" @click="reservationBatch">批量预约</el-button>-->
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { cancelReservation, getApplyList, getSourceList, hasSource, reservation } from '@/api/reservation'
import StorageUtils from '@/utils/Storage'
import { clearStr } from '@/utils'

const getGender = (gender) => {
  if (gender + '' === '1') {
    return '男'
  } else if (gender + '' === '2') {
    return '女'
  } else {
    return '未知'
  }
}
const getVisitTypeName = (visitTypeCode) => {
  switch (visitTypeCode + '') {
    case '1':
      return '门诊病人'
    case '2':
      return '住院病人'
    case '3':
      return '体检病人'
    default:
      return ''
  }
}

export default {
  name: 'ManualReservation',
  data() {
    return {
      applyNum: '', // 默认当前申请单号 (TODO 新需求为数组,改为向后端查询,由后端处理多张申请单)
      defaultId: '', // 默认选中ID
      basicLoading: false, // 基本信息loading
      patientInfo: {}, // 用户信息
      applyList: [], // 申请单信息
      sourceLoading: false, // 号源刷新loading
      activeApply: {}, // 当前选中申请单
      multiApply: [], // 多选申请单数据
      dateList: [], // 日期数据
      activeDate: '', // 当前选中的日期
      sourceList: [], // 号源列表
      activeSource: {}, // 当前选中号源
      changeSourceLoading: false // 号源切换loading
    }
  },
  methods: {
    reservationDisabled() {
      if (this.activeApply.queueList && this.activeApply.queueList.includes(this.activeSource.queueId) ) {
        if (this.activeSource.queueId && [0, 1, 3, 4, 6].includes(this.activeApply.applyState)) {
          return this.activeApply.isPay + '' === '2'
        }
      }
      return true
    },
    // 表格行点击初始化
    initRowClick(applyNum) {
      this.$refs.multipleTable.setCurrentRow(null)
      this.activeSource = {}
      this.activeApply = this.applyList.find(item => item.id === this.defaultId) || this.applyList.find(item => item.applyNum === applyNum)
      this.$refs.multipleTable.setCurrentRow(this.activeApply)
      // 点击菜单
      if (this.activeDate) {
        const calendarSource = this.dateList.find(item => item.day === this.activeDate)
        this.calendarClick(calendarSource)
      }
    },
    // 初始化申请单
    init(callback) {
      this.basicLoading = true
      getApplyList(this.applyNum).then(res => {
        this.applyList = res.data
        let tempApply = res.data[0]
        this.patientInfo = {
          patientName: tempApply.patientName,
          gender: getGender(tempApply.gender),
          age: tempApply.age,
          visitTypeName: getVisitTypeName(tempApply['visitTypeCode']),
          patientId: tempApply.patientId,
          phone: tempApply.phone
        }
        let queueList = []
        res.data.forEach(item => {
          if (item['queueId']&&item['queueId'] && item['queueId'] !== '0' && !queueList.includes(item['queueId'])) {
            queueList.push(...item['queueList'])
          }
        })
        // 查询每天是否有号源
        let arr = []
        let now = new Date()
        arr.push(this.formatDate(now))
        for (let i = 1; i <= 7; i++) {
          now.setDate(now.getDate() + 1)
          arr.push({
            ...this.formatDate(now),
            source: []
          })
        }
        this.dateList = arr
        this.sourceLoading = true
        hasSource({
          dateList: arr.map(item => item.day),
          queueList,
          orgCode: res.data[0].orgCode,
          yardCode: res.data[0].yardCode
        }).then(res => {
          Object.keys(res.data).forEach(i => {
            let temp = arr.find(f => i.endsWith(f.day))
            if (temp) {
              temp.source = res.data[i]
            }
          })
          this.dateList = arr
          if (callback) {
            this.$nextTick(() => {
              callback()
            })
          }
        }).finally(_ => {
          this.sourceLoading = false
        })
      }).finally(_ => {
        this.basicLoading = false
      })
    },
    formatDate(date) {
      let month = '' + (date.getMonth() + 1)
      let day = '' + date.getDate()
      let year = date.getFullYear()
      if (month.length < 2) month = '0' + month
      if (day.length < 2) day = '0' + day
      const weeks = '日一二三四五六'
      return {
        day: [year, month, day].join('-'),
        week: `周${weeks.charAt(date.getDay())}`
      }
    },
    // 行点击事件
    currentChange(newItem, oldItem) {
      this.activeApply = newItem
      if (this.applyNum.includes(newItem.applyNum)) {
        this.defaultId = newItem.id
      }
      // 查询当前最新的日期,执行click方法
      if (newItem.reservationDate && newItem.reservationDate !== '') {
        const calendarSource = this.dateList.find(item => item.day === newItem.reservationDate)
        if (calendarSource) {
          this.calendarClick(calendarSource)
        }
      }
    },
    // 多选事件
    selectionChange(val) {
      this.multiApply = val
    },
    // 预约状态
    applyStateFormat(row, column) {
      switch (row.applyState + '') {
        case '0':
          return '未预约'
        case '1':
          return '已预约'
        case '2':
          return '已检查'
        case '3':
          return '已自动取消'
        case '4':
          return '已手动取消'
        case '5':
          return '已强制取消'
        case '6':
          return '已登记'
        case '7':
          return '已作废'
        default:
          return ''
      }
    },
    // 时间段合并
    reservationDateFormat(row) {
      let txt = ''
      if (row.reservationDate) {
        txt += row.reservationDate
      }
      txt += ' '
      if (row.timeSlot) {
        txt += row.timeSlot
      }
      return txt
    },
    // 表格只允许为预约的进行勾选
    selectable(row) {
      return row.applyState + '' === '0'
    },
    // 日历点击事件
    calendarClick({ day, source }) {
      this.activeDate = day
      if (source && source.length > 0) {
        // 查询号源列表
        this.changeSourceLoading = true
        let arr = []
        source.forEach(item => {
          arr.push({
            ...item,
            queueName: item.queueName, //clearStr(item.queueName, '检查队列'),
            list: []
          })
        })
        getSourceList({
          queueList: source.map(item => item.queueId),
          examDate: day
        }).then(res => {
          res.data.forEach(item => {
            let tempNode = arr.find(f => f.queueId === item.queueId)
            tempNode.list.push(item)
          })
          this.sourceList = arr
        }).finally(_ => {
          this.changeSourceLoading = false
        })
      } else {
        this.sourceList = []
      }
    },
    // 号源点击事件
    sourceClick(source) {
      if (this.sourceEnabled(source)) {
        this.activeSource = source
      }
    },
    // 此号源是否可以点击
    sourceEnabled(source) {
      if (new Date(`${source.examDate} ${source.timeSlot.split('-')[1]}`).getTime() - new Date().getTime() > 0) {
        if (this.activeApply.applyNum) {
          switch (this.activeApply['visitTypeCode'] + '') {
            case '1':
              return source.outSourceCount > source.outUseSourceCount
            case '2':
              return source.inSourceCount > source.inUseSourceCount
            case '3':
              return source.phySourceCount > source.phyUseSourceCount
            default:
              return source.sourceCount > source.useSourceCount
          }
        } else {
          return source.sourceCount > source.useSourceCount
        }
      }
      return false
    },
    // 号源格式化展示
    sourceFormat(source) {
      if (this.activeApply.applyNum) {
        switch (this.activeApply['visitTypeCode'] + '') {
          case '1':
            return `${source.outUseSourceCount}/${source.outSourceCount}`
          case '2':
            return `${source.inUseSourceCount}/${source.inSourceCount}`
          case '3':
            return `${source.phyUseSourceCount}/${source.phySourceCount}`
          default:
            return `${source.useSourceCount}/${source.sourceCount}`
        }
      } else {
        return `${source.useSourceCount}/${source.sourceCount}`
      }
    },
    // 当前号源是否已经被预约
    isUsedSource(source) {
      return this.activeApply.sourceId === source.sourceId
    },
    // 该日期是否已约
    dateHasBeen(item) {
      // console.log('已约判断:', this.activeApply, item)
      return this.activeApply.sourceId && this.activeApply.applyState + '' === '1' && this.activeApply.reservationDate === item.day
    },
    // 取消预约
    cancel() {
      console.log('取消预约的申请单', this.activeApply)
      this.$confirm(
        `是否取消 ${this.activeApply.itemName} 在 ${this.activeApply.reservationDate} ${this.activeApply.timeSlot} 的预约`,
        '申请单取消预约',
        {
          type: 'warning',
          customClass: 'reservationBox',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              const applyNum = this.activeApply.applyNum
              cancelReservation(this.activeApply).then(res => {
                if (res.code === 200) {
                  this.$message.success(`取消成功`)
                  done()
                  this.init(() => {
                    this.initRowClick(applyNum)
                  })
                } else {
                  done()
                  this.$message.error(`${res.msg}`)
                }
                //this.$refs.multipleTable.setCurrentRow(null)
                //this.activeApply = {}
                //this.multiApply = []
                //this.activeSource = {}
                // 刷新一下号源信息
                /*let temp = this.dateList.find(item => item.day === this.activeDate)
                if (temp) {
                  this.calendarClick(temp)
                }*/
              }).finally(_ => {
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }
      )
    },
    // 预约
    reservation() {
      console.log('预约的申请单', this.activeApply, this.activeSource)
      this.$confirm(
        `${this.activeApply.itemName} 是否预约到 ${this.activeSource.examDate} ${this.activeSource.timeSlot}`,
        '申请单预约',
        {
          type: 'info',
          customClass: 'reservationBox',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              const applyNum = this.activeApply.applyNum
              reservation({
                apply: this.activeApply,
                source: this.activeSource
              }).then(res => {
                if (res.code === 200) {
                  this.$message.success(`预约成功`)
                  done()
                  this.init(() => {
                    this.initRowClick(applyNum)
                  })
                } else {
                  done()
                  this.$message.error(`${res.msg}`)
                }
                //this.$refs.multipleTable.setCurrentRow(null)
                //this.activeSource = {}
                //this.activeApply = {}
                //this.multiApply = []
                // 刷新一下号源信息
                /*let temp = this.dateList.find(item => item.day === this.activeDate)
                if (temp) {
                  this.calendarClick(temp)
                }*/
              }).finally(_ => {
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }
      )
    },
    // 批量预约
    reservationBatch() {
      console.log('批量预约的申请单', this.multiApply)
    }
  },
  created() {
    const { applyNum, type } = StorageUtils.getWisLocal('applyNum').body
    this.applyNum = applyNum
    this.init(() => {
      this.initRowClick(applyNum)
    })
  }
}
</script>

<style lang="scss" scoped>
.card {
  ::v-deep .el-card__body {
    padding: 5px;
  }

  ::v-deep .el-card__header {
    padding: 5px 5px 5px 20px;
    display: flex;
    align-items: center;
  }
}

.patient-card-body {
  display: flex;
  flex-wrap: wrap;

  .patient-card-body-item {
    display: flex;
    align-items: center;
    height: 30px;
    margin-right: 20px;

    .patient-card-body-item-title {
      color: silver;
      margin-right: 10px;
      width: 80px;
      font-size: 14px;
      line-height: 1.3;
      justify-content: flex-end;
      display: flex;
      align-items: center;
    }

    .patient-card-body-item-content {
      color: #303133;
      font-size: 16px;
      line-height: 1.3;
      justify-content: flex-start;
      display: flex;
      align-items: center;
    }
  }
}

.body {
  margin-top: 10px;
  //display: flex;

  .body-left {
    //width: 800px;
    margin-right: 10px;

    ::v-deep .cell-active {
      color: #ffffff !important;
      background-color: #409eff !important;
    }

    ::v-deep .el-table__row {
      cursor: pointer;
    }
  }

  .calendar {
    display: flex;
    flex-wrap: wrap;

    .calendar-item {
      min-width: 110px;
      max-width: 200px;
      border: 1px #e6ebf5 solid;
      margin: 8px;
      padding: 5px;
      min-height: 80px;
      border-radius: 8px;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .calendar-item-source {
        display: flex;

        span {
          background-color: #00974f;
          border-radius: 50%;
          width: 21px;
          height: 21px;
          display: block;
          text-align: center;
          color: #ffffff;
          margin-right: 3px;
        }
      }

    }

    .active-item {
      background-color: #f2f8fe;
      color: #409eff;
    }

  }

  .source-list {
    .source-list-item {
      padding: 10px;
      display: flex;

      .item-left {
        width: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px;
        text-align: center;
      }

      .item-right {
        flex: 1;
        display: flex;
        flex-wrap: wrap;

        .source-item {
          width: 230px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          border: 1px #00964c solid;
          border-radius: 5px;
          margin: 5px;
          color: #00964c;
        }

        .source-item-active {
          background-color: #ecab00;
          color: #FFFFFF;
          border: none;
        }

        .source-item-disabled {
          cursor: not-allowed;
          background-color: #ededed;
          border: none;
          color: #7c7c7c;
        }
      }
    }
  }

}
</style>
