<template>
  <div class="druglist">
    <!-- 顶部筛选 -->
    <div class="screening">
      <div class="screening-title flex-vertical-center-l">
        <img src="~@/assets/filters.png" alt />
      </div>
      <div class="screening-form flex-vertical-center-l flex-wrap">
        <div class="screening-item flex-vertical-center-l">
          <span>医共体名称：</span>
          <div class="input">
            <el-select size="mini" placeholder="请选择"
                       v-model="searchData.ygtid" @change="searchData.cascader = [];getCascaderB($event)">
              <el-option
                :label="item.name"
                :value="item.pid"
                v-for="(item,index) in doctorBodyList"
                :key="index"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="screening-item flex-vertical-center-l">
          <span>医疗机构 / 科室名称：</span>
          <div class="input">
            <el-cascader v-if="searchData.ygtid" style="width: 100%" size="mini" clearable
                         :props="{ ...cascaderProp, checkStrictly: true }" :options="cascaderList"
                         v-model="searchData.cascader" @change="lazyLoadMethod"
            />
            <div v-else class="el-select el-select--mini">
              <div class="el-input el-input--mini el-input--suffix">
                <input class="el-input__inner" type="text" readonly="readonly" autocomplete="off" placeholder="请选择">
              </div>
            </div>
          </div>
        </div>

        <el-button type="primary" size="mini" @click="search()">搜索</el-button>
        <el-button type="warning" size="mini" @click="clearFilter()">清空</el-button>

        <el-button type="primary" size="mini" @click="openEditDialog()" v-if="showAdd">新增</el-button>
        <!-- <el-button type="danger" size="mini" v-if="showMapAuto" @click="autoMap(null)">自动映射</el-button> -->
      </div>
    </div>

    <!-- 底部表格数据 -->
    <div class="table">
      <div class="today-table">
        <div class="table-container">
          <el-table :data="tableData" stripe style="width: 100%" border height="100%" cell-class-name="cell-max-height">
            <el-table-column prop="id" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="name" width="200" label="药品目录名称" align="center"></el-table-column>
            <el-table-column prop="ygtName" width="200" label="医共体" align="center"></el-table-column>
            <el-table-column prop="stitutionsName" width="200" label="医疗机构" align="center"></el-table-column>
            <el-table-column prop="departmentidSelsourceName" label="科室" align="center"></el-table-column>
            <el-table-column prop="type" label="类型" width="100" align="center">
              <template slot-scope="scope">{{scope.row.type==0?'中心药房':'his'}}</template>
            </el-table-column>
            <el-table-column prop="describe" label="药品目录描述" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center">
              <div class="flex-center operation" slot-scope="scope">
                <!-- <div class="flex-center" style="margin-right:20px;" v-if="showAdd" @click="add(scope)">
                新增</div>-->
                <div class="flex-center" v-if="showEdit" @click="openEditDialog(scope.row)">修改</div>
                <div class="flex-center bg-yellow" v-if="showMap" @click="openMapPage(scope.row)">映射管理</div>
                <div class="flex-center bg-red" v-if="showMapAuto" @click="autoMap(scope)">自动映射</div>
                <div class="flex-center bg-yellow" v-if="showImport">
                  导入
                  <input
                    type="file"
                    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    id="fileSelect"
                    runat="server"
                    @change="uploadXSL"
                  />
                </div>
              </div>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex-vertical-center-r today-page">
          <el-pagination
            background
            layout=" prev, pager, next, jumper, total"
            :total="total"
            :page-size="limit"
            @current-change="sizeC($event)"
          ></el-pagination>
        </div>
      </div>
    </div>

    <popup
      distanceTop="5vh"
      :showDialog="showEditDialog"
      :loading="editLoading"
      @cancle="showEditDialog=false"
      @confim="submitEditData()"
      title="药品目录管理"
    >
      <div class="flex-center" slot="body">
        <div class="form">
          <div class="form-item flex flex-col-center">
            <span>*</span>
            <div class="name">医共体：</div>
            <div class="input">
              <el-select style="width: 100%" placeholder="请选择医共体"
                         v-model="editData.ygtid" @change="editData.cascader = [];getCascaderB($event)"
              >
                <el-option
                  :label="item.name"
                  :value="item.pid"
                  v-for="(item,index) in doctorBodyList"
                  :key="index"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="form-item flex flex-col-center">
            <span style="opacity:0;">*</span>
            <div class="name">医疗机构 / 科室：</div>
            <div class="input">
              <el-cascader v-if="editCascaderListLoaded" style="width: 100%" clearable collapse-tags
                           :props="{ multiple: true, }" :options="cascaderList"
                           v-model="editData.cascader"
              />
              <el-cascader v-else-if="editData.ygtid" style="width: 100%" clearable collapse-tags
                           :props="{ ...cascaderProp, multiple: true, }"
                           v-model="editData.cascader" @change="lazyLoadMethod"
              />
              <div v-else class="el-select" style="width: 100%;">
                <div class="el-input el-input--suffix">
                  <input type="text" readonly="readonly" autocomplete="off" placeholder="请选择"
                         class="el-input__inner">
                </div>
              </div>
            </div>
          </div>
          <div class="form-item flex flex-col-center">
            <span>*</span>
            <div class="name">类型：</div>
            <div class="input">
              <el-select style="width: 100%" v-model="editData.type" placeholder="请选择类型">
                <el-option label="中心药房" value="0"></el-option>
                <el-option label="HIS" value="1"></el-option>
              </el-select>
            </div>
          </div>
          <div class="form-item flex flex-col-center">
            <span>*</span>
            <div class="name">药品目录名称：</div>
            <div class="input">
              <el-input v-model="editData.name" placeholder="请输入"></el-input>
            </div>
          </div>
          <div class="form-item flex-plane-center-l">
            <span>*</span>
            <div class="name">药品目录描述：</div>
            <div class="input">
              <el-input type="textarea" v-model="editData.describe" placeholder="请输入"></el-input>
            </div>
          </div>
        </div>
      </div>
    </popup>
  </div>
