<template>
  <el-card
    v-loading="loading"
    :body-style="{
      height: '100%',
      padding: 0,
      display: 'flex',
      'flex-direction': 'column',
    }"
  >
    <el-row :gutter="20">
      <el-col :span="6" style="border-right: 1px solid #e9e9e9">
        <el-input
          placeholder="输入关键字/编码进行过滤"
          :size="size"
          v-model="filterText"
          style="margin-bottom: 10px"
        >
        </el-input>

        <el-tree
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          node-key="id"
          @node-click="clickTree"
          highlight-current
          :default-expanded-keys="defaultExpanded"
          :filter-node-method="filterNode"
          ref="tree"
        >
          <span slot-scope="{ node, data }">
            {{ data.code }}{{ data.materialType }}
          </span>
        </el-tree>
      </el-col>

      <el-col :span="18" style="padding: 0 20px">
        <el-row
          style="
            display: flex;
            justify-content: space-between;
            margin: 0 0 30px;
          "
        >
          <el-col style="font-size: 18px; font-weight: 600">详细信息</el-col>
          <el-col style="text-align: right">
            <el-button type="primary" :size="size" @click="mbDownload"
              >模板下载</el-button
            >
            <el-button type="primary" :size="size" @click="importMb"
              >导入</el-button
            >
            <el-button type="primary" :size="size" @click="addClassify"
              >新增</el-button
            >
            <el-button :size="size" @click="editClassify">修改</el-button>
            <el-button :size="size" @click="refreshData">{{
              refreshName ? "全部分类" : "过滤停用"
            }}</el-button>
          </el-col>
        </el-row>

        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="140px"
          class="demo-ruleForm"
        >
          <span class="title">基本信息</span>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物料基本分类编码" prop="code">
                <el-input
                  :disabled="disable"
                  v-model="ruleForm.code"
                  :size="size"
                ></el-input>
                <span>编码规则x-xxx-xxx-xxx</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料基本分类名称" prop="materialType">
                <el-input
                  :disabled="disable"
                  v-model="ruleForm.materialType"
                  :size="size"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="启用状态" prop="isEnable">
                <el-select
                  v-model="ruleForm.isEnable"
                  placeholder="启用状态"
                  :size="size"
                  :disabled="disable"
                  style="width: 230px"
                >
                  <el-option
                    v-for="dict in dict.type.material_enable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品线" prop="productLine" v-if="isFlag">
                <treeselect
                  v-model="ruleForm.productLine"
                  :multiple="false"
                  :options="productOptions"
                  :append-to-body="true"
                  placeholder="请选择产品线"
                  :disabled="disable"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <span class="title">辅助属性</span>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="辅助属性结构" prop="marasstframe">
                <el-select
                  v-model="ruleForm.marasstframe"
                  placeholder="属性结构"
                  clearable
                  :disabled="disable"
                  :size="size"
                  style="width: 230px"
                >
                  <el-option
                    v-for="dict in dict.type.sys_assist_condtion"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="" prop="name">
                  <el-checkbox
                    :disabled="disable"
                    v-model="ruleForm.isInventory"
                    label="isInventory"
                    >库存状态</el-checkbox
                  >
                  <el-checkbox
                    :disabled="disable"
                    v-model="ruleForm.isProductBatch"
                    label="isProductBatch"
                    >产品批号</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row> -->

          <el-row v-if="!disable" style="margin-left: 40px">
            <el-button
              :size="size"
              type="primary"
              @click="submitForm('ruleForm')"
              >保存</el-button
            >
            <el-button :size="size" @click="resetForm('ruleForm')"
              >取消</el-button
            >
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <!-- 导入对话框 -->
    <el-dialog title="数据导入" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="errorFile"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
      </div> -->
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer">
        <el-button :size="size" type="primary" @click="submitFile"
          >确 定</el-button
        >
        <el-button :size="size" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
