<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="" prop="communityId">
            <el-select style="width:160px" v-model="queryParams.communityId"
                       placeholder="请选择医共体" size="small" :clearable="false"
                       @change="getMechanismList()"
            >
              <el-option v-for="item in cascade[0]" :key="item.id" :value="item.id" :label="item.name"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="mechanismId">
            <el-select style="width:160px" v-model="queryParams.mechanismId"
                       placeholder="请选择医疗机构" size="small" :clearable="false"
                       @change="getDeptList()"
            >
              <el-option v-for="item in cascade[1]" :key="item.id" :value="item.id" :label="item.name"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="mechanismId">
            <el-select style="width:160px" v-model="queryParams.deptId"
                       placeholder="请选择科室" size="small" clearable
            >
              <el-option v-for="item in cascade[2]" :key="item.id" :value="item.id" :label="item.name"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="herbsCode">
            <el-input style="width:160px" v-model="queryParams.herbsCode" placeholder="医疗机构药品编码" size="small"
                      clearable
                      @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="herbsName">
            <el-input style="width:160px" v-model="queryParams.herbsName" placeholder="医疗机构药品名称" size="small"
                      clearable
                      @keyup.enter.native="handleQuery"
            ></el-input>
          </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-button type="primary" plain icon="el-icon-plus" size="mini"
                       v-hasPermi="['drugs:map:create']" @click="handleEdit()"
            >新增
            </el-button>
            <el-button type="default" plain icon="el-icon-upload2" size="mini"
                       :loading="importing"
                       v-hasPermi="['drugs:map:import']" @click="startUpload = true;"
            >导入
            </el-button>
            <el-button type="default" plain icon="el-icon-download" size="mini"
                       :loading="exporting"
                       v-hasPermi="['drugs:map:export']" @click="handleExport()"
            >导出
            </el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <el-table v-loading="loading" :data="list" size="mini" border>
      <el-table-column type="index" width="55" align="center" label="序号"/>
      <el-table-column prop="drugsName" label="系统药品名称" align="center"/>
      <el-table-column prop="drugsId" label="系统药品编码" align="center"></el-table-column>
      <el-table-column prop="herbsName" label="医疗机构药品名称" align="center"></el-table-column>
      <el-table-column prop="herbsCode" label="医疗机构药品编码" align="center"></el-table-column>
      <el-table-column prop="herbsSpecsName" label="医疗机构药品规格" align="center"></el-table-column>
      <el-table-column prop="herbsSpecsCode" label="医疗机构药品规格编码" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" align="center"></el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button style="width: 40px;" type="danger" size="mini"
                     v-hasPermi="['drugs:map:remove']"
                     @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"
    />

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :fullscreen="false" :title="title" :visible.sync="open" width="80%" append-to-body size="mini"
               destroy-on-close>
      <edit :community-id="model.communityId" :mechanism-id="model.mechanismId" :dept-id="model.deptId"
            @close="open = false;$event && getList()"
      />
    </el-dialog>

    <el-dialog :fullscreen="false" title="药品映射" :visible.sync="startUpload" width="400px" append-to-body
               size="mini">
      <upload
        :uploading="uploading" @upload="handleImport($event)"
        :downloading="downloading" @download="handleDownload()"
      />
    </el-dialog>


  </div>
</template>

<script>
import selectTable from '@/components/selectTable/selectTable.vue'
import Edit from "./edit.vue";
import Upload from "./upload.vue";
import {listCommunity} from "@/api/system/community";
import {listMechanismId} from "@/api/medical/mechanism";
import {getByMechanismId} from "@/api/medical/dept";
import {drugsMap, drugsMapDelete, drugsMapExport, drugsMapImport, drugsMapImportTemplate} from "@/api/drugs/drugs";