</template>
<script>
import popup from "@/components/Propup.vue";
import {
  getDrugList,
  getDrugBM,
  updateDrugDesc,
  autoMap,
  addDrugList
} from "@/api/business.js";

import { fileImport } from "@/api/upload.js";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import {
  getDoctorBodySelect,
  getMedSelect,
  getDepartSelect
} from "@/api/system.js";

let cache = new Map();
export default {
  components: {
    popup
  },
  data() {
    return {
      searchData: {
        ygtid: '',
        cascader: [],
      },
      tableData: [],
      page: 1,
      limit: 10,
      total: 0,

      // 新增 表单字段
      showEditDialog: false,
      editLoading: false,
      editData: {
        ygtid: '',
        cascader: [],
      },
      editCascaderListLoaded: false,
      showAdd: true,
      showImport: true,
      showMapAuto: true,
      showEdit: true,
      showMap: true,

      pid: "",
      nowPid: "",

      // 医共体
      doctorBodyList: [],
      // 机构 / 科室
      cascaderList: [],
      cascaderProp: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          if (Array.isArray(node.children) && node.children.length > 0) resolve();
          else switch (node.level) {
            case 0:
              /* 编辑表单没有添加 :options="cascaderList" */
              /* el bug 直接选择子选项 不能选中  */
              return this.editData.ygtid && this.getCascaderB(this.editData.ygtid).then(resolve);
            case 1:
              return this.getCascaderC(node.value).then(resolve);
            case 2:
              resolve();
          }
        },
      },
    };
  },
  created() {
    this.getCascaderA();
    this.getDrugList();
    this.getDrugBM();
    this.nowPid = this.getuserinfo.organizationid;
  },
  destroyed() { cache.clear(); },
  methods: {
    lazyLoadMethod(value) {
      if (Array.isArray(value) && value.length === 1) {
        const parent = this.cascaderList.find(item => item.value === value[0]);
        if (parent && !parent.leaf && !parent.children.length) this.cascaderProp.lazyLoad({
          value: value[0],
          level: 1,
        }, () => void 0);
      }
    },
    openMapPage(row) {
      this.$router.push({path: `/index/drugmaplist?pid=${row.pid}`});
    },
    async openEditDialog(row = {}) {
      this.editData = {
        pid: row.pid,
        describe: row.describe || '',
        name: row.name || '',
        type: row.type,
        ygtid: row.ygtid || this.searchData.ygtid,
        cascader: row.stitutionsId || !this.searchData.cascader.length ? [] : [this.searchData.cascader],
      };
      this.editCascaderListLoaded = this.editData.cascader.length > 0 || !!row.stitutionsId;
      this.showEditDialog = true;
      if (this.editCascaderListLoaded) {
        this.editLoading = true;
        if (this.editData.ygtid) await this.getCascaderB(this.editData.ygtid);
        const list = await Promise.all(this.cascaderList.map(item => this.getCascaderC(item.value))).then(() => this.cascaderList);
        if (row.stitutionsId) {
          const cascader = [];
          const stitutionsId = (row.stitutionsId || '').split(',').filter(Boolean);
          const departmentidSelsource = (row.departmentidSelsource || '').split(',').filter(Boolean);
          for (const s of stitutionsId) {
            try {
              const nodes = list.find(item => item.value === s).children.map(node => node.value);
              let i = 0;
              let has = 0;
              do {
                const d = departmentidSelsource[i];
                if (nodes.includes(d)) {
                  has = cascader.push([s, d]);
                  departmentidSelsource.splice(i, 1);
                } else if (d) i += 1;
              } while (departmentidSelsource.length < i);
              if (!has) cascader.push(...nodes.map(d => [s, d]));
            } catch (e) { }
          }
          this.editData.cascader = [...cascader];
        }
        this.editLoading = false;
      }
    },
    async submitEditData() {
      const {cascader = [], ...params} = this.editData;
      const stitutionsId = new Set();
      const departmentidSelsource = new Set();
      if (cascader.length) {
        for (const [s, d] of cascader) {
          stitutionsId.add(s);
          departmentidSelsource.add(d);
        }
      }
      params.stitutionsId = [...stitutionsId].join(',');
      params.departmentidSelsource = [...departmentidSelsource].join(',');
      // 构造 医共体 / 机构 / 科室 树
      params.groupInfo = [{
        pid: params.ygtid,
        name: this.doctorBodyList.find(item => item.pid === params.ygtid).name,
        children: [],
      }];
      if (stitutionsId.size) {
        const group = params.groupInfo[0].children;
        for (const s of stitutionsId) {
          const item1 = this.cascaderList.find(item => item.value === s);
          if (!item1) continue;
          const length = group.push({pid: item1.value, name: item1.label, children: []});
          if (item1.leaf || !Array.isArray(item1.children) || !item1.children.length) continue;
          for (const d of departmentidSelsource) {
            const item2 = item1.children.find(item => item.value === d);
            if (!item2) continue;
            group[length - 1].children.push({pid: item2.value, name: item2.label, children: []});
            departmentidSelsource.delete(d);
          }
        }
      }
      params.groupInfo = JSON.stringify(params.groupInfo);
      const res = await (params.pid ? updateDrugDesc(params) : addDrugList(params));
      if (res.ResultCode == 0) {
        this.$message.success(params.pid ? '操作成功' : '添加成功');
        this.showEditDialog = false;
        await this.getDrugList();
      }
    },
    add(scope) {
      this.$router.push({
        path: "/index/drugmaplist?id=" + scope.row.pid
      });
    },
    sizeC(e) {
      this.page = e;
      this.getDrugList();
    },
    search() {
      this.page = 1;
      this.getDrugList();
    },
    // 清空搜索条件
    clearFilter() {
      this.searchData = {
        ygtid: '',
        cascader: [],
      };
      this.cascaderList = [];
      this.getDrugList();
    },
    doctorBodyC() {
      // this.page = 1
      // this.getDrugList()
    },
    uploadXSL(e) {
      console.log(e, "e");
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      this.fileImport(formData);
    },
    // 获取医共体选择器数据
    async getCascaderA() {
      const res = await getDoctorBodySelect();
      if (res && +res.ResultCode === 0) {
        this.doctorBodyList = res.Data;
      }
    },
    async getCascaderB(organizationId) {
      const nodes = cache.has(organizationId) ? cache.get(organizationId) : await getMedSelect({organizationId}).then(res => res && +res.ResultCode === 0
          ? res.Data.map(item => ({
            children: [], leaf: false,
            label: item.name, value: item.pid,
          }))
          : [],
      ).catch(() => []);

      cache.set(organizationId, nodes);
      this.cascaderList = nodes;
      return nodes;
    },
    async getCascaderC(institutionId) {
      const parent = this.cascaderList.find(item => item.value === institutionId);
      if (parent && (parent.leaf || parent.children.length)) return parent.children || [];

      const nodes = await getDepartSelect({institutionId}).then(res => res && +res.ResultCode === 0
          ? res.Data.map(item => ({
            leaf: true,
            label: item.name, value: item.pid,
          }))
          : [],
      ).catch(() => []);

      if (parent) {
        parent.children = nodes;
        if (!nodes.length) parent.leaf = true;
      }
      return nodes;
    },
    // 获取药品列表
    async getDrugList() {
      let params = {
        page: this.page,
        limit: this.limit,
        // jgmc: this.yigt
        // ygtid: this.yigt,

        ygtid: this.searchData.ygtid,
        stitutionsId: this.searchData.cascader[0],
        departmentidSelsource: this.searchData.cascader[1],
      };
      let res = await getDrugList(params);
      if (res.ResultCode == 0) {
        this.tableData = res.Data.Items;
        this.total = res.Data.TotalRecordCount;
        this.tableData.filter((item, index) => {
          item.id = index + 1;

          return item;
        });

        this.showEdit = res.Data.ButtonRight.indexOf("view") != -1;
        this.showMap = res.Data.ButtonRight.indexOf("mapping") != -1;
      }
    },
    async getDrugBM() {
      let res = await getDrugBM();

      this.showAdd = res.Data.indexOf("add") != -1;
      this.showImport = res.Data.indexOf("edit") != -1;
      this.showMapAuto = res.Data.indexOf("del") != -1;
    },
    // 自动映射
    async autoMap(scope) {
      // console.log(scope, '一共提')
      // return
      const loading = this.$loading({
        lock: true,
        text: "正在映射",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await autoMap({
        // orgId: this.getuserinfo.organizationid
        // orgId: scope ? scope.row.pid : this.getuserinfo.organizationid,
        orgId: scope.row.ygtid
      }).catch(err => {
        loading.close();
      });
      if (res.ResultCode == 0) {
        loading.close();
        this.getDrugList();
        if (res.Data.length > 0) {
          this.$message({
            message: "映射成功," + res.Data.join("、") + "药品无法映射",
            type: "warning",
            showClose: true
          });
        } else {
          this.$message({
            message: "映射成功",
            type: "success",
            showClose: true
          });
        }
      }
    },
    // 导入
    async fileImport(data) {
      let res = await fileImport(data);
      if (res.ResultCode == 0) {
        this.$message({
          message: "导入成功",
          type: "success",
          showClose: true
        });
      }
    }
  },
  computed: {
    ...mapGetters(["getuserinfo"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";
@import "../../style/base.scss";

.bg-yellow {
  background: #ffae45;
  position: relative;
  width: 56px;
  height: 28px;

  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #ffffff;
  margin-left: 10px;
  margin-right: 10px;

  input {
    width: 74px;
    height: 36px;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    opacity: 0;
  }
}

.table {
  padding: 10px 10px;
  background: #ffffff;
  border-radius: 5px;
  margin-top: 10px;
  height: 70vh;

  .table-container {
    height: 90%;
  }

  .today-table {
    height: 100%;

    .operation {
      display: flex;
      align-items: center;
      justify-content: space-around;
      flex-wrap: wrap;
      div {
        width: 60px;
        height: 24px;
        background: #5386f6;
        border-radius: 2px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
        margin: 5px 0;
      }

      .bg-yellow {
        width: 80px;
        height: 24px;
        background: #ffae45;
      }

      .bg-red {
        width: 80px;
        height: 24px;
        background: red;
      }
    }
  }
}

.table-body::v-deep .el-table .cell {
  text-align: center;
}

.el-table::v-deep {
  .cell-max-height div {
    max-height: 240px;
    overflow-y: auto;
  }
}

</style>



<style lang="scss" scoped>
@media screen and (min-width: 1681px) and (max-width: 1920px) {
  .table {
    height: 81vh;

    .table-container {
      height: 94%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 18px 0;
  }
}

@media screen and (min-width: 1601px) and (max-width: 1680px) {
  .table {
    height: 80vh;

    .table-container {
      height: 94%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table td {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 18px 0;
  }
}

@media screen and (min-width: 1361px) and (max-width: 1600px) {
  .table {
    height: 72vh;

    .table-container {
      height: 90%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 5px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 5px 0;
  }
}

@media screen and(min-width:1281px) and (max-width: 1360px) {
  .table {
    height: 72vh;

    .table-container {
      height: 90%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 5px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 5px 0;
  }
}

.form {
  width: 50%;

  .form-item {
    margin-bottom: 10px;

    span {
      color: red;
    }

    .name {
      width: 120px;
    }

    .input {
      flex: 1;
    }
  }
}
</style>