<template>
  <div>
    <crumbs :title="title + hospitaiName" linkTo="MedicalTermCDSS" style="min-width: 1096px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="text" class="downTemplate" @click="exportModule">导入模板下载</el-button>
          <input
            type="file"
            name="uploadfile "
            id="upFile"
            @change="uploadFile($event)"
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          />
          <el-button size="mini" @click="importPage">{{uploadInfo}}</el-button>
          <el-button size="mini" @click="exportData">导出</el-button>
        </el-form-item>
        <el-form-item label="医院科室名称：">
          <el-input size="mini" v-model="filter.hisName" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="标准科室名称：">
          <el-input size="mini" v-model="filter.uniqueName" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item class="dododo">
          <el-button size="mini" @click="filterDatas">检索</el-button>
          <el-button size="mini" type="warning" @click="addRelation">添加关联</el-button>
        </el-form-item>
      </el-form>
    </crumbs>
    <div class="contents">
      <el-table :data="list" border style="width: 100%">
        <el-table-column :resizable="false" type="index" :index="indexMethod" label="编号" width="80"></el-table-column>
        <el-table-column :resizable="false" prop="gmtModified" label="操作时间" width="180"></el-table-column>
        <el-table-column :resizable="false" prop="hisCode" label="医院科室编码" show-overflow-tooltip></el-table-column>
        <el-table-column :resizable="false" prop="hisName" label="医院科室名称" show-overflow-tooltip></el-table-column>
        <el-table-column :resizable="false" prop="uniqueName" label="标准科室名称" show-overflow-tooltip></el-table-column>
        <el-table-column :resizable="false" prop="operate" label="操作">
          <template slot-scope="scope">
            <el-button @click="modifyRelation(scope.row)" type="text" size="small">修改</el-button>
            <span style="margin:0 3px;">|</span>
            <el-button
              @click="showDelDialog(scope.row.id)"
              class="delete"
              type="text"
              size="small"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination pagepage">
        <el-pagination
          :current-page.sync="currentPage"
          @current-change="currentChange"
          background
          :page-size="pageSize"
          :page-sizes="pageSizeArr"
          @size-change="handleSizeChange"
          :layout="pageLayout"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@api/cdss.js';
import config from '@api/config.js';
import utils from '@api/utils.js';