export default {
  name: "DrugsMap",
  computed: {},
  components: {
    Edit,
    Upload,
    selectTable
  },
  data() {
    return {
      cascade: [[], [], []],
      list: [],
      model: {},
      // 遮罩层
      loading: false,
      exporting: false,
      importing: false,
      uploading: false,
      downloading: false,
      startUpload: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "药品映射",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pharmacyId: window.localStorage.getItem("pharmacyId"),

        herbsCode: '',
        herbsName: '',

        communityId: '',
        mechanismId: '',
        deptId: '',
      },
      backupsParams: {},
    };
  },
  created() {
    this.resetQuery();
  },
  methods: {
    /** 查询医共体列表 */
    async getCommunityList() {
      try {
        const {rows} = await listCommunity();
        this.$set(this.cascade, 0, rows.map(item => (item.disabled = item.state === '0', item)))
      } catch (error) {
        this.$set(this.cascade, 0, []);
      }
      const list = this.cascade[0];
      const select = this.queryParams.communityId;
      if (list.length && !(select && list.find(item => item.id === select))) this.queryParams.communityId = list[0].id;
    },
    /** 查询医疗机构列表 */
    async getMechanismList() {
      try {
        if (!this.queryParams.communityId) throw '';
        const {data: rows} = await listMechanismId(this.queryParams.communityId);
        this.$set(this.cascade, 1, rows.map(item => (item.disabled = item.state === '0', item)))
      } catch (error) {
        this.$set(this.cascade, 1, []);
      }
      const list = this.cascade[1];
      const select = this.queryParams.mechanismId;
      if (list.length && !(select && list.find(item => item.id === select))) this.queryParams.mechanismId = list[0].id;

      this.$set(this.cascade, 2, [])
      this.queryParams.deptId = '';
    },
    /** 查询科室列表 */
    async getDeptList() {
      try {
        if (!this.queryParams.mechanismId) throw '';
        const {data: rows} = await getByMechanismId(this.queryParams.mechanismId);
        this.$set(this.cascade, 2, rows.map(item => (item.disabled = item.state === '0', item)))
      } catch (error) {
        this.$set(this.cascade, 2, []);
      }
      const select = this.queryParams.deptId;
      if (select && !this.cascade[2].find(item => item.id === select)) this.queryParams.deptId = '';
    },

    async getList() {
      this.queryParams.communityId = this.backupsParams.communityId;
      this.queryParams.mechanismId = this.backupsParams.mechanismId;
      this.queryParams.deptId = this.backupsParams.deptId;
      this.loading = true;
      try {
        const {rows, total} = await drugsMap(this.queryParams);
        this.list = rows;
        this.total = total;
      } catch (error) {}
      this.loading = false;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      const {communityId, mechanismId, deptId} = this.queryParams;
      this.backupsParams = {communityId, mechanismId, deptId}
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    async resetQuery() {
      this.resetForm("queryForm");
      /*this.queryParams.date = [
        dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      ]*/

      this.queryParams.communityId = this.backupsParams.communityId;
      await this.getCommunityList();
      if (!this.queryParams.communityId) return;
      this.queryParams.mechanismId = this.backupsParams.mechanismId;
      await this.getMechanismList();
      if (!this.queryParams.mechanismId) return;
      this.handleQuery();
      await this.getDeptList()
    },
    handleEdit() {
      this.model = {...this.backupsParams};
      this.editable = true;
      this.open = true;
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否删除该药品映射？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => drugsMapDelete(ids))
        .then(() => {
          this.open = false;
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    async handleExport() {
      this.exporting = true;
      try {
        const {blob, name = ''} = await drugsMapExport(this.backupsParams);
        await this.download(blob, name);
        this.msgSuccess(`${name} 下载成功`);
      } catch (error) {}
      this.exporting = false;
    },
    async handleDownload() {
      this.downloading = true;
      try {
        const {blob, name = ''} = await drugsMapImportTemplate(this.backupsParams);
        await this.download(blob, name);
        this.msgSuccess(`${name} 下载成功`);
      } catch (e) { }
      this.downloading = false;
    },
    async handleImport(file) {
      this.uploading = true;
      try {
        const {msg} = await drugsMapImport(Object.assign({file}, this.backupsParams));
        this.msgSuccess(msg);
        this.startUpload = false;
        this.getList().then();
      } catch (e) {}
      this.uploading = false;
    },
    download(blob, filename = '') {
      const link = document.createElement('a');
      document.body.appendChild(link);

      const url = URL.createObjectURL(blob);
      link.href = url;
      link.download = filename;
      link.click();

      return new Promise(resolve => {
        setTimeout(() => {
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
          resolve();
        }, 20)
      })
    }
  },
};
</script>
<style scoped>
.el-input--small .el-input__inner {
  height: 36px;
  line-height: 36px;
}
</style>
