<template>
  <div class="app-container pageSediment">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="队列名称" prop="queueId">
        <el-select
          v-model="queryParams.queueId"
          clearable
          placeholder="请选择队列"
        >
          <!--          <el-option
                      :key="0"
                      :label="'全部'"
                      :value="''"
                    />-->
          <el-option
            v-for="item in queueList"
            :key="item.id"
            :label="item.queueName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检查日期" prop="examDate">
        <el-date-picker
          v-model="queryParams.examDate"
          :clearable="false"
          placeholder="选择日期"
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          @change="handleQuery"
          @keyup.enter.native="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!--        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="addSource('am')">上午加号
                </el-button>
                <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="addSource('pm')">下午加号
                </el-button>-->
        <el-button
          :disabled="!ids.length>0"
          icon="el-icon-remove"
          size="mini"
          type="warning"
          @click="selectApplyByStop(ids.join(','))"
        >
          停诊
        </el-button>
        <el-button :disabled="!enable" icon="el-icon-edit-outline" size="mini" type="primary"
                   @click="editSource"
        >加/减号
        </el-button>
        <el-dialog v-dialogDrag :center="true" :destroy-on-close="true"
                   :visible.sync="sourceEditVisible"
                   title="号源修改" width="500px"
        >
          <el-alert
            effect="dark"
            style="margin-bottom: 15px;margin-left: 50px;width: 80%"
            title="请输入加/减号的数量,减号为负数"
            type="success"
          >
          </el-alert>
          <div class="formContainer">
            <el-form ref="sourceEditForm" :model="sourceEditForm" :rules="sourceEditRules">
              <el-form-item label="门诊" prop="outSource">
                <el-input-number v-model="sourceEditForm.outSource" :min="sourceEditFormConfig.outSource.min"
                                 :precision="0"
                />
              </el-form-item>
              <el-form-item label="住院" prop="inSource">
                <el-input-number v-model="sourceEditForm.inSource" :min="sourceEditFormConfig.inSource.min"
                                 :precision="0"
                />
              </el-form-item>
              <el-form-item label="体检" prop="phySource">
                <el-input-number v-model="sourceEditForm.phySource" :min="sourceEditFormConfig.phySource.min"
                                 :precision="0"
                />
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer">
            <el-button @click="sourceEditVisible = false">取 消</el-button>
            <el-button type="primary" @click="editSourceConfirm">确 定</el-button>
          </div>
        </el-dialog>
      </el-form-item>
    </el-form>


    <el-table ref="multipleTable" v-loading="loading"
              :cell-class-name="cellClassName"
              :cell-style="cellStyle"
              :data="sourcePoolList"
              :span-method="mergeRows"
              border stripe tooltip-effect="light" @cell-click="tabClick" @row-click="handleRowClick"
              @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" fixed="left" label="午段" prop="timeFrame" show-overflow-tooltip width="80"/>
      <el-table-column :selectable="selectable" align="center" fixed="left" show-overflow-tooltip type="selection"
                       width="55"
      />
      <el-table-column align="center" fixed="left" label="时间段" prop="timeSlot" show-overflow-tooltip width="130"/>
      <el-table-column align="center" fixed="left" label="号源数量" prop="singleSourceCount" show-overflow-tooltip
                       width="80"
      />
      <!--      <el-table-column label="加/减号数量" align="center" prop="addSourceCount"/>-->
      <el-table-column align="center" label="门诊加号" min-width="80" prop="outAddSourceCount"/>
      <el-table-column align="center" label="住院加号" min-width="80" prop="inAddSourceCount"/>
      <el-table-column align="center" label="体检加号" min-width="80" prop="phyAddSourceCount"/>
      <el-table-column
        align="center"
        label="门诊号源数量"
        min-width="80"
        prop="outNumSourceCount"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.index === 'xxxxx'">
