<template>
  <div>
    <!--组件主体-->
    <div :style="`height: ${tableHeight}px;font-size:14px;z-index:10;background-color: #f4f8ff;`">
      <div>
        <span>分诊房间：</span>
        <el-select v-model="LocalConfig.doctorCheck.queueRoom" placeholder="分诊房间" clearable filterable
          style="width: 125px" size="small">
          <el-option v-for="item in dict.room" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
      </div>
      <div>
        <el-cascader :options="dict.itemTypeTree" v-model="LocalConfig.doctorCheck.queueItemTypeIds"
          popper-class="example" style="width: 195px" :props="{
            checkStrictly: true, expandTrigger: 'hover', label: 'displayName', value: 'id',
            id: 'id', children: 'treeChildren', multiple: true
          }" clearable filterable size="small" collapse-tags>
        </el-cascader>
      </div>
      <!--
      <div>
        <span>候诊人员：</span>
        <el-input placeholder="候诊人员" v-model="patientName" size="small" style="width: 125px;" clearable />
      </div>
      -->
      <div style="display: flex;">
        <el-table :data="waitDetail" style="width: 100%;" border highlight-current-row @row-click="rowClickWait"
          :row-style="{ height: '28px' }" :height="Math.floor((tableHeight - 72) / 3)">
          <el-table-column prop="queueRegisterNumber" label="号" min-width="30" align="center" />
          <el-table-column prop="patientName" label="姓名" min-width="80" align="center" />
          <el-table-column prop="isVip" label="isVip" min-width="40" align="center">
            <template slot-scope="scope">
              <div style="font-family: 'Microsoft YaHei';">
                {{ scope.row.isVip == 'Y' ? '√' : '' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;">
          <div>
            <el-button type="primary" class="commonbutton" @click="btnCall(waitRow.queueRegisterId, '1')"
              style="width: 40px;min-width: 40px;height: 26px;">呼叫</el-button>
          </div>
          <div style="margin: 10px 0;">
            <el-button type="primary" class="commonbutton"
              @click="getQueueRegisterList(LocalConfig.doctorCheck.queueRoom, LocalConfig.doctorCheck.queueItemTypeIds)"
              style="width: 40px;min-width: 40px;height: 26px;">刷新</el-button>
          </div>
          <div>
            <el-button type="primary" class="commonbutton" @click="fnQueue"
              style="width: 40px;min-width: 40px;height: 26px;">排队</el-button>
          </div>
        </div>
      </div>
      <div style="margin-top: 6px;">已呼人员：</div>
      <div style="display: flex;">
        <el-table :data="alreadyCalledDetail" style="width: 100%;" border highlight-current-row
          @row-click="rowClickAlready" :row-style="{ height: '28px' }" :height="Math.floor((tableHeight - 72) / 3)">
          <el-table-column prop="queueRegisterNumber" label="号" min-width="30" align="center" />
          <el-table-column prop="patientName" label="姓名" min-width="80" align="center" />
          <el-table-column prop="isVip" label="isVip" min-width="40" align="center">
            <template slot-scope="scope">
              <div style="font-family: 'Microsoft YaHei';">
                {{ scope.row.isVip == 'Y' ? '√' : '' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;">
          <div>
            <el-button type="primary" class="commonbutton" @click="btnCall(alreadyRow, '2')"
              style="width: 40px;min-width: 40px;height: 26px;">过号</el-button>
          </div>
        </div>
      </div>
      <div style="margin-top: 6px;">过号人员：</div>
      <div style="display: flex;">
        <el-table :data="overNumberDetail" style="width: 100%;" border highlight-current-row @row-click="rowClickOver"
          :row-style="{ height: '28px' }" :height="Math.floor((tableHeight - 72) / 3)">
          <el-table-column prop="queueRegisterNumber" label="号" min-width="30" align="center" />
          <el-table-column prop="patientName" label="姓名" min-width="80" align="center" />
          <el-table-column prop="isVip" label="isVip" min-width="40" align="center">
            <template slot-scope="scope">
              <div style="font-family: 'Microsoft YaHei';">
                {{ scope.row.isVip == 'Y' ? '√' : '' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;">
          <div>
            <el-button type="primary" class="commonbutton" @click="btnCall(overRow, '9')"
              style="width: 40px;min-width: 40px;height: 26px;">重呼</el-button>
          </div>
          <div style="margin: 10px 0;">
            <el-button type="primary" class="commonbutton" @click="btnCall(overRow, '0')"
              style="width: 40px;min-width: 40px;height: 26px;">退回</el-button>
          </div>
        </div>
      </div>
    </div>

    <!--组件弹窗-->
    <div>
      <!-- 修改信息 -->
      <el-dialog title="分诊排队" :visible.sync="dialogWin.queue" width="800px" :append-to-body="true"
        :close-on-click-modal="false">
        <Queue :refParams="queueParams" />
      </el-dialog>
    </div>
  </div>

</template>
<script>
import { mapState } from 'vuex';
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { listOrderBy, setCheckStatusColor, deepCopy } from "../../utlis/proFunc"
import Queue from "../../components/queue/Queue.vue";

export default {
  components: {
    Queue
  },
  data() {
    return {
      queueParams: {},
      patientName: '',
      waitDetail: [],
      alreadyCalledDetail: [],
      overNumberDetail: [],


      waitRow: {},
      alreadyRow: {},
      overRow: {},

      LocalConfig: {
        doctorCheck: { // 医生诊台  
          isQueue: 'N',  //启用分诊排队
          queueRoom: '',  //默认分诊房间
          queueItemTypeIds: [], // 检查类别
          isBroadcast: 'N', // 是否广播
        }
      },
      LocalConfigInit: {},
      interval: null, // 定时器句柄
      queue_refresh_interval: 15, // 叫号刷新时间间隔(秒)

      queue_play_voice_repeate_times: 2,  // 语音重复播放次数
      queue_play_voice_repeate_interval: 1, // 语音重复播放时间间隔(秒)


    };
  },

  created() {

  },

  //挂载完成
  mounted() {
    this.fnMounted()
  },

  destroyed() {
    console.log('this.interval', JSON.stringify(this.interval))
    if (this.interval) clearInterval(this.interval)
    console.log('this.interval clearInterval', JSON.stringify(this.interval))
  },

  computed: {
    ...mapState(['window', 'dialogWin', 'dataTransOpts', 'dict', 'doctorCheck']),

    tableHeight() {
      return this.window.pageHeight < 600 ? 400 : this.window.pageHeight - 200
    },

  },

  methods: {
    setCheckStatusColor,

    tableRowClassName({ row, rowIndex }) {
      //console.log('tableRowClassName',rowIndex,row)
      if (row.completeFlag === '0') {
        return 'danger'; //未检
      } else if (row.completeFlag === '2') {
        return 'info'; //弃检
      }
      return '';

    },

    async fnMounted() {
      this.LocalConfigInit = deepCopy(this.LocalConfig)
      let LocalConfig = window.localStorage.getItem("LocalConfig") || null
      try {
        this.LocalConfig = Object.assign({}, deepCopy(this.LocalConfigInit), JSON.parse(LocalConfig) || {})
      } catch (error) {
        console.log('window.localStorage.getItem("LocalConfig")', error)
      }



      if (this.LocalConfig.doctorCheck.isQueue == 'Y') {

        this.dictInit().then(res => {
          if (!this.LocalConfig.doctorCheck.queueRoom) {
            if (res.data.length > 0) this.LocalConfig.doctorCheck.queueRoom = res.data[0].id
          }
          if (this.LocalConfig.doctorCheck.queueRoom) this.getQueueRegisterListByRoomId(this.LocalConfig.doctorCheck.queueRoom)
        })
        this.setQueueParams()

        try {
          let sysParam = await postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: "queue_refresh_interval" })
          this.queue_refresh_interval = Number(sysParam.data || 15)
        } catch (error) {
          console.log(error)
        }

        // 壳端
        if (this.$peisAPI) {

          postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: "queue_play_voice_repeate_times" })
            .then(res => {
              if (res.code > -1) this.queue_play_voice_repeate_times = Number(res.data || 2)
            })

          postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: "queue_play_voice_repeate_interval" })
            .then(res => {
              if (res.code > -1) this.queue_play_voice_repeate_interval = Number(res.data || 1)
            })
        }

        // 启动自动刷新
        if (!this.interval && this.queue_refresh_interval != 0) {
          this.interval = setInterval(() => {
            this.getQueueRegisterList(this.LocalConfig.doctorCheck.queueRoom, this.LocalConfig.doctorCheck.queueItemTypeIds)
          }, this.queue_refresh_interval * 1000);
        }
      }
    },

    btnCall(refRow, completeFlag) {
      let row = Object.assign({}, refRow)
      switch (completeFlag) {
        case "0": // 退回
          if (!row.queueRegisterId) {
            if (this.overNumberDetail.length > 0) row = this.overNumberDetail[0]
          }
          if (!row.queueRegisterId) this.$message.warning({ showClose: true, message: '未可操作的数据，或未选择过号人员' })
          break;
        case "1": // 呼叫
          if (!row.queueRegisterId) {
            if (this.waitDetail.length > 0) row = this.waitDetail[0]
          }
          if (!row.queueRegisterId) this.$message.warning({ showClose: true, message: '未可操作的数据，或未选择候诊人员' })
          break;
        case "2": // 过号
          if (!row.queueRegisterId) {
            if (this.alreadyCalledDetail.length > 0) row = this.alreadyCalledDetail[0]
          }
          if (!row.queueRegisterId) this.$message.warning({ showClose: true, message: '未可操作的数据，或未选择已呼人员' })
          break;
        case "9": // 重呼
          if (!row.queueRegisterId) {
            if (this.overNumberDetail.length > 0) queueRegisterId = this.overNumberDetail[0]
          }
          if (!row.queueRegisterId) this.$message.warning({ showClose: true, message: '未可操作的数据，或未选择过号人员' })
          break;
      }

      // "patientRegisterId": "3a143cf9-0b1b-7765-a90a-b087c4aad1b9",
      // "patientRegisterNo": "003485"
      // 叫号即调人员信息出来
      if (row.patientRegisterNo) {
        this.dataTransOpts.tableS.patient_register.patientRegisterNo = row.patientRegisterNo
        this.dataTransOpts.refresh.patient_register.S++
      }


      if (row.queueRegisterId && completeFlag != '9') {
        postapi('/api/app/QueueRegister/UpdateQueueRegisterStatus', { queueRegisterId: row.queueRegisterId, completeFlag })
          .then(res => {
            if (res.code > -1) {
              this.getQueueRegisterList(this.LocalConfig.doctorCheck.queueRoom, this.LocalConfig.doctorCheck.queueItemTypeIds)
              if (this.$peisAPI && completeFlag == '1') this.outShellCall(row)
            }
          })
      } else if (completeFlag == '9') {
        if (this.$peisAPI) this.outShellCall(row)
      }
    },

    // 调用壳呼叫 api
    outShellCall(row) {
      let roomName = ''
      postapi('/api/app/Room/Get', { roomId: this.LocalConfig.doctorCheck.queueRoom })
        .then(res => {
          if (res.code > -1) {
            roomName = res.data.displayName
            return this.$peisAPI.getIsSpeechEnable()
          }
        })
        .then(res => {
          if (res == 'Y') return this.$peisAPI.speechConnect()
        })
        .then(res => {
          // queue_play_voice_repeate_times: 2,  // 语音重复播放次数
          // queue_play_voice_repeate_interval: 1, // 语音重复播放时间间隔(秒)
          let toOutShell = { SendText: `请${row.patientName}到${roomName}检查`, RepatPlayNum: this.queue_play_voice_repeate_times, Delay: this.queue_play_voice_repeate_interval }
          return this.$peisAPI.speechSendText(JSON.stringify(toOutShell))
        })
        .catch(err => {
          // console.log('呼叫失败', err)
          this.$message.error({ showClose: true, message: err })
        })
    },

    dictInit() {
      return new Promise((resolve, reject) => {
        postapi('/api/app/Room/GetList')
          .then((res) => {
            if (res.code > -1) {
              this.dict.room = res.data
              // this.tableData = res.data.filter(e => {
              //   return medicalCenterId ? (e.medicalCenterId == medicalCenterId) : e
              // });
              resolve(res)
            } else {
              reject(res.message)
            }
          })
          .catch(err => {
            reject(err)
          });
      })
    },


    getQueueRegisterList(roomId, itemType) {
      return new Promise((resolve, reject) => {

        this.waitDetail = []
        this.alreadyCalledDetail = []
        this.overNumberDetail = []

        this.waitRow = {}
        this.alreadyRow = {}
        this.overRow = {}

        let itemTypeIds = []
        itemType.forEach(e => {
          e.forEach(item => {
            itemTypeIds.push(item)
          });
        });

        postapi('/api/app/QueueRegister/GetQueueRegisterListByRoomId', { roomId, itemTypeIds })
          .then(res => {
            if (res.code > -1) {
              this.waitDetail = res.data.waitDetail
              this.alreadyCalledDetail = res.data.alreadyCalledDetail
              this.overNumberDetail = res.data.overNumberDetail

              resolve(res)
            } else {
              reject(res.message)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 获取房间排队信息 ByRoomId
    getQueueRegisterListByRoomId(roomId) {

      if (!roomId) {
        this.$message.warning({ showClose: true, message: '请选择房间' })
        return
      }
      this.getQueueRegisterList(roomId, this.LocalConfig.doctorCheck.queueItemTypeIds)
    },

    // 获取房间排队信息 ByRoomId
    getQueueRegisterListByItemTypeIds(itemTypeIds) {
      this.getQueueRegisterList(this.LocalConfig.doctorCheck.queueRoom, itemTypeIds)
    },

    setQueueParams() {
      this.queueParams.patientRegisterId = this.dataTransOpts.tableS.patient_register.id
    },

    // 分诊排队
    fnQueue() {
      if (!this.queueParams.patientRegisterId) {
        this.$message.warning({ showClose: true, message: '未获取到人员信息' })
        return
      }

      this.queueParams = {
        patientRegisterId: this.queueParams.patientRegisterId
      }
      this.dataTransOpts.plus.queue++
      this.dialogWin.queue = true
    },

    // 选择候诊人员
    rowClickWait(row) {
      this.waitRow = row
    },

    // 选择过号人员
    rowClickAlready(row) {
      this.alreadyRow = row
    },

    // 选择过号人员
    rowClickOver(row) {
      this.overRow = row
    },

  },


  //监听事件
  watch: {
    //体检人员未切换时 也可以强制刷新数据
    "dataTransOpts.refresh.register_check.M": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 组合项目列表 newVal: ${newVal} oldVal: ${oldVal} patient_register.id: ${this.dataTransOpts.tableS.patient_register.id}`);
        if (newVal != oldVal) {
          this.fnMounted()
        }
      }
    },
  }
};
</script>
<style scoped>
::v-deep .el-collapse-item__header {
  height: 32px;
  line-height: 32px;
  background-color: #f4f8ff;
  color: #303133;
  cursor: pointer;
  font-size: 14px;
  font-weight: 700;
  text-align: center;
  padding: 0 0 0 50px;
}
</style>