// 导入的token
import { getToken } from "@/utils/auth";
import {
  getTree,
  getDetail,
  add,
  delClassify,
  edit,
  downLoadClassify,
  getProductLineList,
} from "@/api/classify/basic";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  name: "classify",
  dicts: ["material_enable", "sys_assist_condtion"],
  data() {
    return {
      size: "mini",
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/classify/import",
      },
      loading: false,
      filterText: "",
      data: [],
      defaultProps: {
        children: "childrens",
        label: "materialType",
      },
      ruleForm: {
        code: "",
        materialType: "",
        isEnable: "0",
        delFlag: "",
        marasstframe: "",
        isInventory: "",
        isProductBatch: "",
      },
      rules: {
        code: [
          {
            required: true,
            message: "请输入物料基本分类编码",
            trigger: "blur",
          },
        ],
        materialType: [
          {
            required: true,
            message: "请输入物料基本分类名称",
            trigger: "blur",
          },
        ],
        productLine: [
          {
            required: true,
            message: "请输入产品线",
            trigger: "blur",
          },
        ],
      },
      checkList: [],
      disable: true,
      biao: { parentId: 0 },
      // 删除节点id
      delId: "",
      // 判断是新增还是修改
      isAdd: true,
      defaultExpanded: [],
      // 是否过滤停用
      refreshName: false,
      // 生产线字段判断标志
      isFlag: false,
      // selectTree: [],
      // searchForm: {
      //   componentsName: '', //组件名称
      //   componentsCode: '', //组件编码
      // },
      productOptions: [
        {
          id: 1,
          label: "介入产品线",
        },
        {
          id: 2,
          label: "骨科产品线",
        },
        {
          id: 3,
          label: "检验产品线",
        },
        {
          id: 4,
          label: "综合耗材产品线",
          children: [
            {
              id: 5,
              label: "消毒管控",
            },
            {
              id: 6,
              label: "血统",
            },
            {
              id: 7,
              label: "麻醉",
            },
            {
              id: 8,
              label: "护理",
            },
            {
              id: 9,
              label: "外科",
            },
          ],
        },
        {
          id: 10,
          label: "设备产品线",
        },
      ],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeData();
    this.getProductLine({});
  },
  mounted() {},
  methods: {
    // 获取树形结构
    getTreeData(isEnable) {
      this.loading = true;
      getTree({})
        .then((res) => {
          let { code, rows } = res;
          if (code === 200) {
            this.data = rows;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取物料基本分类详情
    getDetailData(id) {
      getDetail(id).then((res) => {
        let { code, data } = res;
        if (code === 200) {
          console.log("data", data);
          this.isFlag = false;
          if (data.twoClass != null && data.threeClass == null) {
            this.isFlag = true;
          }
          this.ruleForm = data;
          this.ruleForm.isInventory = data.isInventory === "0" ? true : false;
          this.ruleForm.isProductBatch =
            data.isProductBatch === "0" ? true : false;
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return (
        data.materialType.indexOf(value) !== -1 ||
        data.code.indexOf(value) !== -1
      );
    },
    clickTree(data, node) {
      console.log("data", data, node);
      // 如果点击新增时选择了树形节点，则不回显数据,且需要清空ruleForm内的数据
      if (this.disable) {
        this.getDetailData(data.id);
      } else {
        this.$refs["ruleForm"].resetFields();
      }
      // 标记是否为树形结构最外层
      this.biao.parentId = data.id;
      // 将节点id用作删除id
      this.delId = data.id;

      let { id } = data;

      if (this.defaultExpanded.findIndex((item) => item === id) === -1) {
        this.defaultExpanded.push(id);
        this.defaultExpanded = [...new Set(this.defaultExpanded)];
      } else {
        this.defaultExpanded = this.defaultExpanded.filter(
          (item) => item !== id
        );
      }
    },
    submitForm(formName) {
      let isInventory = this.ruleForm.isInventory ? "0" : "2";
      let isProductBatch = this.ruleForm.isProductBatch ? "0" : "2";
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            //判断是走新增还是修改
            console.log("add!");
            console.log(this.biao.parentId);
            console.log(this.ruleForm);
            let params = {
              ...this.ruleForm,
              ...this.biao,
              isInventory,
              isProductBatch,
            };
            console.log("params", params);
            add(params).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getTreeData();
                // this.$refs['ruleForm'].resetFields();
                this.disable = true;
              }
            });
          } else {
            //修改
            console.log("edit");
            let ids = { id: this.biao.parentId };
            console.log("ids", ids);
            let params = {
              ...this.ruleForm,
              ...ids,
              isInventory,
              isProductBatch,
            };
            console.log("params", params);
            edit(params).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getTreeData();
                // this.currentNode = params;
                console.log("this.data", this.defaultExpanded);
                this.disable = true;
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      console.log(formName);
      if (this.isAdd) {
        this.$refs[formName].resetFields();
        this.disable = true;
      } else {
        this.disable = true;
      }
    },
    // 点击新增按钮
    addClassify() {
      // console.log('值呢：', this.ruleForm)
      // 如果点击了树形节点后再点击新增，则清空数据再填写
      if (this.biao.parentId !== 0) {
        this.$refs["ruleForm"].resetFields();
      }
      this.disable = false;
      this.isAdd = true;
    },
    // 删除按钮
    deleteClassify() {
      if (this.biao.parentId == 0) {
        this.$message({
          message: "请选择删除节点",
          type: "warning",
        });
      } else {
        console.log("删除", this.delId);
        delClassify({ id: this.delId }).then((res) => {
          if (res.code === 200) {
            this.getTreeData();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
        });
      }
    },
    // 修改按钮
    editClassify() {
      if (this.biao.parentId == 0) {
        this.$message({
          message: "请选择修改节点",
          type: "warning",
        });
      } else {
        console.log("修改");
        this.disable = false;
        this.isAdd = false;
      }
    },
    // 启用停用
    refreshData() {
      if (this.refreshName == false) {
        this.refreshName = true;
        this.loading = true;
        getTree({ isEnable: "0" })
          .then((res) => {
            let { code, rows } = res;
            if (code === 200) {
              this.data = rows;
            }
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.refreshName = false;
        this.getTreeData();
      }
    },
    // 模板下载
    mbDownload() {
      this.$modal.loading("正在下载模板，请稍后...");
      downLoadClassify({})
        .then((res) => {
          this.$modal.closeLoading();
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          // var temp = res.headers["content-disposition"];
          // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
          // var name = fileName.split(";")[0]; //切割成文件名
          downloadElement.href = href; //下载地址
          downloadElement.download =
            "物料基本分类模板" + this.parseTime(new Date().getTime()) + ".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
          this.download.open = false;
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    // 文件导入
    importMb() {
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$modal.loading("正在导入数据，请稍后...");
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getTreeData();
    },
    errorFile(err) {
      this.$modal.closeLoading();
      this.$modal.notifyError("文件已变动，请重新上传");
    },
    // 提交上传文件
    submitFile() {
      this.$refs.upload.submit();
    },
    // 获取产品线参照
    getProductLine(data) {
      getProductLineList(data).then(res => {
        if (res.code === 200) {
          this.productOptions = res.data;
        } else {
          this.$modal.error("获取产品线参照失败！");
        }
      })
    }
  },
};
</script>

<style scoped lang="scss">
.el-card {
  width: calc(100% - 32px);
  height: calc(100vh - 32px);
  margin: 16px;
  padding: 16px;
  border-radius: 8px;
}
.title {
  font-weight: bold;
}
.filter-tree {
  height: calc(100vh - 102px);
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
