<template>
  <div class="app-container pageSediment">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="90px">
      <el-form-item label="住院/门诊号" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          clearable
          placeholder="请输入住院/门诊号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          clearable
          placeholder="请输入患者姓名"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约日期" prop="date">
        <el-date-picker v-model="queryParams.reservationTime" clearable
                        placeholder="选择预约时间"
                        size="small"
                        type="date"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="病区" prop="wardCode">
        <el-select v-model="queryParams.wardId" :disabled="wardDisabled" filterable placeholder="请选择病区">
          <el-option
            v-for="item in wardList"
            :key="item.wardCode"
            :label="item['wardName']"
            :value="item.wardCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="cyan" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          v-hasPermi="['system:org:export']"
          icon="el-icon-download"
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
        <el-button
          v-if="false"
          icon="el-icon-download"
          size="mini"
          type="primary"
          @click="handlePrint"
        >打印
        </el-button>
      </el-form-item>
    </el-form>

    <el-table ref="multipleTable" v-loading="loading" :data="orgList"
              :span-method="objectSpanMethod" border stripe tooltip-effect="light" @selection-change="handleSelectionChange"
              @row-click="handleRowClick"
    >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column align="left" label="床位号" min-width="60" prop="badNumber" show-overflow-tooltip/>
      <el-table-column align="left" label="姓名" min-width="80" prop="patientName" show-overflow-tooltip/>
      <el-table-column align="left" label="病区" min-width="200" prop="wardName" show-overflow-tooltip/>
      <el-table-column align="left" label="预约时间" min-width="150" prop="reservationDate" show-overflow-tooltip/>
      <el-table-column align="left" label="检查项目" prop="outExamItemName" show-overflow-tooltip width="500"/>
      <el-table-column align="left" label="预约时段" min-width="150" prop="reservationTimeSlot" show-overflow-tooltip/>
      <el-table-column :formatter="isUrgentFormatter" align="center" label="是否加急" prop="isUrgent" width="80"/>
      <el-table-column :formatter="stretcherFormatter" align="center" label="是否推床" prop="stretcher" width="80"/>
      <el-table-column align="left" label="注意事项" prop="remark" show-overflow-tooltip width="500"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:org:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:org:remove']"
                >删除</el-button>
              </template>
            </el-table-column>-->
    </el-table>

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

  </div>
</template>

<script>
import { listOrg, getOrg, delOrg, addOrg, updateOrg, exportOrg } from "@/api/system/org";
import { listNurseApply, listNurseApplyExport } from '@/api/resource/nurseApplyStatic'
import moment from 'moment'
import { getWardList } from '@/api/reservation'
import { downloadExcelToPrint } from '@/utils/request'

export default {
  name: 'NurseResourceDetails',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院区信息表格数据
      orgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否有效字典
      isValidOptions: [],
      wardList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        patientId: null,
        patientName: null,
        wardId: null,
        reservationTime: this.formatDate(new Date())
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      wardDisabled: false
    };
  },
  created() {
    this.getList();
    this.getBq();
    this.getDicts("sys_yes_no").then(response => {
      this.isValidOptions = response.data;
    });
  },
  methods: {
    handlePrint() {
      listNurseApplyExport(this.queryParams)
        .then(res => {
          downloadExcelToPrint(res.msg)
        })
    },
    isUrgentFormatter({ isUrgent }) {
      return isUrgent + '' === '0' ? '常规' : '加急'
    },
    stretcherFormatter({ stretcher }) {
      return stretcher + '' === '0' ? '' : '推床'
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /** 查询院区信息列表 */
    async getList() {
      this.loading = true

      listNurseApply(this.queryParams).then(response => {
        this.orgList = response.rows
        this.total = response.total
        this.loading = false;
      });

    },
    async getBq(){
      const data =  await getWardList()
      this.wardList = data.data
      this.queryParams.wardId = this.wardList[0].wardCode
      try {
        // 判断当前用户是否可以切换病区
        const user = this.$store.getters.loginUser.user
        // 住院医生与护士需要固定病区
        if (user.roles.findIndex(item => ['indoctor', 'nurse'].includes(item.roleKey)) !== -1) {
          this.wardDisabled = false
          this.queryParams.wardCode = user.deptId
        }
      } catch (e) {

      }
    },
    // 是否有效字典翻译
    isValidFormat(row, column) {
      if("1" == row.isValid+""){
        return "是";
      }else{
        return "否";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgCode: null,
        orgName: null,
        isValid: null,
        address: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加院区信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrg(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改院区信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrg(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrg(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除院区信息编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delOrg(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有院区信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return listNurseApplyExport(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const array = this.formatRowspanAndColspan(this.orgList, 'patientId')
      if (columnIndex === 1 || columnIndex === 0) {
        const num = array[rowIndex].num
        if (num > 1) {
          return {
            rowspan: num,
            colspan: 1
          }
        } else if (num < 1) {
          return {
            rowspan: 1,
            colspan: num
          };
        }else {
          return {
            rowspan: 1,
            colspan: 1
          }
        }
      }
    },
    formatRowspanAndColspan(tableData, tableKey) {
      const newArr = []
      // 分类检出tempList中的数据push到newArr中
      for (let i = 0; i < tableData.length;) {
        let count = 0
        for (let j = i; j < tableData.length; j++) {
          if (tableKey === 'patientId') {
            if (tableData[i].patientId === tableData[j].patientId) {
              count++
            }
          }
        }
        if (tableKey === 'patientId') {
          newArr.push({
            data: tableData[i].patientId,
            num: count
          })
        }
        i += count
      }
      // 根据此算法，格式化newArr中的数据
      for (let k = 0; k < newArr.length; k++) {
        if (newArr[k].num > 1 || newArr[k].num === 0) {
          for (let w = k; w < newArr[k].num + k - 1; w++) {
            newArr.splice(w + 1, 0, {
              data: newArr[k].data,
              num: 0
            })
          }
        }
      }
      return newArr
    },
    formatDate(time) {
      return moment(time).format('YYYY-MM-DD')
    }
  }
};
</script>