<!--       <span v-if="scope.row.index === tabClicked.row && scope.column.index === tabClicked.column">-->
              <el-input v-model="scope.row.outNumSourceCount"
                        :autofocus="mark"
                        maxlength="200"
                        placeholder="请输入号源数量"
                        size="mini" @blur="inputBlur(scope.row,scope.column)"
              />
        </span>
          <span v-else>{{ scope.row.outNumSourceCount }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="住院号源数量"
        min-width="80"
        prop="inNumSourceCount"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.index === 'xxxxx'">
<!--            <span v-if="scope.row.index === tabClicked.row && scope.column.index === tabClicked.column">-->
                    <el-input v-model="scope.row.inNumSourceCount"
                              :autofocus="mark"
                              maxlength="200"
                              placeholder="请输入号源数量"
                              size="mini" @blur="inputBlur(scope.row,scope.column)"
                    />
              </span>
          <span v-else>{{ scope.row.inNumSourceCount }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="体检号源数量"
        min-width="80"
        prop="phyNumSourceCount"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.index === 'xxxxx'">
<!--                <span v-if="scope.row.index === tabClicked.row && scope.column.index === tabClicked.column">-->
                        <el-input v-model="scope.row.phyNumSourceCount"
                                  :autofocus="mark"
                                  maxlength="200"
                                  placeholder="请输入号源数量"
                                  size="mini" @blur="inputBlur(scope.row,scope.column)"
                        />
                  </span>
          <span v-else>{{ scope.row.phyNumSourceCount }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="门诊已预约" min-width="80" prop="outSourceCount"/>
      <el-table-column align="center" label="住院已预约" min-width="80" prop="inSourceCount"/>
      <el-table-column align="center" label="体检已预约" min-width="80" prop="phySourceCount"/>
      <el-table-column align="center" label="停诊状态" prop="sourceStatus" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sourceStatus === 1" type="success">正常</el-tag>
          <el-tag v-else type="info">停诊</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-dialogDrag :visible.sync="dialogTableVisible" title="请确认将要取消的申请单信息">
      <el-table ref="multipleTable2" :data="applyList" border class=""
                height="400px" max-height="400" stripe tooltip-effect="light"
      >
        <el-table-column fixed="left" label="姓名" min-width="100" property="patientName" show-overflow-tooltip/>
        <el-table-column fixed="left" label="检查项目名称" min-width="150" property="itemName" show-overflow-tooltip/>
        <el-table-column fixed="left" label="申请科室名" min-width="120" property="applyDeptName" show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="申请医生名" min-width="100" property="applyDoctorName" show-overflow-tooltip
        ></el-table-column>
        <el-table-column :formatter="genderState" align="center" label="性别" property="gender" width="80"
        ></el-table-column>
        <el-table-column align="center" label="年龄" property="age" width="80"></el-table-column>
        <el-table-column label="电话" min-width="100" property="phone" show-overflow-tooltip></el-table-column>
        <el-table-column :formatter="applyState" label="可否取消" property="applyState" width="80"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stopReservation">确 定</el-button>
        <el-button
          icon="el-icon-download"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
        <el-button type="danger" @click="cancelApplyList">取 消</el-button>

      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  updateSourcePool,
  listSourcePoolToManage,
  listSourcePool,
  getSourcePool,
  delSourcePool,
  addSourceNum,
  lessSourceNum,
  exportSourcePool, editSourcePool
} from '@/api/resource/sourcePool'
import { listExamtype } from '@/api/basis/examtype'
import { listQueue } from '@/api/resource/queue'
import { exportApplyByStop, selectApplysByStop, stopReservation } from '@/api/resource/apply'
import { exportApplyAction } from '@/api/resource/applyAction'

export default {
  name: 'SourcePool',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      tabClickIndex: null, // 点击的单元格
      tabClickLabel: '', // 当前点击的列名
      // 当前点击数据,行列旧值
      tabClicked: {
        row: null,
        column: null,
        oldValue: null
      },
      // 加减号源编辑框
      sourceEditVisible: false,
      sourceEditForm: {
        id: null,
        inSource: 0,
        outSource: 0,
        phySource: 0
      },
      sourceEditRules: {
        inSource: [{ required: true, message: '不能为空', trigger: 'blur' }],
        outSource: [{ required: true, message: '不能为空', trigger: 'blur' }],
        phySource: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      sourceEditFormConfig: {
        inSource: { min: 0 },
        outSource: { min: 0 },
        phySource: { min: 0 }
      },
      primaryVal: 0,
      mark: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //检查类型下拉
      examTypeOption: [],
      //队列
      queueList: [],
      // 总条数
      total: 0,
      // 号源池表格数据
      sourcePoolList: [],
      applyInfoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否使用字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        queueId: null,
        examDate: null,
        examTypeId: null

      },
      dialogTableVisible: false,
      applyList: [],
      applyids: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    // 时间转换
    var datejson = new Date().toJSON()
    var date = new Date(+new Date(datejson)
      + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    this.queryParams.examDate = date.substring(0, 10)
    listExamtype().then(response => {
      this.examTypeOption = response.rows
      //this.queryParams.examTypeId = response.rows[0].typeCode;
      this.getQueueList()
    })

    this.getDicts('sys_yes_no').then(response => {
      this.statusOptions = response.data
    })
  },
  computed: {
    // 时候允许操作,理论上说今天之前的都不允许操作了
    enable() {
      if (!this.single && this.queryParams.examDate) {
        return new Date(`${this.queryParams.examDate} 00:00:00`) >= new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      }
      return false
    }
  },
  methods: {
    handleRowClick(row, column, event) {
      if (row.sourceStatus === 1) {
        this.$refs.multipleTable.toggleRowSelection(row)
      }
    },
    // 表格行列合并
    mergeRows({ row, column, rowIndex, columnIndex }) {
      let rowspan = 0
      let colspan = 0
      // 上下午午段合并
      if (columnIndex === 0) {
        colspan = 1
        // 计算当前行的午段数据是不是列表中第一个,当前行索引=0 或者当前行的timeFrame值不等于上一行
        if (rowIndex === 0 || row.timeFrame !== this.sourcePoolList[rowIndex - 1].timeFrame) {
          // 计算需要合并的数量
          rowspan = this.sourcePoolList.filter(item => item.timeFrame === row.timeFrame).length
        }
        return { rowspan, colspan }
      }
    },
    // 单元格上下午样式
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (row.timeFrame === '上午') {
          return { backgroundColor: '#67C23A', fontWeight: 600, fontSize: 'large', color: '#ffffff' }
        } else {
          return { backgroundColor: '#E6A23C', fontWeight: 600, fontSize: 'large', color: '#ffffff' }
        }
      }
    },
    // 禁止勾选已经停诊的号源
    selectable(row, index) {
      return row.sourceStatus == 1
    },
    // 加减号
    editSource() {
      let row = this.sourcePoolList.find(item => item.id === this.ids[0])
      this.sourceEditVisible = true
      this.sourceEditForm = {
        inSource: row.inAddSourceCount,
        outSource: row.outAddSourceCount,
        phySource: row.phyAddSourceCount,
        id: row.id
      }
      this.sourceEditFormConfig = {
        inSource: { min: parseInt(row.inSourceCount - row.inNumSourceCount + '') },
        outSource: { min: parseInt(row.outSourceCount - row.outNumSourceCount + '') },
        phySource: { min: parseInt(row.phySourceCount - row.phyNumSourceCount + '') }
      }
    },
    editSourceConfirm() {
      this.$refs['sourceEditForm'].validate((valid) => {
        if (valid) {
          if (this.sourceEditForm.id) {
            editSourcePool({
              id: this.sourceEditForm.id,
              inAddSourceCount: this.sourceEditForm.inSource,
              outAddSourceCount: this.sourceEditForm.outSource,
              phyAddSourceCount: this.sourceEditForm.phySource
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('修改成功')
                this.sourceEditVisible = false
                this.getList()
              }
            })
          } else {
            this.sourceEditVisible = false
          }
        }
      })
    },
    // 停诊/批量停诊
    stopReservation(ids) {
      const _this = this
      console.log(this.applyids)
      ids = this.applyids
      this.$confirm(`确认是否停诊?`, '停诊', {
        beforeClose: function(action, instance, done) {
          if (action === 'confirm') {
            stopReservation(ids).then(res => {
              if (res.code === 200) {
                this.$message.success('停诊成功')
                _this.getList()
                _this.ids = []
              }
            }).finally(_ => {
              done()
            })
          } else {
            done()
          }
        }
      })
      this.dialogTableVisible = false
    },
    selectApplyByStop(ids) {
      this.dialogTableVisible = true
      console.log(ids)
      this.applyids = ids
      selectApplysByStop(ids).then(res => {
        console.log(res)
        this.applyList = res.data
      })
    },
    applyState(row, column) {
      if (row.applyState === 1) {
        return '可取消'
      } else {
        return '不可取消'
      }
    },
    genderState(row, column) {
      console.log(row.gender)
      if (row.gender === '1') {
        return '男'
      } else if (row.gender === '2') {
        return '女'
      } else {
        return '未知'
      }
    },
    /** 查询号源池列表 */
    getList() {
      this.loading = true
      listSourcePoolToManage(this.queryParams).then(response => {
        this.sourcePoolList = response.rows.sort((x, y) => {
          return new Date(`2022-01-01 ${x.timeSlot.split('-')[0]}`).getTime() - new Date(`2022-01-01 ${y.timeSlot.split('-')[0]}`).getTime()
        })
        this.total = response.total
        this.loading = false
        this.tabClickIndex = null
        this.tabClickLabel = ''
      }).finally(_ => {
        this.loading = false
      })
    },
    getQueueList() {
      this.loading = true
      listQueue().then(response => {
        this.queueList = response.rows
        this.queryParams.queueId = response.rows[0].id
        this.$nextTick(() => {
          this.getList()
        })
      })
    },
    // 是否使用字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    examTypeNameFormat(row, column) {
      let name = ''
      this.examTypeOption.forEach(i => {
        if (row.examTypeId == i.typeCode) {
          name = i.typeName
        }
      })
      return name
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelApplyList() {
      this.applyids = ''
      this.dialogTableVisible = false
      this.applyList = []
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        queueId: null,
        examDate: null,
        timeSlot: null,
        weekName: null,
        timeFrame: null,
        status: 0,
        reservationSerialNum: null,
        examTypeId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const id = this.ids
      console.log(id)
      this.$confirm(
        '增加号源？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          addSourceNum(id).then(res => {
            return res.date
          })
        })
        .then(() => {
          this.getList()
          this.msgSuccess(text + '成功')
        })
        .catch(function() {

        })
    },
    /** 减号按钮操作 */
    handleLess() {
      const id = this.ids
      console.log(id)
      this.$confirm(
        '减少一个号源？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          lessSourceNum(id).then(res => {
            return res.date
          })
        })
        .then(() => {
          this.getList()
          this.msgSuccess(text + '成功')
        })
        .catch(function() {

        })
    },
    // 给行列加索引
    cellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
    },
    /**
     * 添加明细原因 row 当前行 column 当前列
     */
    tabClick(row, column, cell, event) {
      this.mask = true
      this.tabClicked = {
        row: row.index,
        column: column.index,
        oldValue: row[column.property]
      }
    },
    /**
     * 失去焦点初始化
     */
    inputBlur(row, column) {
      // 判断有无修改数据
      if (row[column.property] !== this.tabClicked.oldValue) {
        // 修改了数据需要进行更新
        // 判断数据准确性
        if (!(/(^[1-9]\d*$)/.test(row[column.property]))) {
          row[column.property] = parseInt(this.tabClicked.oldValue)
        } else {
          let sourceCount = parseInt(row.phyNumSourceCount) + parseInt(row.inNumSourceCount) + parseInt(row.outNumSourceCount)
          updateSourcePool({
            id: row.id,
            sourceCount,
            [column.property]: row[column.property]
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('修改成功')
              row.singleSourceCount = sourceCount
            }
          }).finally(() => {
            this.tabClicked = {
              column: null,
              row: null,
              oldValue: null
            }
          })
        }
      } else {
        if (!(/(^[1-9]\d*$)/.test(row[column.property]))) {
          row[column.property] = parseInt(this.tabClicked.oldValue)
        }
        this.tabClicked = {
          column: null,
          row: null,
          oldValue: null
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const applyids = this.applyids
      this.$confirm('是否确认导出所有预约操作记录数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportApplyByStop(applyids)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.formContainer {
  display: flex;
  justify-content: center;
  align-items: center;

  ::v-deep .el-form {
    width: 300px;
  }
}

.app-container {
  ::v-deep .el-dialog {
    box-shadow: none;
  }

  ::v-deep .el-dialog__body {
    padding: 0 10px 0;
  }
}
</style>
