<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>
        <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 icon="el-icon-refresh" size="mini" @click="printApply">打印</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 align="center" type="selection" width="55"/>
      <!--            <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 AsyncUtils from '@/utils/AsyncUtils'
import { listExamtype } from '@/api/basis/examtype'

export default {
  name: 'NurseApplyStatic',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院区信息表格数据
      orgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否有效字典
      isValidOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        patientId: null,
        patientName: null,
        reservationTime: this.formatDate(new Date())
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      selects:null,
      Examtypes: []
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.isValidOptions = response.data;
    });
    listExamtype().then((response) => {
      this.Examtypes = response.rows
    })
  },
  methods: {
    isUrgentFormatter({ isUrgent }) {
      return isUrgent + '' === '0' ? '常规' : '加急'
    },
    stretcherFormatter({ stretcher }) {
      return stretcher + '' === '0' ? '' : '推床'
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /** 查询院区信息列表 */
    getList() {
      this.loading = true
      listNurseApply(this.queryParams).then(response => {
        this.orgList = response.rows
        this.total = response.total
        this.loading = false
      });
    },
    // 是否有效字典翻译
    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
      this.selects = selection
      console.log("selection",selection,this.ids,this.single,this.multiple)
    },
    /** 新增按钮操作 */
    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 === 2 || columnIndex === 1) {
        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')
    },
    // 打印功能
    printApply() {
      const rows = this.selects.filter(item => {
        return ['1'].includes(item.applyState + '')
      }).map(row => {
        console.log(row)
        return {
          examTypeName: this.examTypeFormat(row),
          remarks: row.remark,
          region: row['visitTypeCode'] === '1' ? row['applyDeptName'] : row['wardName'],
          visitNum: row.visitNum,
          patientName: row.patientName,
          reservationDate: row.reservationDate,
          timeFrame: row.timeFrame,
          timeSlot: row.reservationTimeSlot,
          examDeptName: row.examDeptName,
          itemName: row.outExamItemName,
          examAddress: row['examTypeId'] === '3' ? row['stretcher'] === '1' ? '德馨楼四楼' : '德馨楼三楼' : row.examAddress,
          isUrgent: row.isUrgent
        }
      })
      if (rows.length > 0) {
        AsyncUtils.print(rows)
      }
    },
    examTypeFormat(row) {
      return this.Examtypes.find(item => item.typeCode === row.examTypeId)?.typeName
    },
  }
};
</script>
