<template>
  <div class="app-container" v-loading="uploading" element-loading-text="数据导入中">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="院区" prop="wardId">
        <el-select v-model="queryParams.wardId" filterable clearable style="width: 240px">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in wardIdList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="deptId">
        <TreeDept
          v-model="queryParams.deptId"
          clearable
          style="width: 240px"
          :options="deptList"
          :autoFetch="false"
          :props="{ emitPath: true }"
        />
      </el-form-item>
      <el-form-item label="疾病名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入疾病名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">
          新增疾病
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          ref="upload"
          action=""
          accept=".xlsx, .csv"
          list-type="text"
          :multiple="false"
          :limit="1"
          :show-file-list="false"
          :http-request="handleUpload"
          auto-upload
        >
          <el-button type="success" plain icon="el-icon-upload" size="mini">批量导入疾病</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <a :href="exportTemplateUrl" download="批量导入疾病模版.xlsx">
          <el-button type="danger" plain icon="el-icon-download" size="mini">
            下载数据模板
          </el-button>
        </a>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="pageList" border>
      <el-table-column
        align="center"
        label="序号"
        type="index"
        :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
        width="120"
      />
      <el-table-column align="center" label="疾病名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="院区" prop="wardName" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="科室" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import ImportResultPopup from "@/components/ImportResultPopup";
import { diseasePageList, deleteDisease, batchImportDisease, getAllHospital, getTreeHospDept } from "@/api/admin";
import CrudPopup from "./components/CrudPopup/index.vue";
import TreeDept from "@/components/TreeDept";

export default {
  name: "DiseaseManage",
  components: {
    ImportResultPopup,
    CrudPopup,
    TreeDept
  },

  data() {
    return {
      exportTemplateUrl: process.env.VUE_APP_BASE_PATH + "template/diseaseTemplate.xlsx",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        wardId: "", // 院区ID
        deptId: []
      },
      pageList: [],
      uploading: false,
      wardIdList: [], // 院区列表
      deptList: [] // 科室数据
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    this.loadData();
  },
  watch: {
    "queryParams.wardId"(val) {
      const wardId = val;
      if (wardId) {
        this.queryParams.deptId = [];
        this.getDeptList(wardId);
        this.getList(wardId);
      } else {
        this.queryParams.deptId = [];
        this.pageList = [];
        this.getDeptList();
        this.getList();
      }
    },
    "queryParams.deptId"(val) {
      const deptId = val[1] || val[0];
      if (deptId) {
        this.getList(deptId);
      } else {
        this.pageList = [];
      }
    },
  },
  methods: {
    loadData() {
      this.loadWardIdList();
      this.getDeptList();
      this.getList();
    },
    /*获取院区列表*/
    async loadWardIdList() {
      const res = await getAllHospital();
      this.wardIdList = res.data;
    },
    /*获取科室数据*/
    async getDeptList(wardId) {
      const res = await getTreeHospDept({ wardId : wardId });
      this.deptList = res.data || [];
    },
    getList() {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      params.deptId = params.deptId?.length === 2 ?
        params.deptId.slice(-1).toString() :
        params.deptId?.length === 1 && params.deptId.slice(-1).toString() || '';
      diseasePageList(this.addDateRange(params, this.dateRange))
        .then((res) => {
          const { list, page } = res.data;
          this.pageList = list || [];
          this.total = page?.total || 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 导入
    async handleUpload({ file }) {
      this.uploading = true;
      try {
        const res = await batchImportDisease(file);
        if (res.data.successSize > 0) {
          // 刷新
          this.getList();
        }
        this.$refs.importResult.open(res.data);
      } finally {
        this.$refs.upload.clearFiles();
        this.uploading = false;
      }
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getDeptList(this.queryParams.wardId);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增 */
    handleAdd() {
      this.$refs.crud.open().then(this.getList);
    },
    /** 编辑 */
    handleEdit(item) {
      this.$refs.crud.open(item).then(this.getList);
    },
    handleDelete(item) {
      this.$modal
        .confirm("是否确认删除？")
        .then(async () => {
          await deleteDisease(item.id);
          this.$message.success("操作成功");
          this.getList();
        })
        .catch(() => {});
    },
    handleExportSuccess(data) {},
  },
};
</script>
<style lang="scss" scoped></style>