export default {
  name: 'DeptManage',
  data: function() {
    return {
      list: [],
      searched: false,
      filter: {
        hisName: '', // 医院诊断名称
        uniqueName: '' //标准诊断名称
      },
      currentPage: 1,
      pageSize: config.pageSize,
      pageSizeArr: config.pageSizeArr,
      pageLayout: config.pageLayout,
      total: 0,
      fileName: '',
      formData: {},
      headers: {},
      uploadInfo: '导入',
      title: '科室关联维护 | ',
      hospitaiName: '',
      hospitalId: ''
    };
  },
  created() {
    const { data } = this.$route.params;
    this.hospitaiName = (data && data.name) || '';
    this.hospitalId = data && data.hospitalId;
    const that = this;
    //返回时避免参数未赋值就获取列表
    setTimeout(function() {
      that.getDataList();
    });
    // 非首页 编辑页返回 设置 this.currentPage
    if (Object.keys(this.$route.params).length !== 0) {
      this.currentPage = this.$route.params.currentPage;
    }
  },
  watch: {
    filter: {
      handler: function() {
        this.searched = false;
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //const pm = to.param;
      Object.assign(vm, to.params);
      vm.inCurrentPage = to.params.currentPage;
    });
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = utils.getCurrentPage(
        this.currentPage,
        this.total,
        this.pageSize
      );
      this.getDataList();
    },

    // 获取列表数据
    getDataList(isTurnPage) {
      const params = this.getFilterItems(isTurnPage);
      this.searched = true;
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      api.getDeptPage(params).then(res => {
        loading.close();
        if (res.data.code === '0') {
          this.list = res.data.data && res.data.data.records;
        }
        this.total = res.data.data && res.data.data.total;
        if (this.inCurrentPage !== undefined) {
          this.currentPage = this.inCurrentPage;
          this.inCurrentPage = undefined;
        }
      });
    },

    // 处理列表请求数据参数
    getFilterItems(isTurnPage) {
      const { data } = this.$route.params;
      //翻页时筛选条件没点确定则清空
      if (isTurnPage && !this.searched) {
        this.clearFilter();
      }
      const param = {
        current: this.inCurrentPage || this.currentPage,
        size: this.pageSize,
        hisName: this.filter.hisName.trim(),
        uniqueName: this.filter.uniqueName.trim(),
        uniqueCode: '',
        hospitalId: data && data.hospitalId
      };
      return param;
    },

    filterDatas() {
      this.currentPage = 1;
      this.getDataList();
    },
    addRelation() {
      const pam = this.searched
        ? {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            filter: this.filter
          }
        : { currentPage: this.currentPage, pageSize: this.pageSize };
      this.$router.push({
        name: 'AddDept',
        params: Object.assign(pam, {
          isEdit: false,
          data: { hospitalId: this.hospitalId },
          hospitaiName: this.hospitaiName
        })
      });
    },
    // 修改诊断关联-跳转至编辑页面
    modifyRelation(row) {
      const item = Object.assign({}, row);
      const pam = this.searched
        ? {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            filter: this.filter
          }
        : { currentPage: this.currentPage, pageSize: this.pageSize };
      this.$router.push({
        name: 'AddDept',
        params: Object.assign(pam, {
          isEdit: true,
          data: {...item, hospitalId: this.hospitalId},
          hospitaiName: this.hospitaiName
        })
      });
    },
    currentChange(next) {
      this.currentPage = next;
      this.getDataList(true);
      // if (this.cacheData[next]) {       //如果已请求过该页数据，则使用缓存不重复请求
      //     this.list = this.cacheData[next];
      // } else {
      //     this.getDataList();
      // }
    },
    // 清空搜索参数
    clearFilter() {
      this.filter = {
        hisName: '',
        uniqueName: ''
      };
    },

    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    getTagType(val) {
      return val;
    },
    warning(msg, type) {
      this.$message({
        showClose: true,
        message: msg,
        type: type || 'warning'
      });
    },
    showConfirmDialog(msg, resolve) {
      this.$alert(msg, '提示', {
        confirmButtonText: '删除',
        // cancelButtonText: '取消',
        // cancelButtonClass: 'cancelBtn',
        // confirmButtonClass: 'confirmC',
        type: 'warning'
      })
        .then(() => {
          resolve();
        })
        .catch(() => {});
    },
    // 删除关联
    showDelDialog(id) {
      this.showConfirmDialog('是否删除该关联？', () => {
        api
          .deleteDeptRecord({ id: id })
          .then(res => {
            if (res.data.code == '0') {
              if (!this.searched) {
                //未点确认时清空搜索条件
                this.clearFilter();
              }
              if (this.list.length == 1) {
                //当前在最后一页且只有一条数据时，删除后跳到前一页
                this.currentPage =
                  this.currentPage === 1 ? 1 : this.currentPage - 1;
              }
              this.getDataList();
              this.warning(res.data.msg || '操作成功', 'success');
            } else {
              this.warning(res.data.msg);
            }
          })
          .catch(error => {
            if (error.code === '900010001') {
              return false;
            }
            this.warning(error);
          });
      });
    },

    // 导出数据
    exportData() {
      this.$alert('确定要导出全部科室关联数据吗？', '', {
        confirmButtonText: '确定',
        // cancelButtonText: '取消',
        // cancelButtonClass: 'leftbtn',
        // customClass: 'exportBox6',
        title: '提示',
        type: 'warning'
        // beforeClose: (action, instance, done) => {
        //   if (action === 'confirm') {
        //     // instance.confirmButtonLoading = true;
        //     // instance.confirmButtonText = '导出中...';
        //     done()
        //     api.exportDeptRecord().then(res => {
        //       if (res.status === 200) {
        //         setTimeout(() => {
        //           utils.downloadExportedData(res.data, '科室关联数据.xls');
        //           // done();
        //         }, 1500);
        //       }
        //     });
        //   } else {
        //     done();
        //   }
        // }
      })
        .then(() => {
          api.exportDeptRecord({ hospitalId: this.hospitalId }).then(res => {
            if (res.status === 200) {
              this.$message({ message: '导出成功', type: 'success' });
              utils.downloadExportedData(res.data, '科室关联数据.xls');
            }
          });
        })
        .catch(() => {});
    },

    // 导入模板
    exportModule() {
      api.exportDeptModule().then(res => {
        if (res.status === 200) {
          setTimeout(() => {
            utils.downloadExportedData(res.data, '科室导入模板.xls');
          }, 1500);
        }
      });
    },

    // 点击导入
    importPage() {
      let inp = document.getElementById('upFile');
      inp.click();
    },
    // 导入数据
    uploadFile(e) {
      let fileInfo = e.target.files[0];
      // this.fileName = e.target.files[0].name; // 表单同步显示
      e.preventDefault();
      let formData = new FormData();
      formData.append('file', fileInfo);
      formData.append('hospitalId', this.hospitalId);
      const header = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };
      this.uploadInfo = '导入中...';
      api.importDeptRecord(formData, header).then(res => {
        // console.log('导入文件结果', '===================', res);
        if (res.data.code === '00000001') {
          this.$alert(`数据存在异常，导入失败，请修改后再试`, '提示', {
            confirmButtonText: '确定',
            // cancelButtonText: '取消',
            // cancelButtonClass: 'cancelSure',
            // confirmButtonClass: 'sure',
            // customClass: 'exportConfirm',
            type: 'warning'
          })
            .then(() => {})
            .catch(() => {});
          this.getDataList(); // 重新获取列表
          setTimeout(() => {
            this.uploadInfo = '导入';
          }, 300);
        } else if (res.data === '' && res.status === 200) {
          this.$alert(`导入成功`, '提示', {
            confirmButtonText: '确定',
            // cancelButtonText: '取消',
            // cancelButtonClass: 'cancelSure',
            // confirmButtonClass: 'sure',
            // customClass: 'exportConfirm',
            type: 'warning'
          })
            .then(() => {})
            .catch(() => {});
          this.getDataList(); // 重新获取列表
          setTimeout(() => {
            this.uploadInfo = '导入';
          }, 300);
        } else {
          this.$alert(`${res.data.msg}`, '提示', {
            confirmButtonText: '确定',
            // cancelButtonText: '取消',
            // cancelButtonClass: 'cancelSure',
            // confirmButtonClass: 'sure',
            // customClass: 'exportConfirm',
            type: 'warning'
          })
            .then(() => {})
            .catch(() => {});

          setTimeout(() => {
            this.uploadInfo = '导入';
          }, 300);
        }
      });
      //解决上传相同文件不触发change
      let inp = document.getElementById('upFile');
      inp.value = '';
    }
  }
};
</script>


<style lang="less" scoped>
@import '../../../less/admin.less';
.delete {
  color: red;
}
.delete:hover {
  color: red;
}
.pagination {
  min-width: 1010px;
}
.downTemplate {
  margin-right: 8px;
  span {
    color: #02a7f0;
  }
}
#upFile {
  display: none;
}
.el-message-box {
  /deep/.cancelBtn {
    background-color: #d7d7d7;
    border-color: transparent;
  }
  /deep/.confirmC {
    background-color: #ff545b !important;
    border-color: transparent !important;
  }
  /deep/.el-message-box__header {
    border-bottom: 1px solid #dcdfe6;
  }
}
.exportBox6 {
  /deep/ .el-message-box__btns {
    margin-top: 20px;
  }
  /deep/ .el-message-box__message {
    // text-align: center;
  }
  /deep/.leftbtn {
    background-color: #d7d7d7;
    border-color: transparent !important;
  }
  /deep/ .el-message-box__header {
    border-bottom: 1px solid #dcdfe6;
  }
}
.exportConfirm {
  .cancelSure {
    display: none;
  }
}
</style>