<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="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入药房名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="communityId">
            <el-select
              v-model="queryParams.communityId"
              placeholder="请选择医共体"
              clearable
              size="small"
            >
              <el-option
                v-for="item in cimmunity"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.state == 1 ? false : true"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="mechanismId">
            <el-select
              v-model="queryParams.mechanismId"
              placeholder="请选择医疗机构"
              clearable
              size="small"
            >
              <el-option
                v-for="item in mechanismArr.filter(v=>v.communityId==queryParams.communityId)"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.state == 1 ? false : true"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="query-box__right">
          <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"
              @click="handleAdd"
              v-hasPermi="['pharmacy:MedicalPharmacy:add']"
              >新增</el-button
            >
          </el-form-item>
        </div>
      </div>

      <!-- <el-form-item label="药房类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择药房类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="机构类型" prop="mechanismType">
        <el-select v-model="queryParams.mechanismType" placeholder="请选择机构类型" clearable size="small">
          <el-option
            v-for="dict in mechanismTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->

      <!-- <el-form-item label="科室id" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择科室id" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="上级药房" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入上级药房"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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"
          v-hasPermi="['pharmacy:MedicalPharmacy:add']"
          >新增</el-button
        >
      </el-col>

    </el-row> -->

    <el-table
      v-loading="loading"
      :data="MedicalPharmacyList"
      row-key="id"
      default-expand-all
      :border="true"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column
        label="医共体名称"
        align="center"
        prop="communityName"
        width="140"
      />
      <el-table-column label="药房名称" prop="name" width="140" />
      <el-table-column label="药房编码" prop="code" width="140" />
      <el-table-column label="药房类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="药房机构类别" align="center" prop="mechanismType">
        <template slot-scope="scope">
          <dict-tag
            :options="mechanismTypeOptions"
            :value="scope.row.mechanismType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="医疗机构名称"
        align="center"
        prop="mechanismName"
      />
      <el-table-column
        label="科室名称"
        align="center"
        prop="deptName"
        width="140"
      />
      <el-table-column label="药房状态" align="center" prop="state">
        <template slot-scope="scope">
          <!-- <dict-tag :options="stateOptions" :value="scope.row.state" /> -->
          {{ scope.row.state == 1 ? "启用" : "禁用" }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pharmacy:MedicalPharmacy:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['pharmacy:MedicalPharmacy:add']"
            >新增</el-button
          > -->
          <!-- <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleState(scope.row, 0)"
            v-hasPermi="['pharmacy:MedicalPharmacy:edit']"
            >启用</el-button
          > -->
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleState(scope.row)"
            v-hasPermi="['pharmacy:MedicalPharmacy:edit']"
            >{{ scope.row.state != 1 ? "启用" : "禁用" }}</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pharmacy:MedicalPharmacy:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改药房对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="药房名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入药房名称" />
        </el-form-item>
        <el-form-item label="药房编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入药房编码" />
        </el-form-item>
        <el-form-item label="药房类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择药房类型"
            style="width: 100%"
          >
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药房共享状态" prop="yflx">
          <el-select
            v-model="form.yflx"
            placeholder="请选择药房共享状态"
            style="width: 100%"
          >
            <el-option
              v-for="dict in YFLXArr"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药房机构类别" prop="mechanismType">
          <el-select
            v-model="form.mechanismType"
            placeholder="请选择药房机构类别"
            style="width: 100%"
          >
            <el-option
              v-for="dict in mechanismTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医共体" prop="communityId">
          <el-select
            v-model="form.communityId"
            placeholder="请选择医共体"
            style="width: 100%"
          >
            <el-option
              v-for="item in cimmunity"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.state == 1 ? false : true"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医疗机构" prop="mechanismId">
          <!-- <el-select
            v-model="form.mechanismId"
            placeholder="请选择医疗机构"
            style="width: 100%"
            @change="handleMechanism"
          >
            <el-option
              v-for="item in mechanism"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.state == 1 ? false : true"
            >
            </el-option> -->
            <treeselect
              v-model="form.mechanismId"
              :options="MedicalPharmacyOptions"
              :normalizer="normalizer"
              placeholder="请选择医疗机构"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择科室"
            style="width: 100%"
          >
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.name"
              :value="item.id+''"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级药房" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="parentPharmacy"
            :normalizer="normalizer"
            placeholder="请选择上级药房"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMedicalPharmacy,
  getMedicalPharmacy,
  delMedicalPharmacy,
  addMedicalPharmacy,
  updateMedicalPharmacy,
  exportMedicalPharmacy,
} from "@/api/pharmacy/MedicalPharmacy";
import { listMechanismId } from "@/api/medical/mechanism";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getByMechanismId } from "@/api/medical/dept";
import { listMedicalMechanism } from "@/api/medical/mechanism";
import { listCommunity } from "@/api/medical/community";
export default {
  name: "MedicalPharmacy",
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 药房表格数据
      MedicalPharmacyList: [],
      // 药房树选项
      MedicalPharmacyOptions: [{ id: 0, name: "顶级节点", children: [] }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 药房类型字典
      typeOptions: [],
      // 状态字典
      stateOptions: [],
      // 机构类型字典
      mechanismTypeOptions: [],
      mechanisms: [],
      // 是否删除字典
      delOptions: [],
      // 查询参数
      queryParams: {
        name: null,
        type: null,
        mechanismType: null,
        mechanismId: null,
        communityId: null,
        deptId: null,
        parentId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入药房名称必填", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入药房编码必填", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择药房类型", trigger: "blur" }],
        mechanismType: [
          { required: true, message: "请选择药房机构类别", trigger: "blur" },
        ],
        communityId: [
          { required: true, message: "请选择医共体", trigger: "blur" },
        ],
        yflx: [{ required: true, message: "请选择药房共享" }],
      },
      cimmunity: [], //医共体列表
      mechanism: [], //医疗机构列表
      deptList: [], //科室列表
      YFLXArr: [],
      mechanismArr: [],
      parentPharmacy: [{ id: 0, name: "顶级节点", children: [] }]
    };
  },
  created() {
    this.getList();
    this.getCommunityList();
    // this.getMechanismList();
    // this.getListDept();
    this.getMechanismListArr();
    this.getDicts("pharmacyType").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("YFLX").then((response) => {
      this.YFLXArr = response.data;
    });
    this.getDicts("pharmacy_type").then((response) => {
      this.mechanismTypeOptions = response.data;
    });
    this.getDicts("del_state").then((response) => {
      this.delOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then((response) => {
      this.stateOptions = response.data;
    });
  },
  watch: {
    'queryParams.communityId' (val) {
      this.queryParams.mechanismId = ''
    },
    'form.mechanismId' (val) {
      if (!val) {
        return
      }
      this.getListDept(val)
      var d = this.parentPharmacy.find(v => v.id == val)
      if (d && d.parentId) {
        this.parentPharmacy.children = [{
          id: d.parentId,
          name: d.parentName
        }]
      }
    },
    'form.communityId' (val) {
      this.handleCommunityId(val)
    }
  },
  methods: {
    /** 查询药房列表 */
    getList() {
      this.loading = true;
      listMedicalPharmacy(this.queryParams).then((response) => {
        this.MedicalPharmacyList = this.handleTree(
          response.data,
          "id",
          "parentId"
        );
        this.loading = false;
      });
    },
    /** 转换药房数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询药房下拉树结构 */
    getTreeselect() {
      listMedicalPharmacy({
        state: 1
      }).then((response) => {
        this.mechanisms = response.data;
      });
    },
    getMechanismListArr() {
      listMedicalMechanism().then((response) => {
        this.mechanismArr = response.data;
      });
    },
    /** 查询医共体列表 */
    getCommunityList() {
      listCommunity().then((response) => {
        this.cimmunity = response.rows;
      });
    },
    /** 根据医共体筛选 **/
    handleCommunityId(e) {
      if (e) {
        this.getMechanismList(e)
      }
    },
    /** 查询医疗机构名称 **/
    getMechanismList(id) {
      listMechanismId(id).then((response) => {
        if (!this.form.id) {
          this.form.mechanismId = ''
          this.form.parentId = 0
        }
        this.MedicalPharmacyOptions = []
        //var arr = this.mechanisms.filter(v => v.type == val)
        const data = { id: 0, name: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.MedicalPharmacyOptions.push(data)
      });
    },
    /** 通过医疗机构查询科室 **/
    /*handleMechanism(e) {
      this.getListDept(e);
    },*/
    /** 查询科室名称 */
    getListDept(id) {
      getByMechanismId(id).then((response) => {
        this.deptList = response.data;
        //this.form.deptId = null;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        mechanismType: null,
        mechanismId: null,
        communityId: null,
        deptId: null,
        parentId: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        del: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加药房";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getMedicalPharmacy(row.id).then((response) => {
        this.open = true;
        this.form = response.data
        this.form.deptId += ''
        this.title = "修改药房";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMedicalPharmacy(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMedicalPharmacy(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("确定需要删除已选数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delMedicalPharmacy(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //启用 / 禁用
    handleState(row, num) {
      const id = row.id || this.ids;
      const parmes = {
        id,
        state: row.state == 1 ? (row.state = 2) : (row.state = 1),
      };
      updateMedicalPharmacy(parmes).then(() => {
        // this.form = response.data;
        this.getList();
        this.msgSuccess('修改成功')
        window.location.reload()
      });
    },
  },
};
</script>
