
<template>
  <div class="page">
    <el-dialog
      title="导入物料"
      :visible.sync="materiaImportDialog.visible"
      width="600px"
    >
      <div>
        <Upload type="file" tip="导入EXCEL文件" v-model="attachUrl"></Upload>

        <br />
        <a
          class="download"
          style="float: right"
          href="/materia.xls"
          download
          title="下载"
          >模板下载</a
        >
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="materiaImportDialog.visible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="doImportExcel">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="物料类目"
      :visible.sync="materiaDirDialog.visible"
      width="50%"
    >
      <el-form
        :model="dirform"
        :label-width="formLabelWidth"
        :rules="rules"
        ref="dirform"
      >
        <el-row>
          <el-form-item label="类目代码" v-if="dirform.id != null">
            <el-input v-model="dirform.code" disabled></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item prop="name" label="类目名称">
            <el-input v-model.trim="dirform.name"></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="备注">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="materiaDirDialog.visible = false">取 消</el-button>

        <el-button
          type="primary"
          :disabled="(submitButtonDisabled = false)"
          @click="submitDirForm"
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="附件"
      :visible.sync="materiaAttsDialog.visible"
      width="50%"
    >
      <el-form
        :model="attform"
        :label-width="formLabelWidth"
        :rules="attRules"
        ref="attform"
      >
        <!-- <el-row>
          <el-form-item prop="attachName" label="附件名称">
            <el-input v-model.trim="attform.attachName"></el-input>
          </el-form-item>
        </el-row> -->

        <el-row>
          <el-form-item prop="attachType" label="附件分类">
            <el-select
              style="width: 100%"
              v-model="attform.attachType"
              placeholder="请选择附件种类"
            >
              <el-option
                v-for="($label, $value) in tableData.dict.attachType"
                :key="$value"
                :label="$label"
                :value="$value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item prop="attachUrl" label="附件">
            <el-upload
              class="upload-demo"
              action="/m/file/upload"
              :on-success="handleAttsSuccess"
              name="uploadFile"
              :data="{ prePath: '/image/plm/materia' }"
              :limit="1"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="备注">
            <el-input v-model="attform.remark" prop="remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="materiaAttsDialog.visible = false">取 消</el-button>

        <el-button
          type="primary"
          :disabled="(submitButtonDisabled = false)"
          @click="submitAttsForm"
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="物料供应"
      :visible.sync="materiaSupplyDialog.visible"
      width="50%"
    >
      <el-form
        :model="supplyform"
        :label-width="formLabelWidth"
        :rules="supplyRules"
        ref="supplyform"
      >
        <el-row>
          <el-form-item prop="supplierId" label="物料供应商">
            <el-select
              style="width: 100%"
              v-model="supplyform.supplierId"
              placeholder="请选择物料供应商"
            >
              <el-option
                v-for="($label, $value) in tableData.dict.supplierId"
                :key="$value"
                :label="$label"
                :value="$value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="deliveryPeriod" label="交货期">
              <el-input v-model="supplyform.deliveryPeriod"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="deliveryPeriodUnit" label="交货期单位">
              <el-select
                style="width: 100%"
                v-model="supplyform.deliveryPeriodUnit"
                placeholder="请选择交货期单位"
              >
                <el-option
                  v-for="($label, $value) in tableData.dict.deliveryPeriodUnit"
                  :key="$value"
                  :label="$label"
                  :value="$value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="costPlan" label="供货成本">
              <el-input v-model.trim="supplyform.costPlan">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="unitOfMeasure" label="计量单位">
              <el-select
                style="width: 100%"
                v-model="supplyform.unitOfMeasure"
                placeholder="请选择计量单位"
              >
                <el-option
                  v-for="($label, $value) in tableData.dict.unitOfMeasure"
                  :key="$value"
                  :label="$label"
                  :value="$value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="供应商物料代码">
            <el-input v-model="supplyform.supplierMateriaCode"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="materiaSupplyDialog.visible = false"
          >取 消</el-button
        >

        <el-button
          type="primary"
          :disabled="(submitButtonDisabled = false)"
          @click="submitSupplyForm"
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="物料" :visible.sync="materiaDialog.visible" width="50%">
      <el-form
        :model="form"
        :label-width="formLabelWidth"
        :rules="materiaRules"
        ref="form"
      >
        <el-row v-if="form.id != null">
          <el-form-item prop="code" label="物料代码">
            <el-input v-model="form.code" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="name" label="物料名称">
            <el-input v-model.trim="form.name"></el-input>
          </el-form-item>
        </el-row>
        <el-row v-if="form.id != null">
          <el-form-item prop="assetsCode" label="资产编码">
            <el-input v-model.trim="form.assetsCode"></el-input>
          </el-form-item>
        </el-row>
        <el-form-item prop="categoryId" label="物料类目">
          <el-input
            :value="
              tableData.dict.categoryId
                ? tableData.dict.categoryId[form.categoryId]
                : ''
            "
            disabled
          >
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="specModel" label="规格型号">
              <el-input v-model.trim="form.specModel"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="useNum" label="物料用量">
              <el-input
                v-model.trim="form.useNum"
                onkeyup="value=value.replace(/[^\d]/g,'')"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="unitOfMeasure" label="计量单位">
              <el-select
                style="width: 100%"
                v-model="form.unitOfMeasure"
                placeholder="请选择计量单位"
              >
                <el-option
                  v-for="($label, $value) in tableData.dict.unitOfMeasure"
                  :key="$value"
                  :label="$label"
                  :value="$value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="lossRate" label="损耗率">
              <el-input
                v-model="form.lossRate"
                onkeyup="value=value.replace(/[^\d]/g,'')"
                placeholder="0-100"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="supplyType" label="补给方式">
              <el-select
                style="width: 100%"
                v-model="form.supplyType"
                placeholder="请选择计量单位"
              >
                <el-option
                  v-for="($label, $value) in tableData.dict.supplyType"
                  :key="$value"
                  :label="$label"
                  :value="$value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="costPlan" label="计划成本">
              <el-input
                v-model="form.costPlan"
                onkeyup="value=value.replace(/[^0-9.]/g,'')"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item prop="mainPicUrl" label="图片">
            <el-upload
              class="avatar-uploader"
              action="/m/file/upload"
              :show-file-list="false"
              :on-success="handleSuccess"
              name="uploadFile"
              :data="{ prePath: '/image/plm/materia' }"
              :before-upload="beforeUpload"
            >
              <img
                v-if="form.mainPicUrl"
                :src="form.mainPicUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- 
            <Upload type="thumb" v-model="form.mainPicUrl"></Upload> -->
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
        </el-row>

        <el-row
          v-for="($label, $value) in tableData.dict.extField"
          :key="$value"
        >
          <el-form-item :label="$label">
            <el-input v-model="form[$value]"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="materiaDialog.visible = false">取 消</el-button>

        <el-button
          type="primary"
          :disabled="(submitButtonDisabled1 = false)"
          @click="submitForm"
          >保 存</el-button
        >
      </span>
    </el-dialog>
    <el-row gutter="20">
      <el-col :span="6" class="el-row-filter">
        <el-row :span="24" style="height: 40px">
          <el-tooltip effect="light" content="新增同级目录">
            <el-button
              @click="addDir"
              icon="el-icon-plus"
              size="mini"
              circle
            ></el-button>
          </el-tooltip>

          <el-tooltip effect="light" content="新增子级目录">
            <el-button
              circle
              @click="addDirChild"
              icon="el-icon-folder-add"
              size="mini"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="light" content="编辑当前目录">
            <el-button
              circle
              @click="editDir"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
          </el-tooltip>
        </el-row>
        <el-divider style="height: 10px"></el-divider>
        <div id="dataPage" style="height: 540px" class="mytree">
          <el-scrollbar style="height: 100%">
            <el-tree
              size="mini"
              ref="categoryTree"
              id="el-tree"
              :data="data"
              node-key="id"
              indent="0"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              :props="treeProps"
              :load="loadNode"
              :render-content="renderContent"
              highlight-current
              lazy
            >
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="18">
        <el-row v-if="isShowSearch">
          <el-form :inline="true" size="mini">
            <el-form-item label="物料代码">
              <el-input
                v-model="searchform.code"
                placeholder="物料代码"
              ></el-input>
            </el-form-item>

            <el-form-item label="物料名称">
              <el-input
                v-model="searchform.name"
                placeholder="物料名称"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button plain @click="searchConfirm">查询</el-button>
            </el-form-item>
          </el-form>
        </el-row>

        <el-row style="margin-bottom: 5px">
          <el-tooltip effect="light" content="搜索">
            <el-button
              circle
              icon="el-icon-search"
              @click="search"
              size="mini"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="light" content="新增物料">
            <el-button
              circle
              icon="el-icon-plus"
              size="mini"
              @click="addMateria"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="light" content="导入物料">
            <el-button
              circle
              icon="el-icon-upload2"
              @click="doImportOpen"
              size="mini"
            ></el-button>
          </el-tooltip>
        </el-row>

        <div>
          <el-table
            size="mini"
            v-loading="loading"
            :data="materiaTableData"
            @row-click="clickTableRow"
            border
            highlight-current-row
          >
            <el-table-column prop="code" label="物料代码"> </el-table-column>

            <el-table-column prop="name" label="物料名称"> </el-table-column>
            <el-table-column prop="specModel" label="规格型号">
            </el-table-column>
            <el-table-column prop="categoryName" label="类目">
            </el-table-column>

            <el-table-column
              prop="unitOfMeasure"
              :formatter="formatter"
              label="计量单位"
            >
            </el-table-column>
            <el-table-column prop="useNum" label="默认用量"> </el-table-column>
            <el-table-column
              prop="supplyType"
              :formatter="formatter"
              label="补给方式"
            >
            </el-table-column>
            <el-table-column
              prop="costPlan"
              :formatter="formatterMoney"
              label="计划成本"
            >
            </el-table-column>

            <el-table-column prop="mainPicUrl" label="图片">
              <!-- 图片的显示 -->
              <!-- <template slot-scope="scope">
                <img :src="scope.row.mainPicUrl" min-width="70" height="70" />
              </template> -->

              <template slot-scope="scope">
                <el-popover trigger="click" placement="top">
                  <img
                    :src="scope.row.mainPicUrl"
                    style="width: auto; height: 400px"
                  />
                  <div slot="reference" class="name-wrapper">
                    <img
                      :src="scope.row.mainPicUrl"
                      min-width="70"
                      height="70"
                    />
                    <!-- <el-tag size="medium">{{ scope.row.name }}</el-tag> -->
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column prop="enabled" :formatter="formatter" label="启用">
            </el-table-column>

            <el-table-column label="物料供应">
              <template slot-scope="scope">
                <el-popover
                  v-if="
                    scope.row.supplierEntities &&
                    scope.row.supplierEntities.length > 0
                  "
                  trigger="hover"
                  placement="top"
                >
                  <p
                    v-for="(item, index) in scope.row.supplierEntities"
                    :key="index"
                  >
                    供应商：{{ scope.row.supplierEntities[index].supplierName }}
                  </p>

                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{
                      scope.row.supplierEntities.length > 0 ? "供应商" : "无"
                    }}</el-tag>
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column label="相关附件">
              <template slot-scope="scope">
                <el-popover
                  trigger="hover"
                  v-if="
                    scope.row.attachEntityList &&
                    scope.row.attachEntityList.length > 0
                  "
                  width="200"
                  placement="top"
                >
                  <el-table :data="scope.row.attachEntityList">
                    <el-table-column
                      prop="attachUrl"
                      :formatter="formatterLink"
                      label="下载地址"
                    />
                  </el-table>

                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{
                      scope.row.attachEntityList &&
                      scope.row.attachEntityList.length > 0
                        ? "附件"
                        : "无"
                    }}</el-tag>
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <!-- 
            <el-table-column  prop="remark" label="备注"> </el-table-column> -->

            <el-table-column width="120" fixed="right" label="操作">
              <template slot-scope="scope">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-tooltip effect="light" content="编辑物料">
                      <el-button
                        circle
                        icon="el-icon-edit"
                        size="mini"
                        @click="handleMateriaEdit(scope.$index, scope.row)"
                      ></el-button> </el-tooltip
                  ></el-col>
                  <el-col :span="8">
                    <el-tooltip effect="light" content="添加供应商">
                      <el-button
                        circle
                        icon="el-icon-files"
                        size="mini"
                        @click="handleMateriaSupply(scope.$index, scope.row)"
                      ></el-button> </el-tooltip
                  ></el-col>
                  <el-col :span="8">
                    <el-tooltip effect="light" content="添加附件">
                      <el-button
                        circle
                        icon="el-icon-tickets"
                        size="mini"
                        @click="handleMateriaAtts(scope.$index, scope.row)"
                      ></el-button> </el-tooltip
                  ></el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-tooltip effect="light" content="添加资产码">
                      <el-button
                        circle
                        icon="el-icon-coin"
                        size="mini"
                        @click="handleMateriaAsset(scope.$index, scope.row)"
                      ></el-button> </el-tooltip
                  ></el-col>
                  <el-col :span="8">
                    <el-tooltip effect="light" content="物料废弃">
                      <el-button
                        circle
                        icon="el-icon-delete"
                        size="mini"
                        @click="handleMateriaDiscard(scope.$index, scope.row)"
                      ></el-button> </el-tooltip
                  ></el-col>
                  <el-col :span="8"></el-col>
                </el-row>
              </template>
            </el-table-column>
            -

            <el-table-column
              width="100"
              v-for="($label, $value) in tableData.dict.extField"
              :key="$value"
              :prop="$value"
              :label="$label"
            >
            </el-table-column>
          </el-table>
        </div>
        <el-row>
          <!-- 分页器 -->
          <div class="table-foot">
            <Pagination
              :total="tableData.pageInfo.totalResult"
              :prePageResult="tableData.pageInfo.prePageResult"
            />
          </div>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>



