<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>
            <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:storage:add']">新增</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-table v-loading="loading" :data="storageList" size="mini" @selection-change="handleSelectionChange" :border="true">
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="出入库方式名称" align="center" prop="name"/>
      <el-table-column label="出入库标志" align="center" prop="mark">
        <template slot-scope="scope">
          <dict-tag :options="markOptions" :value="scope.row.mark" />
        </template>
      </el-table-column>
      <el-table-column label="单位部门类型" align="center" prop="deptType">
        <template slot-scope="scope">
          <dict-tag :options="deptTypeOptions" :value="scope.row.deptType" />
        </template>
      </el-table-column>
      <el-table-column label="出入库策略" align="center" prop="strategy">
        <template slot-scope="scope">
          <dict-tag :options="strategyOptions" :value="scope.row.strategy" />
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="display">
        <template slot-scope="scope">
          {{ scope.row.display === "Y" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="系统预置" align="center" prop="sysState">
        <template slot-scope="scope">
          {{ scope.row.sysState === "Y" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="顺序号" align="center" prop="sort" />
      <el-table-column label="使用范围" align="center" prop="pharmacyList">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.pharmacyList" :key="index" style="margin-right: 5px">{{ item.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" style="width: 40px" @click="handleUpdate(scope.row)" v-hasPermi="['pharmacy:storage:edit']">修改</el-button>
          <el-button size="mini" type="primary" style="width: 40px" @click="handleDelete(scope.row)" v-hasPermi="['pharmacy:storage:remove']" v-if="scope.row.sysState !== 'Y'">删除</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 :title="title" :visible.sync="open" :destroy-on-close="true" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="出入库方式名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入出入库方式名称" />
        </el-form-item>
        <el-form-item label="出入库标志" prop="mark">
          <el-select v-model="form.mark" placeholder="请选择出入库标志" style="width: 100%" @change="handleMark">
            <el-option v-for="dict in markOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对应出入库标志" prop="dyMark">
          <el-select v-model="form.dyMark" placeholder="请选择对应标志" style="width: 100%">
            <el-option label="出库" value="1" :disabled="form.mark == 1"></el-option>
            <el-option label="入库" value="2" :disabled="form.mark == 2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对应出入库方式" prop="dyId">
          <el-select v-model="form.dyId" style="width: 100%" placeholder="请选择对应出入库方式">
            <el-option v-for="item in markArr" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位部门类型" prop="deptType">
          <el-select v-model="form.deptType" placeholder="请选择单位部门类型" style="width: 100%">
            <el-option v-for="dict in deptTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出入库策略" prop="strategy">
          <el-select v-model="form.strategy" placeholder="请选择出入库策略" style="width: 100%">
            <el-option v-for="dict in strategyOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示" prop="display">
          <el-select v-model="form.display" placeholder="请选择是否显示" style="width: 100%">
            <el-option v-for="dict in sysOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统预置" prop="sysState">
          <el-select v-model="form.sysState" placeholder="请选择系统预置" style="width: 100%" @change="handleSysState" disabled>
            <el-option v-for="dict in sysOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="使用范围" prop="pharmacyList">
          <el-tree
            v-model="form.pharmacyList"
            :data="MedicalPharmacyList"
            :show-checkbox="true"
            node-key="id"
            @check="treeCheck"
            :default-checked-keys="pharmacyListArr"
            ref="treeCheck" 
          >
          </el-tree>
        </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 {
  listStorage,
  getStorage,
  delStorage,
  addStorage,
  updateStorage,
  exportStorage,
  boundary,
} from "@/api/pharmacy/storage";
import { listMedicalPharmacy } from "@/api/pharmacy/MedicalPharmacy";
export default {
  name: "Storage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库管理表格数据
      storageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 出入库标志字典
      markOptions: [],
      // 单位部门类型字典
      deptTypeOptions: [
        { dictLabel: "药房", dictValue: "1" },
        { dictLabel: "供货单位", dictValue: "2" },
      ],
      // 出入库策略字典
      strategyOptions: [],
      disableDetails: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        mark: null,
        deptType: null,
        strategy: null,
        display: null,
        sysState: null,
      },
      // 表单参数
      form: {
        pharmacyList: [],
        sysState: "N",
      },
      pharmacyListArr: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "出入库方式名称必填", trigger: "blur" },
        ],
        mark: [{ required: true, message: "出入库标志必填", trigger: "blur" }],
        deptType: [
          { required: true, message: "单位部门类型必填", trigger: "blur" },
        ],
        strategy: [
          { required: true, message: "出入库策略必填", trigger: "blur" },
        ],
        display: [{ required: true, message: "是否显示必填", trigger: "blur" }],
        sysState: [
          { required: true, message: "系统预置必填", trigger: "blur" },
        ],
        sort: [{ required: true, message: "排序必填", trigger: "blur" }],
        pharmacyList: [
          { required: true, message: "使用范围必填", trigger: "blur" },
        ],
      },
      sysOptions: [],
      MedicalPharmacyList: [],
      markArr:[],
    };
  },
  created() {
    this.getList();
    this.getMedicalPharmacy();
    this.getDicts("lssue_receipt").then((response) => {
      this.markOptions = response.data;
    });
    // this.getDicts("dept_type").then((response) => {
    //   this.deptTypeOptions = response.data;
    // });
    this.getDicts("lssue_receipt_strategy").then((response) => {
      this.strategyOptions = response.data;
    });
    // sys_yes_no
    this.getDicts("sys_yes_no").then((response) => {
      this.sysOptions = response.data;
    });
  },
  methods: {
    handleSysState(e) {
      //console.log(e);
      // e === "Y" ? (this.disableDetails = false) : (this.disableDetails = true);
    },
    handleMark(e) {
      //console.log(e);
      listStorage({ mark: e == 1 ? (e = 2) : (e = 1) }).then((response) => {
        this.markArr = response.rows;
      });
    },
    /** 查询出入库管理列表 */
    getList() {
      this.loading = true;
      listStorage(this.queryParams).then((response) => {
        this.storageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        mark: null,
        deptType: null,
        strategy: null,
        display: null,
        sysState: "N",
        sort: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        pharmacyList: [],
      };
      this.pharmacyListArr = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 树状图选择
    treeCheck(e, v) {
      const checkArr = v.checkedNodes;
      const indexArr = [];
      for (let i in checkArr) {
        let obj = {
          id: checkArr[i].id,
          name: checkArr[i].name,
        };
        indexArr.push(obj);
      }
      this.form.pharmacyList = this.unique(indexArr);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$nextTick(() => {
        this.$refs.treeCheck.setCheckedKeys((this.pharmacyListArr = []));
      });
      this.open = true;
      this.title = "添加出入库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStorage(id).then((response) => {
        if (!response.data.pharmacyList) {
          response.data.pharmacyList = [];
        }

        this.form = response.data;
        response.data.pharmacyList.map((item) => {
          this.pharmacyListArr.push(item.id);
        });
        //console.log("this.$refs.treeCheck", this.$refs.treeCheck);
        this.$nextTick(() => {
          this.$refs.treeCheck.setCheckedKeys(this.pharmacyListArr);
        });
        this.open = true;
        this.title = "修改出入库管理";
      });
    },
    // 去重
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form.range = JSON.stringify(this.form.range);
          if (this.form.id != null) {
            updateStorage(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStorage(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查询药房列表 */
    getMedicalPharmacy() {
      this.loading = true;
      boundary().then((response) => {
        this.MedicalPharmacyList = response.data;
        this.MedicalPharmacyList.forEach(v => {
          v.label = v.name
        })
        // this.MedicalPharmacyList = this.handleTree(
        //   response.data,
        //   "id",
        //   "parentId"
        // );
        // _readNodes(this.MedicalPharmacyList);
        // function _readNodes(nodes = [], arr = []) {
        //   for (let item of nodes) {
        //     item.label = item.label;
        //     item.value = item.id;
        //     if (item.children && item.children.length)
        //       _readNodes(item.children, arr);
        //   }
        // }

        this.loading = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("确定需要删除已选数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delStorage(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有出入库管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportStorage(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