<script>
import Pagination from "@/components/Pagination.vue";
import treemenu from "@/assets/mixins/treemenu";
import table from "@/assets/mixins/table";
import menuContext from "@/components/menuContext.vue";

export default {
  components: {
    menuContext,
    Pagination,
  },
  name: "index",
  mixins: [table, treemenu],
  mounted() {
    //dom加载完，进行目标dom的设置，直接在data中赋值，会找不到dom
    this.$nextTick(() => {
      this.contextMenuTarget = document.querySelector("#el-tree");
    });
    setTimeout(() => {
      this.loading = false;
    }, 1000);
  },

  created() {
    this.$post("/materia/add", {});

    //初始化获取根节点
    this.$post("/materia/category/getListByParentId", {
      parentId: -1,
    }).then(({ data }) => {
      this.data = data.result;
    });
  },
  methods: {
    handleAttsSuccess(response, file, fileList) {
      let code = response.code;
      if (code === 1) {
        this.attform.attachUrl = response.url;
        this.attform.attachName = file.name;
      } else {
        this.$message.error("上传文件失败");
      }
      console.log(this.attform);
    },

    handleMateriaEdit(index, row) {
      console.log(index, row);
      this.tableRowData = row;
      this.editMateria();
    },

    handleMateriaSupply(index, row) {
      console.log(index, row);
      this.tableRowData = row;
      this.addMateriaSupply();
    },

    handleMateriaAtts(index, row) {
      console.log(index, row);
      this.tableRowData = row;
      this.addMateriaAtts();
    },

    handleMateriaAsset(index, row) {
      console.log(index, row);
      this.tableRowData = row;

      this.$prompt("请输入资产码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.$post("/materia/updateAsset", {
            id: this.tableRowData.id,
            asset: value,
          })
            .then((res) => {
              if (res && res.code && res.code == 1) {
                this.$message({
                  type: "success",
                  message: "修改资产码成功: ",
                });
              }
            })
            .catch((error) => {
              // _this.$message.error(error.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },

    handleMateriaDiscard(index, row) {
      console.log(index, row);
      this.tableRowData = row;
      this.discardMateria();
    },

    discardMateria() {
      console.log("discard materia");

      if (!this.tableRowData.id) {
        this.$message.info("请选择需要废弃的物料项！");
        return;
      }

      this.$confirm("此操作将永久废弃该物料, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$post("/materia/discard", {
            id: this.tableRowData.id,
          })
            .then((res) => {
              if (res && res.code && res.code == 1) {
                this.loading = true;
                this.initPage();
                this.loading = false;
                // _this.$message.success("物料废弃成功！");
              }
            })
            .catch((error) => {
              // _this.$message.error(error.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消废弃!",
          });
        });
    },
    doImportOpen() {
      this.materiaImportList = [];
      this.fileList3 = [];
      this.attachUrl = "";
      // console.log(this.fileList3);
      this.materiaImportDialog.visible = true;
    },

    /**
     * 提交物料导入
     */
    doImportExcel() {
      if (this.attachUrl === "") {
        this.$message.error("请上传物料导入文件！");
        return;
      }

      this.loading = true;
      this.$post("/materia/doImportExcel", { path: this.attachUrl }, {})
        .then((res) => {
          if (res && res.code && res.code == 1) {
            if (res.msg && res.msg != "") {
              this.$alert(res.msg, "导入结果提示：", {
                dangerouslyUseHTMLString: true,
              });
            } else {
              this.$message.info("物料导入成功！");
            }
            this.$post("/materia/list", {}).then(({ data }) => {
              this.materiaTableData = data.result;
              this.initPage(data);
            });
          } else {
            this.$message.info(res.msg);
          }
            this.loading = false;
        })
        .catch((error) => {
            this.loading = false;
          this.$message.error(error.message);
        });
    
      this.materiaImportDialog.visible = false;
    },

    //上传前图片数据校验
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error("上传图片必须是JPG/GIF/PNG/BMP 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG || isBMP || isGIF || isPNG;
    },
    handleSuccess(res, file) {
      this.$message({
        type: "success",
        message: "图片上传成功",
        duration: 6000,
      });
      this.form.mainPicUrl = res.url;
    },

    search() {
      //this.searchform = {};
      if (this.isShowSearch) {
        this.isShowSearch = false;
      } else {
        this.isShowSearch = true;
      }
    },
    searchConfirm() {
      let { path, query } = this.$route;
      this.query = {
        "query.code": this.searchform.code,
        "query.name": this.searchform.name,
      };
      if (this.radio) {
        this.radio = null;
        this.tableRowData = {};
      }
      this.getData();
    },
    refreshNodeBy(id) {
      let node = this.$refs.categoryTree.getNode(id); // 通过节点id找到对应树节点对象
      node.loaded = false;
      node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
    },

    handleNodeClick(data) {
      console.log("handleNodeClick", data);
      // let { path, query } = this.$route;
      // console.log(path, query);
      // let type = data.type;
      // let children = data.children;
      this.thisformdata = data; //按需展示不同的按钮
      if (data.type == 0) {
        let { path, query } = this.$route;
        this.query = Object.assign({}, query, {
          "query.categoryId": this.thisformdata.id,
        });
        if (this.radio) {
          this.radio = null;
          this.tableRowData = {};
        }
        this.loading = true;
        this.getData();
        this.loading = false;
      }
    },

    initPage() {
      let { path, query } = this.$route;
      this.query = Object.assign({}, query, {
        "query.categoryId": this.thisformdata.id,
      });
      this.getData();
    },

    renderContent: function (h, { node, data, store }) {
      return (
        <span>
          <i style="font-size:16px;color:#409EFF" class={data.icon}></i>
          <span style="padding-left: 2px;font-size:14px">{node.label}</span>
        </span>
      );
    },
    // 提交表单
    submitForm(ref) {
      if (this.submitButtonDisabled) {
        return;
      }
      const el = this.$refs.form;
      el.validate((valid) => {
        if (!valid) return;
        this.submitButtonDisabled = true;
        this.loading = true;
        this.$post("/materia/save", {
          entity: {
            ...this.form,
            costPlan: parseInt(parseFloat(this.form.costPlan) * 1000 + ""),
          },
        })
          .then((res) => {
            // this.refreshNodeBy(this.form.categoryId);
            this.materiaDialog.visible = false;
            if (res && res.code && res.code == 1) {
              this.$message.success(res.msg);

              this.initPage();
            }
            this.initForm();
            this.radio = null;
            this.loading = false;
          })
          .catch((error) => {
            this.submitButtonDisabled = false;
            this.loading = false;
            this.$message.error(error.message);
          });
      });
    },

    // 提交表单
    submitDirForm(ref) {
      if (this.submitButtonDisabled) {
        return;
      }
      const el = this.$refs.dirform;
      el.validate((valid) => {
        if (!valid) return;
        this.submitButtonDisabled = true;
        this.$post("/materia/category/save", {
          entity: this.dirform,
        })
          .then((res) => {
            //  this.getData();
            this.materiaDirDialog.visible = false;

            if (res && res.code && res.code == 1) {
              //this.$message.success(res.msg);
              this.initForm();
              console.log(this.thisformdata);
              if (!JSON.stringify(this.thisformdata) == "{}") {
                if (this.isChildDir) {
                  this.refreshNodeBy(this.thisformdata.id);
                } else {
                  this.refreshNodeBy(this.thisformdata.parentId);
                }
              } else {
                this.$post("/materia/category/getListByParentId", {
                  parentId: -1,
                }).then(({ data }) => {
                  this.data = data.result;
                });
              }
              this.initPage();
            }
          })
          .catch((error) => {
            this.submitButtonDisabled = false;
            this.$message.error(error.message);
          });
      });
    },

    // 提交表单
    submitAttsForm(ref) {
      if (this.submitButtonDisabled) {
        return;
      }
      const el = this.$refs.attform;
      el.validate((valid) => {
        if (!valid) return;
        this.submitButtonDisabled = true;
        this.$post("/attach/save", {
          entity: this.attform,
        })
          .then((res) => {
            this.materiaAttsDialog.visible = false;

            if (res && res.code && res.code == 1) {
              this.$message.success("添加附件成功！");
              this.initForm();
            }
          })
          .catch((error) => {
            this.submitButtonDisabled = false;
            this.$message.error(error.message);
          });
      });
    },

    submitSupplyForm(ref) {
      if (this.submitButtonDisabled) {
        return;
      }
      const el = this.$refs.supplyform;
      el.validate((valid) => {
        if (!valid) return;
        this.submitButtonDisabled = true;
        this.$post("/materia/supplier/save", {
          entity: {
            ...this.supplyform,
            costPlan: parseInt(
              parseFloat(this.supplyform.costPlan) * 1000 + ""
            ),
          },
        })
          .then((res) => {
            this.materiaSupplyDialog.visible = false;

            if (res && res.code && res.code == 1) {
              this.$message.success("添加物料供应商成功！");

              this.initForm();

              this.initPage();
            }
          })
          .catch((error) => {
            this.submitButtonDisabled = false;
            this.$message.error(error.message);
          });
      });
    },

    beforeRender(data) {
      this.materiaTableData = data.result;
      return data;
    },

    async loadNode(node, resolve) {
      console.log("node:", node);
      console.log(this.data);

      if (node.level === 0) {
        resolve(this.data);
        return;
      }
      this.$post("/materia/category/getDirListByParentId", {
        parentId: node.data.id,
        type: node.data.type,
      }).then(({ data }) => {
        resolve(data.result);
        // this.bomTableData = data.bomList;
      });
    },
    // table的左键点击当前行事件
    clickTableRow(row, column, event) {
      console.log("clickTableRow row", row);
      this.tableRowData = row;
      // this.materiaTableData.forEach((item, index) => {
      //   if (row.code === item.code) {
      //     this.radio = parseInt(index) + 1;
      //   }
      // });
    },

    initForm() {
      this.form = {
        id: null,
        name: "",
        shortName: "",
        selfCode: "",
        code: "",
        assetsCode: "",
        categoryId: "1",
        enabled: 1,
        specModel: "",
        unitOfMeasure: "",
        useNum: "1",
        lossRate: "",
        supplyType: "",
        costPlan: "",
        mainPicUrl: "",
        remark: "",
      };

      this.dirform = {
        id: null,
        parentId: -1,
        code: "",
        selfCode: "",
        name: "",
        enabled: "1",
        isLeaf: 1,
        startNum: 1,
        remark: "",
      };

      this.supplyform = {
        id: null,
        materiaId: "",
        supplierId: "",
        deliveryPeriod: "",
        deliveryPeriodUnit: "",
        supplierMateriaCode: "",
        unitOfMeasure: "",
        costPlan: "",
      };

      (this.attform = {
        id: null,
        tableCode: "mortals_iot_materia",
        tableDataId: "",
        attachType: "",
        attachName: "",
        attachUrl: "",
        remark: "",
      }),
        this.$post("/materia/add", {});
    },
  },

  data() {
    return {
      loading: false,
      materiaDialog: {
        visible: false,
      },
      materiaDirDialog: {
        visible: false,
      },
      materiaAttsDialog: {
        visible: false,
      },
      materiaSupplyDialog: {
        visible: false,
      },
      materiaImportDialog: {
        visible: false,
        syncRet: "",
      },
      attachUrl: "",
      form: {},
      fileList: [],

      dirform: {},
      attform: {},
      supplyform: {},
      searchform: {
        code: "",
        name: "",
      },
      formLabelWidth: "120px",
      formInputWidth: "20",
      radio: null,
      materiaTableData: [],
      currentRowIndex: 0, // 获取当前右键点击的table行下标
      data: [],
      fileList3: [],
      materiaList: [],
      currCategory: {},
      treeProps: {
        children: "children",
        label: "name",
        isLeaf: "isLeaf",
        type: "type",
        icon: "icon",
        id: "id",
      },
      submitButtonDisabled: false,
      isChildDir: false, //刷新标志
      isShowDrop: false, //右键菜单的是否显示
      contextMenuTarget: null, //右键菜单的DOM对象
      thisformdata: {}, //右键菜单的点击的节点对象
      targetElement: {}, //右键点击的目标对象
      isShowSearch: false,
      tableRowData: {},
      rules: {
        name: [
          {
            required: true,
            message: "请输入类目名称",
            trigger: "blur",
          },
        ],
        selfCode: [
          {
            required: true,
            message: "请输入类目短代码",
            trigger: "blur",
          },
        ],
      },

      attRules: {
        attachType: [
          {
            required: true,
            message: "请选择附件类型",
            trigger: "blur",
          },
        ],
        attachUrl: [
          {
            required: true,
            message: "请上传附件",
            trigger: "blur",
          },
        ],
      },

      supplyRules: {
        supplierId: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "blur",
          },
        ],
        deliveryPeriod: [
          {
            required: true,
            message: "请输入交货期",
            trigger: "blur",
          },
        ],
        deliveryPeriodUnit: [
          {
            required: true,
            message: "请交货期单位",
            trigger: "blur",
          },
        ],

        unitOfMeasure: [
          {
            required: true,
            message: "请选择计量单位",
            trigger: "blur",
          },
        ],

        costPlan: [
          {
            required: true,
            message: "请输入供货成本",
            trigger: "blur",
          },
        ],
      },
      materiaRules: {
        name: [
          {
            required: true,
            message: "请输入物料名称",
            trigger: "blur",
          },
          { max: 50, message: "物料名称最大长度50个字符", trigger: "blur" },
        ],
        shortName: [
          {
            required: true,
            message: "请输入物料简称",
            trigger: "blur",
          },
        ],
        assetsCode: [
          {
            required: false,
            message: "请输入资产编码",
            trigger: "blur",
          },
        ],
        categoryId: [
          {
            required: true,
            message: "请选择物料类目",
            trigger: "blur",
          },
        ],
        useNum: [
          {
            required: true,
            message: "请输入用量",
            trigger: "blur",
          },
        ],
        lossRate: [
          {
            required: true,
            message: "请输入损耗率",
            trigger: "blur",
          },
        ],
        specModel: [
          {
            required: true,
            message: "请输入规格型号",
            trigger: "blur",
          },
        ],
        unitOfMeasure: [
          {
            required: true,
            message: "请输入计量单位",
            trigger: "blur",
          },
        ],
        supplyType: [
          {
            required: true,
            message: "请选择补给方式",
            trigger: "blur",
          },
        ],

        costPlan: [
          {
            required: true,
            message: "请输入计划成本",
            trigger: "blur",
          },
        ],
        mainPicUrl: [
          {
            required: true,
            message: "请选择图片",
            trigger: "blur",
          },
        ],
      },
    };
  },
};
</script>
<style>
.winClass {
  width: 500px;
  height: 200px;
  overflow-y: auto;
}
/* el-divider 修改高度&虚线效果 */
.el-divider--horizontal {
  margin: 5px 0;
  background: 0 0;
  border-top: 1px solid #e8eaec;
}
.el-row-filter {
  max-height: 600px;
  height: 600px;
  overflow: auto;
}
.table-foot {
  width: 100%;
  overflow: auto;
}

#dataPage {
  margin: 0 0;
  font-family: "Microsoft Yahei", "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  height: 100%;
}

.el-scrollbar .el-scrollbar__wrap .el-scrollbar__view {
  overflow-y: hidden;
  overflow-x: hidden;
}
.el-radio__label {
  display: none !important;
}
</style>


<style lang="scss" scoped>
.el-select {
  width: 130px;
}

.mytree /deep/ {
  .el-tree--highlight-current
    /deep/
    .el-tree-node.is-checked
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }
  .el-tree--highlight-current
    /deep/
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }
  .el-tree > .el-tree-node:after {
    border-top: none;
  }
  .el-tree-node {
    position: relative;
    padding-left: 16px;
  }
  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  // .el-tree-node__expand-icon.is-leaf {
  //   display: none;
  // }
  .el-tree-node__children {
    padding-left: 16px;
  }

  .el-tree-node :last-child:before {
    height: 38px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #4386c6;
    bottom: 0px;
    height: 100%;
    top: -26px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #4386c6;
    height: 20px;
    top: 12px;
    width: 24px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding-right: 8px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
